* @brief Atomic write of the full alarmBands array onto a dataset. */
| 2561 | * @brief Atomic write of the full alarmBands array onto a dataset. |
| 2562 | */ |
| 2563 | API::CommandResponse API::Handlers::ProjectHandler::datasetSetAlarmBands(const QString& id, |
| 2564 | const QJsonObject& params) |
| 2565 | { |
| 2566 | const QStringList required{ |
| 2567 | QString(Keys::GroupId), QString(Keys::DatasetId), QString(Keys::AlarmBands)}; |
| 2568 | for (const auto& key : required) |
| 2569 | if (!params.contains(key)) |
| 2570 | return CommandResponse::makeError( |
| 2571 | id, ErrorCode::MissingParam, QStringLiteral("Missing required parameter: %1").arg(key)); |
| 2572 | |
| 2573 | const int groupId = params.value(Keys::GroupId).toInt(); |
| 2574 | const int datasetId = params.value(Keys::DatasetId).toInt(); |
| 2575 | const auto arr = params.value(Keys::AlarmBands).toArray(); |
| 2576 | |
| 2577 | auto& pm = DataModel::ProjectModel::instance(); |
| 2578 | const auto& groups = pm.groups(); |
| 2579 | const auto git = std::find_if( |
| 2580 | groups.begin(), groups.end(), [groupId](const auto& g) { return g.groupId == groupId; }); |
| 2581 | |
| 2582 | if (git == groups.end()) |
| 2583 | return CommandResponse::makeError( |
| 2584 | id, ErrorCode::InvalidParam, QStringLiteral("Group id not found: %1").arg(groupId)); |
| 2585 | |
| 2586 | const auto& datasets = git->datasets; |
| 2587 | const auto dit = std::find_if(datasets.begin(), datasets.end(), [datasetId](const auto& d) { |
| 2588 | return d.datasetId == datasetId; |
| 2589 | }); |
| 2590 | |
| 2591 | if (dit == datasets.end()) |
| 2592 | return CommandResponse::makeError(id, |
| 2593 | ErrorCode::InvalidParam, |
| 2594 | QStringLiteral("Dataset id not found in group: %1/%2") |
| 2595 | .arg(QString::number(groupId), QString::number(datasetId))); |
| 2596 | |
| 2597 | DataModel::Dataset updated = *dit; |
| 2598 | updated.alarmBands.clear(); |
| 2599 | updated.alarmBands.reserve(arr.size()); |
| 2600 | |
| 2601 | int dropped = 0; |
| 2602 | for (const auto& v : arr) { |
| 2603 | DataModel::AlarmBand b; |
| 2604 | if (DataModel::read(b, v.toObject())) |
| 2605 | updated.alarmBands.push_back(std::move(b)); |
| 2606 | else |
| 2607 | ++dropped; |
| 2608 | } |
| 2609 | |
| 2610 | pm.updateDataset(groupId, datasetId, updated, true); |
| 2611 | |
| 2612 | QJsonObject result; |
| 2613 | result[Keys::GroupId] = groupId; |
| 2614 | result[Keys::DatasetId] = datasetId; |
| 2615 | result[QStringLiteral("count")] = static_cast<int>(updated.alarmBands.size()); |
| 2616 | result[QStringLiteral("updated")] = true; |
| 2617 | if (dropped > 0) |
| 2618 | result[QStringLiteral("droppedInvalid")] = dropped; |
| 2619 | |
| 2620 | return CommandResponse::makeSuccess(id, result); |