group_service.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. #include "smartbotic/webserver/group_service.hpp"
  2. #include <spdlog/spdlog.h>
  3. #include <chrono>
  4. #include <functional>
  5. #include <iomanip>
  6. #include <sstream>
  7. #include <unordered_set>
  8. namespace smartbotic::webserver {
  9. namespace {
  10. auto SetStringValue(::smartbotic::database::MapValue* map, const std::string& key, const std::string& value) {
  11. auto* field = &(*map->mutable_fields())[key];
  12. field->set_string_value(value);
  13. }
  14. auto SetArrayValue(::smartbotic::database::MapValue* map, const std::string& key, const std::vector<std::string>& values) {
  15. auto* field = &(*map->mutable_fields())[key];
  16. auto* array = field->mutable_array_value();
  17. for (const auto& value : values) {
  18. array->add_values()->set_string_value(value);
  19. }
  20. }
  21. auto GetStringValue(const ::smartbotic::database::MapValue& map, const std::string& key) -> std::string {
  22. auto it = map.fields().find(key);
  23. if (it != map.fields().end() && it->second.has_string_value()) {
  24. return it->second.string_value();
  25. }
  26. return "";
  27. }
  28. auto GetArrayValue(const ::smartbotic::database::MapValue& map, const std::string& key) -> std::vector<std::string> {
  29. std::vector<std::string> result;
  30. auto it = map.fields().find(key);
  31. if (it != map.fields().end() && it->second.has_array_value()) {
  32. for (const auto& value : it->second.array_value().values()) {
  33. if (value.has_string_value()) {
  34. result.push_back(value.string_value());
  35. }
  36. }
  37. }
  38. return result;
  39. }
  40. auto GetBoolValue(const ::smartbotic::database::MapValue& map, const std::string& key) -> bool {
  41. auto it = map.fields().find(key);
  42. if (it != map.fields().end() && it->second.has_bool_value()) {
  43. return it->second.bool_value();
  44. }
  45. return false;
  46. }
  47. auto SetBoolValue(::smartbotic::database::MapValue* map, const std::string& key, bool value) {
  48. auto* field = &(*map->mutable_fields())[key];
  49. field->set_bool_value(value);
  50. }
  51. } // namespace
  52. GroupService::GroupService(DatabaseClient& db_client) : db_client_(db_client) {}
  53. GroupService::~GroupService() = default;
  54. // Move operations not supported due to reference member
  55. GroupService::GroupService(GroupService&& other) noexcept
  56. : db_client_(other.db_client_), initialized_(other.initialized_) {}
  57. auto GroupService::operator=(GroupService&& /*other*/) noexcept -> GroupService& {
  58. // Cannot reassign reference member, so this is essentially a no-op
  59. return *this;
  60. }
  61. auto GroupService::Initialize() -> bool {
  62. if (initialized_) {
  63. return true;
  64. }
  65. auto* collection_service = db_client_.GetCollectionService();
  66. if (collection_service == nullptr) {
  67. spdlog::error("Collection service not available");
  68. return false;
  69. }
  70. // Check if _groups collection exists
  71. ::smartbotic::database::GetCollectionMetadataRequest get_req;
  72. get_req.set_name(kCollectionName);
  73. grpc::ClientContext get_ctx;
  74. ::smartbotic::database::CollectionMetadata metadata;
  75. auto status = collection_service->GetCollectionMetadata(&get_ctx, get_req, &metadata);
  76. if (status.ok()) {
  77. spdlog::info("System collection {} already exists", kCollectionName);
  78. } else {
  79. // Collection doesn't exist, create it
  80. ::smartbotic::database::CreateCollectionRequest create_req;
  81. create_req.set_name(kCollectionName);
  82. // Add compound index on workspace_id + name for uniqueness within workspace
  83. auto* name_index = create_req.add_indexes();
  84. name_index->set_collection(kCollectionName);
  85. name_index->set_index_name("workspace_name_unique");
  86. name_index->add_fields("workspace_id");
  87. name_index->add_fields("name");
  88. name_index->set_unique(true);
  89. name_index->set_type(::smartbotic::database::INDEX_TYPE_HASH);
  90. grpc::ClientContext create_ctx;
  91. ::smartbotic::database::CollectionMetadata created_metadata;
  92. status = collection_service->CreateCollection(&create_ctx, create_req, &created_metadata);
  93. if (!status.ok()) {
  94. spdlog::error("Failed to create {} collection: {}", kCollectionName, status.error_message());
  95. return false;
  96. }
  97. spdlog::info("Created system collection {}", kCollectionName);
  98. }
  99. // Ensure superadmin group exists
  100. auto superadmin_result = GetGroupByName("", kSuperadminGroupName, true);
  101. if (!superadmin_result.success) {
  102. if (!CreateSuperadminGroup()) {
  103. spdlog::error("Failed to create superadmin group");
  104. return false;
  105. }
  106. } else {
  107. spdlog::info("Global superadmin group already exists");
  108. }
  109. initialized_ = true;
  110. return true;
  111. }
  112. auto GroupService::CreateSuperadminGroup() -> bool {
  113. return CreateSystemGroup(kSuperadminGroupName, {"*"});
  114. }
  115. auto GroupService::CreateSystemGroup(const std::string& name, const std::vector<std::string>& permissions) -> bool {
  116. auto* doc_service = db_client_.GetDocumentService();
  117. if (doc_service == nullptr) {
  118. return false;
  119. }
  120. // Check if group already exists
  121. auto existing = GetGroupByName("", name, true);
  122. if (existing.success) {
  123. spdlog::info("System group {} already exists", name);
  124. return true;
  125. }
  126. ::smartbotic::database::CreateDocumentRequest create_req;
  127. create_req.set_collection(kCollectionName);
  128. auto* data = create_req.mutable_data();
  129. SetStringValue(data, "workspace_id", ""); // Global group
  130. SetStringValue(data, "name", name);
  131. SetArrayValue(data, "permissions", permissions);
  132. SetBoolValue(data, "is_system", true); // Mark as system group
  133. SetStringValue(data, "parent_group_id", "");
  134. SetStringValue(data, "created_at", GetCurrentTimestamp());
  135. SetStringValue(data, "updated_at", GetCurrentTimestamp());
  136. SetStringValue(data, "deleted_at", "");
  137. SetStringValue(data, "created_by", ""); // System-created
  138. SetStringValue(data, "updated_by", "");
  139. grpc::ClientContext ctx;
  140. ::smartbotic::database::Document created_doc;
  141. auto status = doc_service->CreateDocument(&ctx, create_req, &created_doc);
  142. if (!status.ok()) {
  143. spdlog::error("Failed to create system group {}: {}", name, status.error_message());
  144. return false;
  145. }
  146. spdlog::info("Created system group {} with ID {}", name, created_doc.id());
  147. return true;
  148. }
  149. auto GroupService::CreateGroup(const CreateGroupRequest& request) -> GroupResult {
  150. if (!initialized_) {
  151. return GroupResult{.success = false, .error = "Group service not initialized", .group = std::nullopt};
  152. }
  153. // Validate request
  154. if (request.name.empty()) {
  155. return GroupResult{.success = false, .error = "Name is required", .group = std::nullopt};
  156. }
  157. if (request.workspace_id.empty()) {
  158. return GroupResult{.success = false, .error = "Workspace ID is required for non-global groups", .group = std::nullopt};
  159. }
  160. // Prevent creating groups with reserved names
  161. if (request.name == kSuperadminGroupName) {
  162. return GroupResult{.success = false, .error = "Cannot create group with reserved name", .group = std::nullopt};
  163. }
  164. // Check if name already exists in workspace
  165. if (NameExistsInWorkspace(request.workspace_id, request.name)) {
  166. return GroupResult{.success = false, .error = "Group name already exists in workspace", .group = std::nullopt};
  167. }
  168. // Validate parent group if specified
  169. if (!request.parent_group_id.empty()) {
  170. auto parent_result = GetGroup(request.parent_group_id, false);
  171. if (!parent_result.success) {
  172. return GroupResult{.success = false, .error = "Parent group not found", .group = std::nullopt};
  173. }
  174. }
  175. // Create the document
  176. auto* doc_service = db_client_.GetDocumentService();
  177. if (doc_service == nullptr) {
  178. return GroupResult{.success = false, .error = "Document service not available", .group = std::nullopt};
  179. }
  180. ::smartbotic::database::CreateDocumentRequest create_req;
  181. create_req.set_collection(kCollectionName);
  182. auto* data = create_req.mutable_data();
  183. SetStringValue(data, "workspace_id", request.workspace_id);
  184. SetStringValue(data, "name", request.name);
  185. SetArrayValue(data, "permissions", request.permissions);
  186. SetBoolValue(data, "is_system", request.is_system);
  187. SetStringValue(data, "parent_group_id", request.parent_group_id);
  188. SetStringValue(data, "created_at", GetCurrentTimestamp());
  189. SetStringValue(data, "updated_at", GetCurrentTimestamp());
  190. SetStringValue(data, "deleted_at", "");
  191. SetStringValue(data, "created_by", request.actor_id);
  192. SetStringValue(data, "updated_by", request.actor_id);
  193. grpc::ClientContext ctx;
  194. ::smartbotic::database::Document created_doc;
  195. auto status = doc_service->CreateDocument(&ctx, create_req, &created_doc);
  196. if (!status.ok()) {
  197. spdlog::error("Failed to create group: {}", status.error_message());
  198. return GroupResult{.success = false, .error = status.error_message(), .group = std::nullopt};
  199. }
  200. spdlog::info("Created group {} with name {} in workspace {}", created_doc.id(), request.name, request.workspace_id);
  201. return GroupResult{.success = true, .error = "", .group = DocumentToGroup(created_doc)};
  202. }
  203. auto GroupService::GetGroup(const std::string& id, bool include_deleted) -> GroupResult {
  204. if (!initialized_) {
  205. return GroupResult{.success = false, .error = "Group service not initialized", .group = std::nullopt};
  206. }
  207. auto* doc_service = db_client_.GetDocumentService();
  208. if (doc_service == nullptr) {
  209. return GroupResult{.success = false, .error = "Document service not available", .group = std::nullopt};
  210. }
  211. ::smartbotic::database::GetDocumentRequest get_req;
  212. get_req.set_collection(kCollectionName);
  213. get_req.set_id(id);
  214. grpc::ClientContext ctx;
  215. ::smartbotic::database::Document doc;
  216. auto status = doc_service->GetDocument(&ctx, get_req, &doc);
  217. if (!status.ok()) {
  218. if (status.error_code() == grpc::StatusCode::NOT_FOUND) {
  219. return GroupResult{.success = false, .error = "Group not found", .group = std::nullopt};
  220. }
  221. return GroupResult{.success = false, .error = status.error_message(), .group = std::nullopt};
  222. }
  223. auto group = DocumentToGroup(doc);
  224. if (!include_deleted && group.IsDeleted()) {
  225. return GroupResult{.success = false, .error = "Group not found", .group = std::nullopt};
  226. }
  227. return GroupResult{.success = true, .error = "", .group = group};
  228. }
  229. auto GroupService::GetGroupByName(const std::string& workspace_id, const std::string& name, bool include_deleted) -> GroupResult {
  230. if (!initialized_ && name != kSuperadminGroupName) {
  231. return GroupResult{.success = false, .error = "Group service not initialized", .group = std::nullopt};
  232. }
  233. auto* query_service = db_client_.GetQueryService();
  234. if (query_service == nullptr) {
  235. return GroupResult{.success = false, .error = "Query service not available", .group = std::nullopt};
  236. }
  237. ::smartbotic::database::QueryRequest query_req;
  238. query_req.set_collection(kCollectionName);
  239. query_req.set_limit(1);
  240. // Build compound filter: workspace_id AND name
  241. auto* filter = query_req.mutable_filter();
  242. auto* composite = filter->mutable_composite();
  243. composite->set_operator_(::smartbotic::database::COMPOSITE_OPERATOR_AND);
  244. auto* ws_filter = composite->add_filters()->mutable_field();
  245. ws_filter->set_field("workspace_id");
  246. ws_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  247. ws_filter->mutable_value()->set_string_value(workspace_id);
  248. auto* name_filter = composite->add_filters()->mutable_field();
  249. name_filter->set_field("name");
  250. name_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  251. name_filter->mutable_value()->set_string_value(name);
  252. grpc::ClientContext ctx;
  253. ::smartbotic::database::QueryResponse response;
  254. auto status = query_service->Query(&ctx, query_req, &response);
  255. if (!status.ok()) {
  256. return GroupResult{.success = false, .error = status.error_message(), .group = std::nullopt};
  257. }
  258. if (response.documents().empty()) {
  259. return GroupResult{.success = false, .error = "Group not found", .group = std::nullopt};
  260. }
  261. auto group = DocumentToGroup(response.documents(0));
  262. if (!include_deleted && group.IsDeleted()) {
  263. return GroupResult{.success = false, .error = "Group not found", .group = std::nullopt};
  264. }
  265. return GroupResult{.success = true, .error = "", .group = group};
  266. }
  267. auto GroupService::ListGroups(const std::string& workspace_id, int limit, int offset, bool include_deleted) -> GroupListResult {
  268. if (!initialized_) {
  269. return GroupListResult{.success = false, .error = "Group service not initialized", .groups = {}, .total_count = 0};
  270. }
  271. auto* query_service = db_client_.GetQueryService();
  272. if (query_service == nullptr) {
  273. return GroupListResult{.success = false, .error = "Query service not available", .groups = {}, .total_count = 0};
  274. }
  275. ::smartbotic::database::QueryRequest query_req;
  276. query_req.set_collection(kCollectionName);
  277. query_req.set_limit(limit);
  278. query_req.set_offset(offset);
  279. // Build filter for workspace
  280. auto* filter = query_req.mutable_filter();
  281. if (!include_deleted) {
  282. // Filter: workspace_id = X AND deleted_at = ""
  283. auto* composite = filter->mutable_composite();
  284. composite->set_operator_(::smartbotic::database::COMPOSITE_OPERATOR_AND);
  285. auto* ws_filter = composite->add_filters()->mutable_field();
  286. ws_filter->set_field("workspace_id");
  287. ws_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  288. ws_filter->mutable_value()->set_string_value(workspace_id);
  289. auto* del_filter = composite->add_filters()->mutable_field();
  290. del_filter->set_field("deleted_at");
  291. del_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  292. del_filter->mutable_value()->set_string_value("");
  293. } else {
  294. // Filter: workspace_id = X
  295. auto* ws_filter = filter->mutable_field();
  296. ws_filter->set_field("workspace_id");
  297. ws_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  298. ws_filter->mutable_value()->set_string_value(workspace_id);
  299. }
  300. // Order by name ascending
  301. auto* order = query_req.add_order_by();
  302. order->set_field("name");
  303. order->set_direction(::smartbotic::database::SORT_DIRECTION_ASCENDING);
  304. grpc::ClientContext ctx;
  305. ::smartbotic::database::QueryResponse response;
  306. auto status = query_service->Query(&ctx, query_req, &response);
  307. if (!status.ok()) {
  308. return GroupListResult{.success = false, .error = status.error_message(), .groups = {}, .total_count = 0};
  309. }
  310. GroupListResult result;
  311. result.success = true;
  312. result.total_count = response.total_count();
  313. for (const auto& doc : response.documents()) {
  314. result.groups.push_back(DocumentToGroup(doc));
  315. }
  316. return result;
  317. }
  318. auto GroupService::ListGroupsByIds(const std::vector<std::string>& group_ids, bool include_deleted) -> GroupListResult {
  319. if (!initialized_) {
  320. return GroupListResult{.success = false, .error = "Group service not initialized", .groups = {}, .total_count = 0};
  321. }
  322. if (group_ids.empty()) {
  323. return GroupListResult{.success = true, .error = "", .groups = {}, .total_count = 0};
  324. }
  325. // Fetch each group by ID
  326. GroupListResult result;
  327. result.success = true;
  328. for (const auto& id : group_ids) {
  329. auto grp_result = GetGroup(id, include_deleted);
  330. if (grp_result.success && grp_result.group) {
  331. result.groups.push_back(*grp_result.group);
  332. }
  333. }
  334. result.total_count = static_cast<int64_t>(result.groups.size());
  335. return result;
  336. }
  337. auto GroupService::UpdateGroup(const std::string& id, const UpdateGroupRequest& request) -> GroupResult {
  338. if (!initialized_) {
  339. return GroupResult{.success = false, .error = "Group service not initialized", .group = std::nullopt};
  340. }
  341. // First get the existing group
  342. auto existing = GetGroup(id, false);
  343. if (!existing.success) {
  344. return existing;
  345. }
  346. // Cannot modify superadmin group
  347. if (existing.group->name == kSuperadminGroupName && existing.group->IsGlobal()) {
  348. return GroupResult{.success = false, .error = "Cannot modify superadmin group", .group = std::nullopt};
  349. }
  350. // Check if name is being updated and if it already exists
  351. if (request.name && *request.name != existing.group->name) {
  352. if (*request.name == kSuperadminGroupName) {
  353. return GroupResult{.success = false, .error = "Cannot use reserved name", .group = std::nullopt};
  354. }
  355. if (NameExistsInWorkspace(existing.group->workspace_id, *request.name)) {
  356. return GroupResult{.success = false, .error = "Group name already exists in workspace", .group = std::nullopt};
  357. }
  358. }
  359. auto* doc_service = db_client_.GetDocumentService();
  360. if (doc_service == nullptr) {
  361. return GroupResult{.success = false, .error = "Document service not available", .group = std::nullopt};
  362. }
  363. ::smartbotic::database::UpdateDocumentRequest update_req;
  364. update_req.set_collection(kCollectionName);
  365. update_req.set_id(id);
  366. update_req.set_merge(true); // Merge with existing data
  367. auto* data = update_req.mutable_data();
  368. if (request.name) {
  369. SetStringValue(data, "name", *request.name);
  370. }
  371. if (request.permissions) {
  372. SetArrayValue(data, "permissions", *request.permissions);
  373. }
  374. if (request.parent_group_id) {
  375. // Validate parent group if specified
  376. if (!request.parent_group_id->empty()) {
  377. auto parent_result = GetGroup(*request.parent_group_id, false);
  378. if (!parent_result.success) {
  379. return GroupResult{.success = false, .error = "Parent group not found", .group = std::nullopt};
  380. }
  381. // Prevent circular references
  382. if (*request.parent_group_id == id) {
  383. return GroupResult{.success = false, .error = "Group cannot be its own parent", .group = std::nullopt};
  384. }
  385. }
  386. SetStringValue(data, "parent_group_id", *request.parent_group_id);
  387. }
  388. SetStringValue(data, "updated_at", GetCurrentTimestamp());
  389. if (!request.actor_id.empty()) {
  390. SetStringValue(data, "updated_by", request.actor_id);
  391. }
  392. grpc::ClientContext ctx;
  393. ::smartbotic::database::Document updated_doc;
  394. auto status = doc_service->UpdateDocument(&ctx, update_req, &updated_doc);
  395. if (!status.ok()) {
  396. return GroupResult{.success = false, .error = status.error_message(), .group = std::nullopt};
  397. }
  398. spdlog::info("Updated group {}", id);
  399. return GroupResult{.success = true, .error = "", .group = DocumentToGroup(updated_doc)};
  400. }
  401. auto GroupService::DeleteGroup(const std::string& id) -> GroupResult {
  402. if (!initialized_) {
  403. return GroupResult{.success = false, .error = "Group service not initialized", .group = std::nullopt};
  404. }
  405. // First get the existing group
  406. auto existing = GetGroup(id, false);
  407. if (!existing.success) {
  408. return existing;
  409. }
  410. // Cannot delete superadmin group
  411. if (existing.group->name == kSuperadminGroupName && existing.group->IsGlobal()) {
  412. return GroupResult{.success = false, .error = "Cannot delete superadmin group", .group = std::nullopt};
  413. }
  414. auto* doc_service = db_client_.GetDocumentService();
  415. if (doc_service == nullptr) {
  416. return GroupResult{.success = false, .error = "Document service not available", .group = std::nullopt};
  417. }
  418. // Soft delete by setting deleted_at
  419. ::smartbotic::database::UpdateDocumentRequest update_req;
  420. update_req.set_collection(kCollectionName);
  421. update_req.set_id(id);
  422. update_req.set_merge(true);
  423. auto* data = update_req.mutable_data();
  424. SetStringValue(data, "deleted_at", GetCurrentTimestamp());
  425. SetStringValue(data, "updated_at", GetCurrentTimestamp());
  426. grpc::ClientContext ctx;
  427. ::smartbotic::database::Document updated_doc;
  428. auto status = doc_service->UpdateDocument(&ctx, update_req, &updated_doc);
  429. if (!status.ok()) {
  430. return GroupResult{.success = false, .error = status.error_message(), .group = std::nullopt};
  431. }
  432. spdlog::info("Soft deleted group {}", id);
  433. return GroupResult{.success = true, .error = "", .group = DocumentToGroup(updated_doc)};
  434. }
  435. auto GroupService::NameExistsInWorkspace(const std::string& workspace_id, const std::string& name) -> bool {
  436. auto result = GetGroupByName(workspace_id, name, true);
  437. return result.success;
  438. }
  439. auto GroupService::GetSuperadminGroup() -> GroupResult {
  440. return GetGroupByName("", kSuperadminGroupName, false);
  441. }
  442. auto GroupService::DocumentToGroup(const ::smartbotic::database::Document& doc) -> Group {
  443. Group group;
  444. group.id = doc.id();
  445. group.workspace_id = GetStringValue(doc.data(), "workspace_id");
  446. group.name = GetStringValue(doc.data(), "name");
  447. group.permissions = GetArrayValue(doc.data(), "permissions");
  448. group.is_system = GetBoolValue(doc.data(), "is_system");
  449. group.parent_group_id = GetStringValue(doc.data(), "parent_group_id");
  450. group.created_at = GetStringValue(doc.data(), "created_at");
  451. group.updated_at = GetStringValue(doc.data(), "updated_at");
  452. group.deleted_at = GetStringValue(doc.data(), "deleted_at");
  453. group.created_by = GetStringValue(doc.data(), "created_by");
  454. group.updated_by = GetStringValue(doc.data(), "updated_by");
  455. return group;
  456. }
  457. auto GroupService::ListSystemGroups(bool include_deleted) -> GroupListResult {
  458. if (!initialized_) {
  459. return GroupListResult{.success = false, .error = "Group service not initialized", .groups = {}, .total_count = 0};
  460. }
  461. auto* query_service = db_client_.GetQueryService();
  462. if (query_service == nullptr) {
  463. return GroupListResult{.success = false, .error = "Query service not available", .groups = {}, .total_count = 0};
  464. }
  465. ::smartbotic::database::QueryRequest query_req;
  466. query_req.set_collection(kCollectionName);
  467. query_req.set_limit(100);
  468. // Build filter: workspace_id = "" AND is_system = true
  469. auto* filter = query_req.mutable_filter();
  470. auto* composite = filter->mutable_composite();
  471. composite->set_operator_(::smartbotic::database::COMPOSITE_OPERATOR_AND);
  472. auto* ws_filter = composite->add_filters()->mutable_field();
  473. ws_filter->set_field("workspace_id");
  474. ws_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  475. ws_filter->mutable_value()->set_string_value("");
  476. auto* sys_filter = composite->add_filters()->mutable_field();
  477. sys_filter->set_field("is_system");
  478. sys_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  479. sys_filter->mutable_value()->set_bool_value(true);
  480. if (!include_deleted) {
  481. auto* del_filter = composite->add_filters()->mutable_field();
  482. del_filter->set_field("deleted_at");
  483. del_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  484. del_filter->mutable_value()->set_string_value("");
  485. }
  486. // Order by name ascending
  487. auto* order = query_req.add_order_by();
  488. order->set_field("name");
  489. order->set_direction(::smartbotic::database::SORT_DIRECTION_ASCENDING);
  490. grpc::ClientContext ctx;
  491. ::smartbotic::database::QueryResponse response;
  492. auto status = query_service->Query(&ctx, query_req, &response);
  493. if (!status.ok()) {
  494. return GroupListResult{.success = false, .error = status.error_message(), .groups = {}, .total_count = 0};
  495. }
  496. GroupListResult result;
  497. result.success = true;
  498. result.total_count = response.total_count();
  499. for (const auto& doc : response.documents()) {
  500. result.groups.push_back(DocumentToGroup(doc));
  501. }
  502. return result;
  503. }
  504. auto GroupService::ListGlobalGroups(bool include_deleted) -> GroupListResult {
  505. if (!initialized_) {
  506. return GroupListResult{.success = false, .error = "Group service not initialized", .groups = {}, .total_count = 0};
  507. }
  508. auto* query_service = db_client_.GetQueryService();
  509. if (query_service == nullptr) {
  510. return GroupListResult{.success = false, .error = "Query service not available", .groups = {}, .total_count = 0};
  511. }
  512. ::smartbotic::database::QueryRequest query_req;
  513. query_req.set_collection(kCollectionName);
  514. query_req.set_limit(100);
  515. // Build filter: workspace_id = ""
  516. auto* filter = query_req.mutable_filter();
  517. if (!include_deleted) {
  518. auto* composite = filter->mutable_composite();
  519. composite->set_operator_(::smartbotic::database::COMPOSITE_OPERATOR_AND);
  520. auto* ws_filter = composite->add_filters()->mutable_field();
  521. ws_filter->set_field("workspace_id");
  522. ws_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  523. ws_filter->mutable_value()->set_string_value("");
  524. auto* del_filter = composite->add_filters()->mutable_field();
  525. del_filter->set_field("deleted_at");
  526. del_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  527. del_filter->mutable_value()->set_string_value("");
  528. } else {
  529. auto* ws_filter = filter->mutable_field();
  530. ws_filter->set_field("workspace_id");
  531. ws_filter->set_operator_(::smartbotic::database::FILTER_OPERATOR_EQUAL);
  532. ws_filter->mutable_value()->set_string_value("");
  533. }
  534. // Order by name ascending
  535. auto* order = query_req.add_order_by();
  536. order->set_field("name");
  537. order->set_direction(::smartbotic::database::SORT_DIRECTION_ASCENDING);
  538. grpc::ClientContext ctx;
  539. ::smartbotic::database::QueryResponse response;
  540. auto status = query_service->Query(&ctx, query_req, &response);
  541. if (!status.ok()) {
  542. return GroupListResult{.success = false, .error = status.error_message(), .groups = {}, .total_count = 0};
  543. }
  544. GroupListResult result;
  545. result.success = true;
  546. result.total_count = response.total_count();
  547. for (const auto& doc : response.documents()) {
  548. result.groups.push_back(DocumentToGroup(doc));
  549. }
  550. return result;
  551. }
  552. auto GroupService::GetEffectivePermissions(const std::string& group_id) -> std::vector<std::string> {
  553. std::vector<std::string> permissions;
  554. std::unordered_set<std::string> visited; // Prevent infinite loops
  555. std::function<void(const std::string&)> collect_permissions = [&](const std::string& id) {
  556. if (id.empty() || visited.contains(id)) {
  557. return;
  558. }
  559. visited.insert(id);
  560. auto result = GetGroup(id, false);
  561. if (!result.success || !result.group) {
  562. return;
  563. }
  564. // Add this group's permissions
  565. for (const auto& perm : result.group->permissions) {
  566. permissions.push_back(perm);
  567. }
  568. // Recursively get parent's permissions
  569. if (!result.group->parent_group_id.empty()) {
  570. collect_permissions(result.group->parent_group_id);
  571. }
  572. };
  573. collect_permissions(group_id);
  574. return permissions;
  575. }
  576. auto GroupService::GetCurrentTimestamp() -> std::string {
  577. auto now = std::chrono::system_clock::now();
  578. auto time = std::chrono::system_clock::to_time_t(now);
  579. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
  580. std::ostringstream oss;
  581. oss << std::put_time(std::gmtime(&time), "%Y-%m-%dT%H:%M:%S");
  582. oss << '.' << std::setfill('0') << std::setw(3) << ms.count() << 'Z';
  583. return oss.str();
  584. }
  585. } // namespace smartbotic::webserver