@descix/platform-api 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1901 @@
1
+ /**
2
+ * @descix/platform-api - Firestore Models
3
+ *
4
+ * Platform-wide Firestore model classes shared between Cloud and Powch microservices.
5
+ *
6
+ * NOTE: KnowledgeBase, IPDocMetadata, and ChunkMetadata are intentionally NOT extracted here
7
+ * because they contain dynamic imports to Cloud-specific services (pineconeService,
8
+ * googleStorageService, geminiAPI). Those classes remain in DeSciX_Cloud/microservice/services/ipStorageUtils.js.
9
+ *
10
+ * All config values are loaded lazily via getCloudConfig() from @descix/cloud-core.
11
+ * The bootstrap must complete before any model methods are called.
12
+ */
13
+
14
+ import crypto from 'crypto';
15
+ import path from 'path';
16
+ import {
17
+ CacheFirestore,
18
+ FirestoreCollections,
19
+ FirestoreDocumentPath,
20
+ Purchase,
21
+ AuthProvider,
22
+ FieldValue,
23
+ Timestamp,
24
+ ProductTypes,
25
+ getCloudConfig,
26
+ } from '@descix/cloud-core';
27
+
28
+ // Inline normalizeEmail — avoids circular dependency with email module
29
+ function normalizeEmail(email) {
30
+ return email ? email.trim().toLowerCase() : null;
31
+ }
32
+
33
+ // --- Helper Functions ---
34
+
35
+ export function clean_name_for_id(name) {
36
+ if (!name) return '';
37
+ const disallowed_chars = " #%&*+/=?^`{|}~";
38
+ const transRegex = new RegExp(`[${disallowed_chars.split('').join('')}]`, 'g');
39
+ return name.replace(/\s+/g, "_").toLowerCase().replace(transRegex, "");
40
+ }
41
+
42
+ export function count_tokens(text) {
43
+ if (!text) return 0;
44
+ return Math.ceil(text.length / 4);
45
+ }
46
+
47
+ export function matrix_to_bigquery(rows, projectId, datasetId, tableId, append) {
48
+ console.log("matrix_to_bigquery stub called. Data not sent to BigQuery.");
49
+ console.log("First row headers:", rows[0]);
50
+ return `Stub run: ${new Date()}`;
51
+ }
52
+
53
+ /**
54
+ * Sanitize WebAuthn credentialId for Firestore document ID (replace / and +)
55
+ * @param {string} credentialId - Raw credential ID from WebAuthn
56
+ * @returns {string} Sanitized string safe for Firestore doc IDs
57
+ */
58
+ export function sanitizeCredentialId(credentialId) {
59
+ if (!credentialId || typeof credentialId !== 'string') return '';
60
+ return credentialId.replace(/\//g, '_').replace(/\+/g, '-');
61
+ }
62
+
63
+ export async function get_default_community() {
64
+ const utils = getCloudConfig();
65
+ const community_id = utils.DEFAULT_COMMUNITY_ID;
66
+ return await Community.from_firestore(community_id);
67
+ }
68
+
69
+ /**
70
+ * Get user's entitlements for tell_me_how scope filtering.
71
+ * Returns communities the user is a member of and apps they've purchased.
72
+ *
73
+ * @param {User|Object} user - User object or { id: user_id }
74
+ * @returns {Promise<{communities: string[], apps: string[]}>}
75
+ */
76
+ export async function getUserEntitlements(user) {
77
+ if (!user || !user.id) {
78
+ return { communities: [], apps: [] };
79
+ }
80
+
81
+ try {
82
+ const db = new CacheFirestore();
83
+ const purchaseDocs = await db.get_docs(FirestoreCollections.USER_PURCHASES(user.id));
84
+
85
+ const communityIds = new Set();
86
+ const appIds = new Set();
87
+
88
+ if (purchaseDocs) {
89
+ for (const purchaseData of purchaseDocs) {
90
+ if (!purchaseData) continue;
91
+
92
+ const productPath = purchaseData.ProductPath || '';
93
+ const productType = purchaseData.ProductType || '';
94
+ const parts = productPath.split('/');
95
+
96
+ if (productType === ProductTypes.COMMUNITY) {
97
+ if (parts.length >= 2 && parts[0].toLowerCase() === 'community') {
98
+ communityIds.add(parts[1]);
99
+ }
100
+ } else if (productType === ProductTypes.APP) {
101
+ if (parts.length >= 4 && parts[0].toLowerCase() === 'community' && parts[2].toLowerCase() === 'apps') {
102
+ communityIds.add(parts[1]);
103
+ appIds.add(parts[3]);
104
+ }
105
+ }
106
+ }
107
+ }
108
+
109
+ // Add public/free apps that everyone has access to
110
+ try {
111
+ const publicApps = await db.get_docs(
112
+ 'Community/daita/Apps',
113
+ null,
114
+ [['is_public', '==', true]]
115
+ );
116
+ if (publicApps) {
117
+ for (const app of publicApps) {
118
+ if (app?.app_id) {
119
+ appIds.add(app.app_id);
120
+ }
121
+ }
122
+ }
123
+ } catch (err) {
124
+ console.warn('[getUserEntitlements] Failed to get public apps:', err.message);
125
+ }
126
+
127
+ // Always include 'daita' community (platform core)
128
+ communityIds.add('daita');
129
+
130
+ return {
131
+ communities: Array.from(communityIds),
132
+ apps: Array.from(appIds)
133
+ };
134
+ } catch (error) {
135
+ console.error('[getUserEntitlements] Error:', error);
136
+ return { communities: ['daita'], apps: [] };
137
+ }
138
+ }
139
+
140
+ // --- Role Class ---
141
+
142
+ export class Role {
143
+ constructor(
144
+ role_id, role_name, role_description = '', scope, scope_id, permissions = [],
145
+ price_usdsci = 0, purchase_type = 'ONE_TIME', discord_role_id = null,
146
+ owner_id = null, created_date = null, updated_date = null,
147
+ display_metadata = null,
148
+ billing_period = null
149
+ ) {
150
+ this.role_id = role_id;
151
+ this.role_name = role_name;
152
+ this.role_description = role_description;
153
+ this.scope = scope;
154
+ this.scope_id = scope_id;
155
+ this.permissions = permissions || [];
156
+ this.price_usdsci = Number(price_usdsci) || 0;
157
+ this.purchase_type = purchase_type || 'ONE_TIME';
158
+ this.billing_period = billing_period || null;
159
+ this.discord_role_id = discord_role_id;
160
+ this.owner_id = owner_id;
161
+ this.created_date = created_date instanceof Timestamp ? created_date : (created_date ? Timestamp.fromDate(new Date(created_date)) : Timestamp.now());
162
+ this.updated_date = updated_date instanceof Timestamp ? updated_date : (updated_date ? Timestamp.fromDate(new Date(updated_date)) : Timestamp.now());
163
+
164
+ this.display_metadata = display_metadata || {
165
+ icon_url: null,
166
+ category: null,
167
+ short_description: null
168
+ };
169
+
170
+ this.db = new CacheFirestore();
171
+ }
172
+
173
+ get collection_path() {
174
+ if (!this.scope || !this.scope_id) throw new Error("Role scope and scope_id are required to determine collection path.");
175
+ return FirestoreCollections.ROLES(this.scope, this.scope_id);
176
+ }
177
+
178
+ get doc_id() {
179
+ if (!this.role_id) throw new Error("Role ID is required for document ID.");
180
+ return this.role_id;
181
+ }
182
+
183
+ get product_path() {
184
+ return FirestoreDocumentPath.ROLE(this.scope, this.scope_id, this.role_id);
185
+ }
186
+
187
+ to_dict() {
188
+ const result = {
189
+ role_id: this.role_id,
190
+ role_name: this.role_name,
191
+ role_description: this.role_description,
192
+ scope: this.scope,
193
+ scope_id: this.scope_id,
194
+ permissions: this.permissions,
195
+ price_usdsci: this.price_usdsci,
196
+ purchase_type: this.purchase_type,
197
+ discord_role_id: this.discord_role_id,
198
+ owner_id: this.owner_id,
199
+ created_date: this.created_date,
200
+ updated_date: this.updated_date,
201
+ display_metadata: this.display_metadata
202
+ };
203
+ if (this.billing_period) {
204
+ result.billing_period = this.billing_period;
205
+ }
206
+ return result;
207
+ }
208
+
209
+ static from_dict(data) {
210
+ if (!data) return null;
211
+ const created_date_obj = data.created_date instanceof Timestamp ? data.created_date : Timestamp.fromDate(new Date(data.created_date || Date.now()));
212
+ const updated_date_obj = data.updated_date instanceof Timestamp ? data.updated_date : Timestamp.fromDate(new Date(data.updated_date || Date.now()));
213
+
214
+ return new Role(
215
+ data.role_id,
216
+ data.role_name,
217
+ data.role_description,
218
+ data.scope,
219
+ data.scope_id,
220
+ data.permissions,
221
+ data.price_usdsci,
222
+ data.purchase_type,
223
+ data.discord_role_id,
224
+ data.owner_id,
225
+ created_date_obj,
226
+ updated_date_obj,
227
+ data.display_metadata,
228
+ data.billing_period || null
229
+ );
230
+ }
231
+
232
+ async to_firestore() {
233
+ if (!this.role_id || !this.scope || !this.scope_id) {
234
+ console.error("Cannot save Role without role_id, scope, and scope_id.");
235
+ return false;
236
+ }
237
+ this.updated_date = Timestamp.now();
238
+ return await this.db.put_doc(this.collection_path, this.doc_id, this.to_dict());
239
+ }
240
+
241
+ static async from_firestore(scope, scope_id, role_id) {
242
+ const db = new CacheFirestore();
243
+ const doc = await db.get_doc(FirestoreCollections.ROLES(scope, scope_id), role_id);
244
+ if (!doc) return null;
245
+ return Role.from_dict(doc);
246
+ }
247
+
248
+ async delete_role() {
249
+ if (!this.role_id || !this.scope || !this.scope_id) {
250
+ console.error("Cannot delete Role without role_id, scope, and scope_id.");
251
+ return false;
252
+ }
253
+ return await this.db.delete_doc(this.collection_path, this.doc_id);
254
+ }
255
+
256
+ static async create_role(user, role_id, role_name, role_description, scope, scope_id,
257
+ permissions, price_usdsci, purchase_type, discord_role_id,
258
+ display_metadata) {
259
+
260
+ if (!role_id || !role_name || !scope || !scope_id) {
261
+ throw new Error("Missing required parameters: role_id, role_name, scope, scope_id.");
262
+ }
263
+
264
+ if (!['PLATFORM', 'COMMUNITY', 'APP'].includes(scope.toUpperCase())) {
265
+ throw new Error("Invalid scope. Must be PLATFORM, COMMUNITY, or APP.");
266
+ }
267
+
268
+ const existingRole = await Role.from_firestore(scope.toUpperCase(), scope_id, role_id);
269
+ if (existingRole) {
270
+ throw new Error(`Role with ID '${role_id}' already exists in scope '${scope}/${scope_id}'.`);
271
+ }
272
+
273
+ const newRole = new Role(
274
+ role_id, role_name, role_description, scope.toUpperCase(), scope_id, permissions,
275
+ price_usdsci, purchase_type, discord_role_id,
276
+ user.id,
277
+ null,
278
+ null,
279
+ display_metadata
280
+ );
281
+
282
+ const success = await newRole.to_firestore();
283
+ if (!success) {
284
+ throw new Error("Failed to save the new role to Firestore.");
285
+ }
286
+
287
+ return { role: newRole.to_dict() };
288
+ }
289
+
290
+ static async get_roles_for_scope(params) {
291
+ const { scope, scope_id } = params;
292
+
293
+ if (!scope || !scope_id) {
294
+ throw new Error("Missing required parameters: scope, scope_id.");
295
+ }
296
+ if (!['PLATFORM', 'COMMUNITY', 'APP'].includes(scope.toUpperCase())) {
297
+ throw new Error("Invalid scope. Must be PLATFORM, COMMUNITY, or APP.");
298
+ }
299
+
300
+ const db = new CacheFirestore();
301
+ const rolesPath = FirestoreCollections.ROLES(scope.toUpperCase(), scope_id);
302
+ const roleDocs = await db.get_docs(rolesPath);
303
+
304
+ if (!roleDocs) {
305
+ return { roles: [] };
306
+ }
307
+
308
+ const roles = roleDocs.map(doc => Role.from_dict(doc)).filter(role => role !== null);
309
+ return { roles: roles.map(r => r.to_dict()) };
310
+ }
311
+ }
312
+
313
+ // --- App Class ---
314
+
315
+ export class App {
316
+ constructor(
317
+ community_id, app_name, app_id = null, app_description = "",
318
+ knowledgebase_name = null, icon_url = "",
319
+ create_date = new Date(), ip_site_gcs_path_url = "", owner_id = "",
320
+ price = 0, token_symbol = null, drive_folder_id = "",
321
+ initial_daita_value = 0, api_base_url = null,
322
+ // default_app_model: per CEO 2026-05-26 inheritance chain — when null/absent the
323
+ // platform per-level model (levelConfig.model) wins. Only set when an app team
324
+ // wants to pin a specific model regardless of intelligence level.
325
+ default_app_model = null
326
+ ) {
327
+ const utils = getCloudConfig();
328
+ this.community_id = String(community_id);
329
+ this.app_name = String(app_name);
330
+ this.app_id = app_id === null ? clean_name_for_id(app_name) : String(app_id);
331
+ this.app_description = app_description;
332
+ this.knowledgebase_name = String(knowledgebase_name || utils.DEFAULT_KNOWLEDGEBASE_NAME);
333
+ this.icon_url = icon_url;
334
+ this.ip_site_gcs_path_url = String(ip_site_gcs_path_url);
335
+ this.create_date = create_date instanceof Date ? create_date : new Date(create_date);
336
+ this.owner_id = String(owner_id);
337
+ // default_app_model: keep as null/absent unless the caller passed an explicit value.
338
+ // This avoids re-populating the doc with utils.DEFAULT_AI_MODEL on every hydration,
339
+ // which would shadow the per-level platform default at request time.
340
+ this.default_app_model = default_app_model || null;
341
+ this.default_prompt = utils.DEFAULT_COMMUNITY_PROMPT;
342
+ this.price = price;
343
+ this.token_symbol = token_symbol;
344
+ this.drive_folder_id = drive_folder_id || "";
345
+ this.initial_daita_value = initial_daita_value || 0;
346
+ this.api_base_url = api_base_url;
347
+
348
+ // Repo sharing fields (set post-construction via set_app_repo command)
349
+ this.repo_url = null;
350
+ this.repo_branch = null;
351
+ this.repo_subfolder = null;
352
+ this.repo_deploy_key = null;
353
+ this.repo_key_fingerprint = null;
354
+
355
+ this.db = new CacheFirestore();
356
+ }
357
+
358
+ get product_path() {
359
+ return FirestoreDocumentPath.APP(this.community_id, this.app_id);
360
+ }
361
+
362
+ to_dict() {
363
+ const copy = { ...this };
364
+ delete copy.db;
365
+ if (copy.create_date instanceof Date && !isNaN(copy.create_date.getTime())) {
366
+ copy.create_date = Timestamp.fromDate(copy.create_date);
367
+ } else if (!copy.create_date || !(copy.create_date instanceof Timestamp)) {
368
+ copy.create_date = Timestamp.now();
369
+ }
370
+ if (copy.initial_daita_value === undefined) copy.initial_daita_value = 0;
371
+ return copy;
372
+ }
373
+
374
+ async to_firestore() {
375
+ const apps_path = FirestoreCollections.APPS(this.community_id);
376
+ return await this.db.put_doc(apps_path, this.app_id, this.to_dict());
377
+ }
378
+
379
+ static async from_firestore(community_id, app_id) {
380
+ const db = new CacheFirestore();
381
+ const apps_path = FirestoreCollections.APPS(community_id);
382
+ const doc = await db.get_doc(apps_path, app_id);
383
+ if (!doc) return null;
384
+ const create_date_obj = doc.create_date instanceof Timestamp ? doc.create_date.toDate() : new Date(doc.create_date);
385
+ const app = new App(
386
+ doc.community_id || community_id,
387
+ doc.app_name,
388
+ doc.app_id || app_id,
389
+ doc.app_description || "",
390
+ doc.knowledgebase_name, doc.icon_url, create_date_obj, doc.ip_site_gcs_path_url,
391
+ doc.owner_id || "", doc.price || 0, doc.token_symbol || null, doc.drive_folder_id || "",
392
+ doc.initial_daita_value || 0,
393
+ doc.api_base_url || null,
394
+ doc.default_app_model || null // hydrate from Firestore (null = use platform per-level)
395
+ );
396
+ app.repo_url = doc.repo_url || null;
397
+ app.repo_branch = doc.repo_branch || null;
398
+ app.repo_subfolder = doc.repo_subfolder || null;
399
+ app.repo_deploy_key = doc.repo_deploy_key || null;
400
+ app.repo_key_fingerprint = doc.repo_key_fingerprint || null;
401
+ return app;
402
+ }
403
+
404
+ static quick_create_app(community_id, app_name, icon_url, app_description = "", owner_id = "", price = 0, token_symbol = null) {
405
+ const utils = getCloudConfig();
406
+ const knowledgebase_name = utils.DEFAULT_KNOWLEDGEBASE_NAME;
407
+ const ip_site_gcs_path_url = "";
408
+ const create_date = new Date();
409
+ let app_id = clean_name_for_id(app_name);
410
+ const app_doc = new App(community_id, app_name, app_id, app_description, knowledgebase_name, icon_url, create_date, ip_site_gcs_path_url, owner_id, price, token_symbol);
411
+ app_doc.to_firestore();
412
+ return app_doc;
413
+ }
414
+
415
+ static from_dict(data) {
416
+ if (!data) return null;
417
+ const utils = getCloudConfig();
418
+ const create_date_obj = data.create_date instanceof Timestamp ? data.create_date.toDate() : new Date(data.create_date || Date.now());
419
+ const app = new App(
420
+ data.community_id,
421
+ data.app_name,
422
+ data.app_id,
423
+ data.app_description || "",
424
+ data.knowledgebase_name || utils.DEFAULT_KNOWLEDGEBASE_NAME,
425
+ data.icon_url || "",
426
+ create_date_obj,
427
+ data.ip_site_gcs_path_url || "",
428
+ data.owner_id || "",
429
+ data.price || 0,
430
+ data.token_symbol || null,
431
+ data.drive_folder_id || "",
432
+ data.initial_daita_value || 0,
433
+ data.api_base_url || null,
434
+ data.default_app_model || null // hydrate from data dict
435
+ );
436
+ app.repo_url = data.repo_url || null;
437
+ app.repo_branch = data.repo_branch || null;
438
+ app.repo_subfolder = data.repo_subfolder || null;
439
+ app.repo_deploy_key = data.repo_deploy_key || null;
440
+ app.repo_key_fingerprint = data.repo_key_fingerprint || null;
441
+ return app;
442
+ }
443
+ }
444
+
445
+ // --- User Class ---
446
+
447
+ export class User {
448
+ constructor(
449
+ id, email = null, user_info = null,
450
+ wallet_address = null, signature = null,
451
+ roles = new Map(),
452
+ total_rep = 0, total_ref_generic = 0, total_dip = 0, claimed_promotions = [],
453
+ accumulated_ref_commission = 0, accumulated_rep_commission = 0, accumulated_dip_commission = 0,
454
+ provider_links = null,
455
+ base_folder_id = null,
456
+ nfts = new Map(),
457
+ ad_campaigns = new Map(),
458
+ pending_referral_code = null,
459
+ api_signatures = [],
460
+ point_multiplier = 1.0,
461
+ lifetime_spend_usd = 0,
462
+ pending_ref_count = 0
463
+ ) {
464
+ if (!id || typeof id !== 'string' || id.length === 0) {
465
+ throw new Error('User ID is required (non-empty string)');
466
+ }
467
+ this.id = id;
468
+ this.email = email ? normalizeEmail(email) : null;
469
+ this.user_info = user_info;
470
+ this.wallet_address = wallet_address;
471
+ this.signature = signature;
472
+ this.roles = roles instanceof Map ? roles : new Map(Object.entries(roles || {}));
473
+ this.total_rep = total_rep;
474
+ this.total_ref_generic = total_ref_generic;
475
+ this.total_dip = total_dip;
476
+ this.claimed_promotions = claimed_promotions || [];
477
+ this.accumulated_ref_commission = accumulated_ref_commission;
478
+ this.accumulated_rep_commission = accumulated_rep_commission;
479
+ this.accumulated_dip_commission = accumulated_dip_commission;
480
+ this.base_folder_id = base_folder_id || null;
481
+
482
+ if (provider_links instanceof Map) {
483
+ this.provider_links = provider_links;
484
+ } else if (provider_links && typeof provider_links === 'object') {
485
+ this.provider_links = new Map(Object.entries(provider_links));
486
+ } else {
487
+ this.provider_links = new Map();
488
+ }
489
+
490
+ this.nfts = nfts instanceof Map ? nfts : new Map(Object.entries(nfts || {}));
491
+ this.ad_campaigns = ad_campaigns instanceof Map ? ad_campaigns : new Map(Object.entries(ad_campaigns || {}));
492
+ this.pending_referral_code = pending_referral_code || null;
493
+ this.api_signatures = Array.isArray(api_signatures) ? api_signatures : [];
494
+ this.point_multiplier = point_multiplier || 1.0;
495
+ this.lifetime_spend_usd = lifetime_spend_usd || 0;
496
+ this.pending_ref_count = pending_ref_count || 0;
497
+
498
+ this.db = new CacheFirestore();
499
+ }
500
+
501
+ to_dict() {
502
+ const copy = { ...this };
503
+ delete copy.db;
504
+ copy.roles = copy.roles instanceof Map ? Object.fromEntries(copy.roles) : (copy.roles || {});
505
+ copy.provider_links = copy.provider_links instanceof Map ? Object.fromEntries(copy.provider_links) : (copy.provider_links || {});
506
+ copy.nfts = copy.nfts instanceof Map ? Object.fromEntries(copy.nfts) : (copy.nfts || {});
507
+ copy.ad_campaigns = copy.ad_campaigns instanceof Map ? Object.fromEntries(copy.ad_campaigns) : (copy.ad_campaigns || {});
508
+
509
+ if (!copy.claimed_promotions) copy.claimed_promotions = [];
510
+ if (copy.total_rep === undefined) copy.total_rep = 0;
511
+ if (copy.total_ref_generic === undefined) copy.total_ref_generic = 0;
512
+ if (copy.total_dip === undefined) copy.total_dip = 0;
513
+ if (copy.accumulated_ref_commission === undefined) copy.accumulated_ref_commission = 0;
514
+ if (copy.accumulated_rep_commission === undefined) copy.accumulated_rep_commission = 0;
515
+ if (copy.accumulated_dip_commission === undefined) copy.accumulated_dip_commission = 0;
516
+ if (copy.base_folder_id === undefined) copy.base_folder_id = null;
517
+ if (!Array.isArray(copy.api_signatures)) copy.api_signatures = [];
518
+ if (copy.point_multiplier === undefined) copy.point_multiplier = 1.0;
519
+ if (copy.lifetime_spend_usd === undefined) copy.lifetime_spend_usd = 0;
520
+ if (copy.pending_ref_count === undefined) copy.pending_ref_count = 0;
521
+
522
+ return copy;
523
+ }
524
+
525
+ static async from_firestore(user_id) {
526
+ const db = new CacheFirestore();
527
+ const user_doc = await db.get_doc(FirestoreCollections.USERS(), user_id);
528
+ if (!user_doc) return null;
529
+
530
+ let rolesMap = new Map();
531
+ if (user_doc.roles && typeof user_doc.roles === 'object') {
532
+ for (const [roleId, roleData] of Object.entries(user_doc.roles)) {
533
+ rolesMap.set(roleId, roleData);
534
+ }
535
+ }
536
+
537
+ let providerLinksMap = null;
538
+ if (user_doc.provider_links && typeof user_doc.provider_links === 'object') {
539
+ providerLinksMap = new Map(Object.entries(user_doc.provider_links));
540
+ }
541
+
542
+ const docId = user_id || user_doc.id || user_doc.email;
543
+ if (!docId) {
544
+ console.error('User document missing ID and email fields');
545
+ return null;
546
+ }
547
+
548
+ let nftsMap = new Map(Object.entries(user_doc.nfts || {}));
549
+ let adCampaignsMap = new Map(Object.entries(user_doc.ad_campaigns || {}));
550
+
551
+ const user = new User(
552
+ docId,
553
+ user_doc.email || null,
554
+ user_doc.user_info || null,
555
+ user_doc.wallet_address || null,
556
+ user_doc.signature || null,
557
+ rolesMap,
558
+ user_doc.total_rep || 0,
559
+ user_doc.total_ref_generic || 0,
560
+ user_doc.total_dip || 0,
561
+ user_doc.claimed_promotions || [],
562
+ user_doc.accumulated_ref_commission || 0,
563
+ user_doc.accumulated_rep_commission || 0,
564
+ user_doc.accumulated_dip_commission || 0,
565
+ providerLinksMap,
566
+ user_doc.base_folder_id || null,
567
+ nftsMap,
568
+ adCampaignsMap,
569
+ user_doc.pending_referral_code || null,
570
+ user_doc.api_signatures || []
571
+ );
572
+
573
+ // ws-user-domain-owners: hydrate owner-method-backed fields that are NOT
574
+ // constructor params. commitTosAndConnect/stampBaseEntitlements/markMigrated/
575
+ // setPendingReferral write these via db.update_doc_fields (targeted field
576
+ // writes onto FirestoreCollections.USERS()), so they exist on the Firestore
577
+ // doc but were previously dropped on every from_firestore() load. Mirrors
578
+ // Cloud ipStorageUtils.js User.from_firestore (commit 105a152).
579
+ user.tos_accepted_at = user_doc.tos_accepted_at || null;
580
+ user.tos_version = user_doc.tos_version || null;
581
+ user.gate_passed_at = user_doc.gate_passed_at || null;
582
+ user.gate_source = user_doc.gate_source || null;
583
+ user.verified_email = user_doc.verified_email || null;
584
+ user.base_entitlements_stamp = user_doc.base_entitlements_stamp || null;
585
+ user.migrated_to = user_doc.migrated_to || null;
586
+ user.migrated_at = user_doc.migrated_at || null;
587
+ user.pending_referral_guild_id = user_doc.pending_referral_guild_id || null;
588
+
589
+ return user;
590
+ }
591
+
592
+ static async to_firestore(user_id, user_info, auth_provider = 'discord') {
593
+ const db = new CacheFirestore();
594
+ const user = await db.get_doc(FirestoreCollections.USERS(), user_id);
595
+ const email = user_info?.email || null;
596
+
597
+ let discord_user_id = null;
598
+ let google_user_id = null;
599
+ let auth_providers = [auth_provider];
600
+
601
+ if (auth_provider === 'discord') {
602
+ discord_user_id = user_id;
603
+ } else if (auth_provider === 'google') {
604
+ if (user_id.startsWith('google_')) {
605
+ google_user_id = user_id.substring(7);
606
+ } else {
607
+ google_user_id = user_id;
608
+ user_id = `google_${user_id}`;
609
+ }
610
+ }
611
+
612
+ const dataToStore = {
613
+ id: user_id,
614
+ email: email,
615
+ discord_user_id: discord_user_id,
616
+ google_user_id: google_user_id,
617
+ auth_providers: auth_providers,
618
+ user_info: user_info,
619
+ wallet_address: null,
620
+ signature: null,
621
+ roles: {},
622
+ nfts: {},
623
+ ad_campaigns: {},
624
+ total_rep: 0,
625
+ total_ref_generic: 0,
626
+ total_dip: 0,
627
+ claimed_promotions: [],
628
+ accumulated_ref_commission: 0,
629
+ accumulated_rep_commission: 0,
630
+ accumulated_dip_commission: 0
631
+ };
632
+
633
+ if (!user) {
634
+ return await db.put_doc(FirestoreCollections.USERS(), user_id, dataToStore);
635
+ } else {
636
+ const updates = { user_info: user_info };
637
+ if (user.email !== email && email) updates.email = email;
638
+
639
+ if (auth_provider === 'discord' && !user.discord_user_id) {
640
+ updates.discord_user_id = discord_user_id;
641
+ }
642
+ if (auth_provider === 'google' && !user.google_user_id) {
643
+ updates.google_user_id = google_user_id;
644
+ }
645
+
646
+ const existingProviders = user.auth_providers || (user.discord_user_id ? ['discord'] : ['google']);
647
+ if (!existingProviders.includes(auth_provider)) {
648
+ updates.auth_providers = [...existingProviders, auth_provider];
649
+ }
650
+
651
+ if (user.roles === undefined) updates.roles = {};
652
+ if (user.nfts === undefined) updates.nfts = {};
653
+ if (user.ad_campaigns === undefined) updates.ad_campaigns = {};
654
+ if (user.total_rep === undefined) updates.total_rep = 0;
655
+ if (user.total_ref_generic === undefined) updates.total_ref_generic = 0;
656
+ if (user.total_dip === undefined) updates.total_dip = 0;
657
+ if (user.claimed_promotions === undefined) updates.claimed_promotions = [];
658
+ if (user.accumulated_ref_commission === undefined) updates.accumulated_ref_commission = 0;
659
+ if (user.accumulated_rep_commission === undefined) updates.accumulated_rep_commission = 0;
660
+ if (user.accumulated_dip_commission === undefined) updates.accumulated_dip_commission = 0;
661
+
662
+ return await db.update_doc_fields(FirestoreCollections.USERS(), user_id, updates);
663
+ }
664
+ }
665
+
666
+ static async findByEmail(email) {
667
+ if (!email) return null;
668
+ const normalized = normalizeEmail(email);
669
+ if (!normalized) return null;
670
+ const db = new CacheFirestore();
671
+ const sanitizedId = User.sanitizeProviderId(normalized);
672
+ const emailIndexKey = `email_${sanitizedId}`;
673
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), emailIndexKey);
674
+ if (index && index.descix_user_id) {
675
+ return await User.from_firestore(index.descix_user_id);
676
+ }
677
+ return User.from_firestore(normalized);
678
+ }
679
+
680
+ static async findByWallet(walletAddress) {
681
+ if (!walletAddress) return null;
682
+ const normalizedAddress = walletAddress.toLowerCase();
683
+ const db = new CacheFirestore();
684
+ const index = await db.get_doc(FirestoreCollections.WALLET_INDEX(), normalizedAddress);
685
+ if (!index || !index.descix_user_id) return null;
686
+ return await User.from_firestore(index.descix_user_id);
687
+ }
688
+
689
+ static async findByProvider(providerType, providerId) {
690
+ if (!providerType || !providerId) return null;
691
+ const db = new CacheFirestore();
692
+ const sanitizedId = User.sanitizeProviderId(providerId);
693
+ const indexKey = `${providerType}_${sanitizedId}`;
694
+ const index = await db.get_doc(FirestoreCollections.PROVIDER_INDEX(), indexKey);
695
+ if (!index || !index.descix_user_id) return null;
696
+ return await User.from_firestore(index.descix_user_id);
697
+ }
698
+
699
+ async linkProvider(providerType, providerId, providerData = {}) {
700
+ if (!providerType || !providerId) {
701
+ console.error('linkProvider: providerType and providerId are required');
702
+ return false;
703
+ }
704
+
705
+ this.provider_links.set(providerType, {
706
+ provider_id: providerId,
707
+ linked_at: Timestamp.now(),
708
+ provider_data: providerData
709
+ });
710
+
711
+ const db = new CacheFirestore();
712
+ const sanitizedId = User.sanitizeProviderId(providerId);
713
+ const indexKey = `${providerType}_${sanitizedId}`;
714
+ await db.put_doc(FirestoreCollections.PROVIDER_INDEX(), indexKey, {
715
+ descix_user_id: this.id,
716
+ provider_type: providerType,
717
+ provider_id: providerId,
718
+ linked_at: Timestamp.now()
719
+ });
720
+
721
+ return await this.to_firestore();
722
+ }
723
+
724
+ static sanitizeProviderId(providerId) {
725
+ if (!providerId) return '';
726
+ if (providerId.includes('@') || providerId.includes('+') || providerId.includes('/')) {
727
+ return crypto.createHash('sha256').update(providerId.toLowerCase()).digest('hex').substring(0, 32);
728
+ }
729
+ return providerId.replace(/[/.+@#[\]]/g, '_');
730
+ }
731
+
732
+ async unlinkProvider(providerType) {
733
+ if (!providerType) {
734
+ console.error('unlinkProvider: providerType is required');
735
+ return false;
736
+ }
737
+
738
+ const providerLink = this.provider_links.get(providerType);
739
+ if (!providerLink) {
740
+ console.warn(`unlinkProvider: Provider ${providerType} not linked to user ${this.id}`);
741
+ return false;
742
+ }
743
+
744
+ this.provider_links.delete(providerType);
745
+
746
+ const db = new CacheFirestore();
747
+ const sanitizedId = User.sanitizeProviderId(providerLink.provider_id);
748
+ const indexKey = `${providerType}_${sanitizedId}`;
749
+ await db.delete_doc(FirestoreCollections.PROVIDER_INDEX(), indexKey);
750
+
751
+ const updatePath = `provider_links.${providerType}`;
752
+ await db.update_doc_fields(FirestoreCollections.USERS(), this.id, {
753
+ [updatePath]: FieldValue.delete()
754
+ });
755
+
756
+ return true;
757
+ }
758
+
759
+ async to_firestore() {
760
+ if (!this.id) {
761
+ console.error('User.to_firestore: User ID is required');
762
+ return false;
763
+ }
764
+ const db = new CacheFirestore();
765
+ return await db.put_doc(FirestoreCollections.USERS(), this.id, this.to_dict());
766
+ }
767
+
768
+ static async findByGoogleId(google_sub) {
769
+ if (!google_sub) return null;
770
+ const db = new CacheFirestore();
771
+ const users = await db.get_docs(FirestoreCollections.USERS(), null, [['google_user_id', '==', google_sub]]);
772
+ if (users && users.length > 0) {
773
+ const userDoc = users[0];
774
+ return User.from_firestore(userDoc.id);
775
+ }
776
+ const userId = `google_${google_sub}`;
777
+ return await User.from_firestore(userId);
778
+ }
779
+
780
+ async addApiSignature(name, walletAddress, signature, options = {}) {
781
+ const signatureId = crypto.randomUUID();
782
+ const signatureRecord = {
783
+ id: signatureId,
784
+ name: name || 'Unnamed Client',
785
+ wallet_address: walletAddress,
786
+ signature: signature,
787
+ created_at: new Date().toISOString(),
788
+ last_used: null,
789
+ permissions: options.permissions || { read: true, write: false, admin: false },
790
+ communities: options.communities || []
791
+ };
792
+
793
+ this.api_signatures.push(signatureRecord);
794
+
795
+ const db = new CacheFirestore();
796
+ const signatureKey = crypto.createHash('sha256').update(signature).digest('hex').substring(0, 32);
797
+ await db.put_doc(FirestoreCollections.SIGNATURE_INDEX(), signatureKey, {
798
+ user_id: this.id,
799
+ signature_id: signatureId,
800
+ wallet_address: walletAddress,
801
+ created_at: Timestamp.now()
802
+ });
803
+
804
+ await this.to_firestore();
805
+ return signatureRecord;
806
+ }
807
+
808
+ async revokeApiSignature(signatureId) {
809
+ const sigIndex = this.api_signatures.findIndex(s => s.id === signatureId);
810
+ if (sigIndex === -1) {
811
+ console.warn(`revokeApiSignature: Signature ${signatureId} not found`);
812
+ return false;
813
+ }
814
+
815
+ const sig = this.api_signatures[sigIndex];
816
+
817
+ const db = new CacheFirestore();
818
+ const signatureKey = crypto.createHash('sha256').update(sig.signature).digest('hex').substring(0, 32);
819
+ await db.delete_doc(FirestoreCollections.SIGNATURE_INDEX(), signatureKey);
820
+
821
+ this.api_signatures.splice(sigIndex, 1);
822
+ await this.to_firestore();
823
+
824
+ return true;
825
+ }
826
+
827
+ static async findBySignature(signature) {
828
+ if (!signature) return null;
829
+
830
+ const db = new CacheFirestore();
831
+ const signatureKey = crypto.createHash('sha256').update(signature).digest('hex').substring(0, 32);
832
+ const indexEntry = await db.get_doc(FirestoreCollections.SIGNATURE_INDEX(), signatureKey);
833
+
834
+ if (!indexEntry || !indexEntry.user_id) return null;
835
+
836
+ const user = await User.from_firestore(indexEntry.user_id);
837
+ if (!user) return null;
838
+
839
+ const signatureRecord = user.api_signatures.find(s => s.id === indexEntry.signature_id);
840
+ if (!signatureRecord) return null;
841
+
842
+ signatureRecord.last_used = new Date().toISOString();
843
+ await user.to_firestore();
844
+
845
+ return { user, signatureRecord };
846
+ }
847
+
848
+ listApiSignatures() {
849
+ return this.api_signatures.map(sig => ({
850
+ ...sig,
851
+ signature: sig.signature ? `${sig.signature.substring(0, 10)}...${sig.signature.substring(sig.signature.length - 6)}` : null
852
+ }));
853
+ }
854
+
855
+ hasRole(role_id) {
856
+ if (!this.roles.has(role_id)) {
857
+ return false;
858
+ }
859
+ const roleData = this.roles.get(role_id);
860
+ if (roleData && roleData.expires_date) {
861
+ const expiryDate = roleData.expires_date instanceof Timestamp
862
+ ? roleData.expires_date.toDate()
863
+ : (roleData.expires_date instanceof Date ? roleData.expires_date : new Date(roleData.expires_date));
864
+ return expiryDate > new Date();
865
+ }
866
+ return true;
867
+ }
868
+
869
+ getRoleAcquisitionDate(role_id) {
870
+ return this.roles.get(role_id)?.acquired_date;
871
+ }
872
+
873
+ async addRole(role_id, acquisitionDetails = { acquired_date: Timestamp.now() }) {
874
+ const updatePath = `roles.${role_id}`;
875
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, { [updatePath]: acquisitionDetails });
876
+ }
877
+
878
+ async removeRole(role_id) {
879
+ const updatePath = `roles.${role_id}`;
880
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, { [updatePath]: FieldValue.delete() });
881
+ }
882
+
883
+ async checkSubscription(context = {}) {
884
+ const { communityId, appId, target = 'chat' } = context;
885
+ if (!communityId) return { verified: false, message: 'Community ID required' };
886
+
887
+ const subscriptionRoleIds = [];
888
+ subscriptionRoleIds.push(`community_${communityId}_${target}`);
889
+ subscriptionRoleIds.push(`community_${communityId}_chat`);
890
+ if (appId) {
891
+ subscriptionRoleIds.push(`app_${communityId}_${appId}_${target}`);
892
+ subscriptionRoleIds.push(`app_${communityId}_${appId}_chat`);
893
+ }
894
+
895
+ let activeRoleId = null;
896
+ let expiresAt = null;
897
+
898
+ for (const roleId of subscriptionRoleIds) {
899
+ if (this.hasRole(roleId)) {
900
+ activeRoleId = roleId;
901
+ const roleData = this.roles.get(roleId);
902
+ if (roleData && roleData.expires_date) {
903
+ expiresAt = roleData.expires_date instanceof Timestamp
904
+ ? roleData.expires_date.toDate()
905
+ : (roleData.expires_date instanceof Date ? roleData.expires_date : new Date(roleData.expires_date));
906
+ }
907
+ return {
908
+ verified: true,
909
+ hasSubscription: true,
910
+ activeRoleId: activeRoleId,
911
+ expiresAt: expiresAt ? expiresAt.toISOString() : null,
912
+ communityId: communityId,
913
+ appId: appId,
914
+ target: target,
915
+ message: `Access verified${expiresAt ? ` (expires: ${expiresAt.toISOString()})` : ''}`
916
+ };
917
+ }
918
+ }
919
+
920
+ // Check Purchases (fallback)
921
+ const purchases = await this.get_purchases();
922
+ for (const purchase of purchases) {
923
+ if (purchase.ExpiresAt) {
924
+ const expiryDate = purchase.ExpiresAt instanceof Timestamp
925
+ ? purchase.ExpiresAt.toDate()
926
+ : (purchase.ExpiresAt instanceof Date ? purchase.ExpiresAt : new Date(purchase.ExpiresAt));
927
+
928
+ if (expiryDate > new Date()) {
929
+ const productPath = purchase.ProductPath || '';
930
+ if (productPath.includes(`/Community/${communityId}`) ||
931
+ (appId && productPath.includes(`/App/${appId}`))) {
932
+ return {
933
+ verified: true,
934
+ hasSubscription: true,
935
+ expiresAt: expiryDate.toISOString(),
936
+ communityId: communityId,
937
+ appId: appId,
938
+ target: target,
939
+ message: `Access verified via purchase (expires: ${expiryDate.toISOString()})`
940
+ };
941
+ }
942
+ }
943
+ }
944
+ }
945
+
946
+ return {
947
+ verified: false,
948
+ hasSubscription: false,
949
+ communityId: communityId,
950
+ appId: appId,
951
+ target: target,
952
+ message: `No active subscription found for ${target} access.`
953
+ };
954
+ }
955
+
956
+ async set_wallet_address_and_signature(wallet_address, signature) {
957
+ const normalizedAddress = wallet_address?.toLowerCase() || wallet_address;
958
+
959
+ if (normalizedAddress) {
960
+ const existingUser = await User.findByWallet(normalizedAddress);
961
+ if (existingUser && existingUser.id !== this.id) {
962
+ throw new Error(`Wallet address ${wallet_address} is already associated with another account`);
963
+ }
964
+
965
+ if (this.wallet_address && this.wallet_address !== normalizedAddress) {
966
+ await this.db.delete_doc(FirestoreCollections.WALLET_INDEX(), this.wallet_address);
967
+ }
968
+
969
+ await this.db.put_doc(FirestoreCollections.WALLET_INDEX(), normalizedAddress, {
970
+ descix_user_id: this.id,
971
+ wallet_address: normalizedAddress,
972
+ linked_at: Timestamp.now()
973
+ });
974
+ }
975
+
976
+ this.wallet_address = normalizedAddress;
977
+ this.signature = signature;
978
+ const updates = { wallet_address: normalizedAddress, signature: signature };
979
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
980
+ }
981
+
982
+ // --- User-Domain Owner Methods (ws-user-domain-owners) ---
983
+ async commitTosAndConnect({ tos_version, gate_source, verified_email } = {}) {
984
+ const updates = {
985
+ tos_accepted_at: Timestamp.now(),
986
+ tos_version: tos_version || '1.0.0',
987
+ gate_passed_at: Timestamp.now(),
988
+ gate_source: gate_source
989
+ };
990
+ this.tos_accepted_at = updates.tos_accepted_at;
991
+ this.tos_version = updates.tos_version;
992
+ this.gate_passed_at = updates.gate_passed_at;
993
+ this.gate_source = updates.gate_source;
994
+ if (verified_email) {
995
+ const normalized = normalizeEmail(verified_email);
996
+ updates.verified_email = normalized;
997
+ updates.email = normalized;
998
+ this.verified_email = normalized;
999
+ this.email = normalized;
1000
+ }
1001
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1002
+ }
1003
+
1004
+ isConnected() {
1005
+ return !!this.tos_accepted_at;
1006
+ }
1007
+
1008
+ async stampBaseEntitlements(stamp) {
1009
+ const updates = { base_entitlements_stamp: stamp };
1010
+ this.base_entitlements_stamp = stamp;
1011
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1012
+ }
1013
+
1014
+ hasBaseEntitlementStamp(stamp) {
1015
+ return this.base_entitlements_stamp === stamp;
1016
+ }
1017
+
1018
+ async setPendingReferral(code, guild_id = null) {
1019
+ const updates = { pending_referral_code: code };
1020
+ this.pending_referral_code = code;
1021
+ if (guild_id !== null) {
1022
+ updates.pending_referral_guild_id = guild_id;
1023
+ this.pending_referral_guild_id = guild_id;
1024
+ }
1025
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1026
+ }
1027
+
1028
+ async clearPendingReferral() {
1029
+ // Symmetric with setPendingReferral(code, guild_id): clears BOTH fields it can set.
1030
+ // Mirrors Cloud ipStorageUtils.js User.clearPendingReferral (commit 111318e).
1031
+ const updates = { pending_referral_code: null, pending_referral_guild_id: null };
1032
+ this.pending_referral_code = null;
1033
+ this.pending_referral_guild_id = null;
1034
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1035
+ }
1036
+
1037
+ async setBaseFolderId(id) {
1038
+ const updates = { base_folder_id: id };
1039
+ this.base_folder_id = id;
1040
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1041
+ }
1042
+
1043
+ async markMigrated(to) {
1044
+ const updates = { migrated_to: to, migrated_at: Timestamp.now() };
1045
+ this.migrated_to = updates.migrated_to;
1046
+ this.migrated_at = updates.migrated_at;
1047
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, updates);
1048
+ }
1049
+ // --- End User-Domain Owner Methods ---
1050
+
1051
+ async incrementRep(amount) {
1052
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'total_rep', FieldValue.increment(amount));
1053
+ }
1054
+ async incrementDip(amount) {
1055
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'total_dip', FieldValue.increment(amount));
1056
+ }
1057
+ async incrementRefGeneric(amount) {
1058
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'total_ref_generic', FieldValue.increment(amount));
1059
+ }
1060
+ async incrementRefCommission(amount) {
1061
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'accumulated_ref_commission', FieldValue.increment(amount));
1062
+ }
1063
+ async incrementRepCommission(amount) {
1064
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'accumulated_rep_commission', FieldValue.increment(amount));
1065
+ }
1066
+ async incrementDipCommission(amount) {
1067
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'accumulated_dip_commission', FieldValue.increment(amount));
1068
+ }
1069
+ async incrementPendingRef(amount) {
1070
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'pending_ref_count', FieldValue.increment(amount));
1071
+ }
1072
+ async addClaimedPromotion(promotion_custom_id) {
1073
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'claimed_promotions', FieldValue.arrayUnion(promotion_custom_id));
1074
+ }
1075
+ async resetGenericRef() {
1076
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'total_ref_generic', 0);
1077
+ }
1078
+ async resetClaimedPromotions() {
1079
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'claimed_promotions', []);
1080
+ }
1081
+ async resetRefCommission() {
1082
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'accumulated_ref_commission', 0);
1083
+ }
1084
+ async resetRepCommission() {
1085
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'accumulated_rep_commission', 0);
1086
+ }
1087
+ async resetDipCommission() {
1088
+ return await this.db.update_doc_field(FirestoreCollections.USERS(), this.id, 'accumulated_dip_commission', 0);
1089
+ }
1090
+
1091
+ async getCommunityStats(community_id) {
1092
+ let stats = await UserCommunityStats.from_firestore(this.id, community_id);
1093
+ if (!stats) {
1094
+ stats = new UserCommunityStats(this.id, community_id);
1095
+ }
1096
+ return stats;
1097
+ }
1098
+
1099
+ async incrementCommunityRep(community_id, amount) {
1100
+ const statsPath = FirestoreCollections.USER_COMMUNITY_STATS(this.id);
1101
+ const statsExists = await this.db.doc_exists(statsPath, community_id);
1102
+ if (!statsExists) {
1103
+ const initialStats = new UserCommunityStats(this.id, community_id, amount, 0, 0);
1104
+ return await initialStats.to_firestore();
1105
+ } else {
1106
+ return await this.db.update_doc_field(statsPath, community_id, 'community_rep', FieldValue.increment(amount));
1107
+ }
1108
+ }
1109
+
1110
+ async incrementCommunityRef(community_id, amount) {
1111
+ const statsPath = FirestoreCollections.USER_COMMUNITY_STATS(this.id);
1112
+ const statsExists = await this.db.doc_exists(statsPath, community_id);
1113
+ if (!statsExists) {
1114
+ const initialStats = new UserCommunityStats(this.id, community_id, 0, amount, 0);
1115
+ return await initialStats.to_firestore();
1116
+ } else {
1117
+ return await this.db.update_doc_field(statsPath, community_id, 'community_ref', FieldValue.increment(amount));
1118
+ }
1119
+ }
1120
+
1121
+ async incrementCommunityDip(community_id, amount) {
1122
+ const statsPath = FirestoreCollections.USER_COMMUNITY_STATS(this.id);
1123
+ const statsExists = await this.db.doc_exists(statsPath, community_id);
1124
+ if (!statsExists) {
1125
+ const initialStats = new UserCommunityStats(this.id, community_id, 0, 0, amount);
1126
+ return await initialStats.to_firestore();
1127
+ } else {
1128
+ return await this.db.update_doc_field(statsPath, community_id, 'community_dip', FieldValue.increment(amount));
1129
+ }
1130
+ }
1131
+
1132
+ async resetCommunityRef(community_id) {
1133
+ const statsPath = FirestoreCollections.USER_COMMUNITY_STATS(this.id);
1134
+ const statsExists = await this.db.doc_exists(statsPath, community_id);
1135
+ if (statsExists) {
1136
+ return await this.db.update_doc_field(statsPath, community_id, 'community_ref', 0);
1137
+ }
1138
+ return true;
1139
+ }
1140
+
1141
+ async get_purchases() {
1142
+ const purchaseDocs = await this.db.get_docs(FirestoreCollections.USER_PURCHASES(this.id));
1143
+ if (!purchaseDocs) return [];
1144
+ return purchaseDocs.map(doc => doc ? Purchase.from_dict(doc, this.id) : null)
1145
+ .filter(p => p !== null);
1146
+ }
1147
+
1148
+ static async get_user_purchased_community_and_app_objects(user_id) {
1149
+ const db = new CacheFirestore();
1150
+ const purchaseDocs = await db.get_docs(FirestoreCollections.USER_PURCHASES(user_id));
1151
+ const communityIds = new Set();
1152
+ const appPairs = [];
1153
+
1154
+ if (purchaseDocs) {
1155
+ const communityPurchases = [];
1156
+ const appPurchases = [];
1157
+ for (const purchaseData of purchaseDocs) {
1158
+ const purchase = Purchase.from_dict(purchaseData, user_id);
1159
+ if (!purchase) continue;
1160
+ if (purchase.ProductType === ProductTypes.COMMUNITY) communityPurchases.push(purchase);
1161
+ else if (purchase.ProductType === ProductTypes.APP) appPurchases.push(purchase);
1162
+ }
1163
+
1164
+ for (const purchase of communityPurchases) {
1165
+ const parts = purchase.ProductPath.split('/');
1166
+ if (parts.length >= 2 && parts[0].toLowerCase() === 'community') {
1167
+ communityIds.add(parts[1]);
1168
+ }
1169
+ }
1170
+
1171
+ const productLookups = await Promise.all(
1172
+ appPurchases.map(p => db.get_doc('Products', p.PurchaseId))
1173
+ );
1174
+ for (let i = 0; i < appPurchases.length; i++) {
1175
+ const productDoc = productLookups[i];
1176
+ const purchase = appPurchases[i];
1177
+ if (productDoc?.community_id) {
1178
+ appPairs.push({ community: productDoc.community_id, app: purchase.PurchaseId });
1179
+ } else {
1180
+ const parts = purchase.ProductPath.split('/');
1181
+ if (parts.length >= 4 && parts[0].toLowerCase() === 'community' && parts[2].toLowerCase() === 'apps') {
1182
+ appPairs.push({ community: parts[1], app: parts[3] });
1183
+ }
1184
+ }
1185
+ }
1186
+ }
1187
+
1188
+ const communities = communityIds.size > 0
1189
+ ? (await Promise.all(Array.from(communityIds).map(id => Community.from_firestore(id)))).filter(c => c !== null)
1190
+ : [];
1191
+ const apps = appPairs.length > 0
1192
+ ? (await Promise.all(appPairs.map(p => App.from_firestore(p.community, p.app)))).filter(a => a !== null)
1193
+ : [];
1194
+
1195
+ return { communities, apps };
1196
+ }
1197
+
1198
+ async get_user_info() {
1199
+ const user = await User.from_firestore(this.id);
1200
+ return user ? user.user_info : null;
1201
+ }
1202
+
1203
+ async set_user_info(user_info) {
1204
+ return await this.db.update_doc_fields(FirestoreCollections.USERS(), this.id, { user_info: user_info });
1205
+ }
1206
+
1207
+ async is_registered() {
1208
+ return await this.db.doc_exists(FirestoreCollections.USERS(), this.id);
1209
+ }
1210
+
1211
+ async get_user_purchases(product_type = null) {
1212
+ let whereClause = null;
1213
+ if (product_type) {
1214
+ whereClause = [['ProductType', '==', product_type]];
1215
+ }
1216
+ const purchaseDocs = await this.db.get_docs(FirestoreCollections.USER_PURCHASES(this.id), null, whereClause);
1217
+ if (!purchaseDocs) return [];
1218
+ return purchaseDocs.map(doc => doc ? Purchase.from_dict(doc, this.id) : null)
1219
+ .filter(p => p !== null);
1220
+ }
1221
+
1222
+ async get_user_communities() {
1223
+ const community_purchases = await this.get_user_purchases(ProductTypes.COMMUNITY);
1224
+ const doc_ids = community_purchases.map(purchase => {
1225
+ const parts = purchase.ProductPath.split('/');
1226
+ return (parts.length >= 2 && parts[0].toLowerCase() === 'community') ? parts[1] : null;
1227
+ }).filter(id => id !== null);
1228
+
1229
+ if (doc_ids.length === 0) return [];
1230
+
1231
+ const communityPromises = doc_ids.map(id => Community.from_firestore(id));
1232
+ const communities = await Promise.all(communityPromises);
1233
+ return communities.filter(c => c !== null);
1234
+ }
1235
+
1236
+ async purchase_product_firestore(product_path, product_type, project_token = null, purchase_price = 0.0, purchase_id = null) {
1237
+ const utils = getCloudConfig();
1238
+ const token = project_token || utils.DEFAULT_COMMUNITY_ID;
1239
+ const db = new CacheFirestore();
1240
+ let userPurchasesCollectionPath = FirestoreCollections.USER_PURCHASES(this.id);
1241
+
1242
+ if (purchase_id && product_type === ProductTypes.APP) {
1243
+ const existing = await db.get_doc(userPurchasesCollectionPath, purchase_id);
1244
+ if (existing) {
1245
+ console.log(`User ${this.id} already has entitlement for ${purchase_id}. Skipping.`);
1246
+ return { success: true, isNewPurchase: false };
1247
+ }
1248
+ } else if (product_type !== ProductTypes.ROLE) {
1249
+ const existing = await db.get_docs(userPurchasesCollectionPath, null, [['ProductPath', '==', product_path]]);
1250
+ if (existing && existing.length > 0) {
1251
+ console.log(`User ${this.id} already purchased ${product_path}. Skipping.`);
1252
+ return { success: true, isNewPurchase: false };
1253
+ }
1254
+ }
1255
+
1256
+ if (!purchase_id) purchase_id = crypto.randomUUID();
1257
+ const purchase = new Purchase(product_path, token, purchase_price, new Date(), this.id, product_type, purchase_id);
1258
+ const purchase_success = await purchase.to_firestore();
1259
+
1260
+ if (purchase_success && product_type === ProductTypes.COMMUNITY) {
1261
+ const parts = product_path.split('/');
1262
+ if (parts.length >= 2 && parts[0].toLowerCase() === 'community') {
1263
+ const community_id = parts[1];
1264
+ const community = await Community.from_firestore(community_id);
1265
+ if (community) {
1266
+ const defaultAppId = community.default_app_id || utils.DEFAULT_APP_ID;
1267
+ const defaultAppProductPath = FirestoreDocumentPath.APP(community_id, defaultAppId);
1268
+ const existing_app_purchase = await db.get_doc(userPurchasesCollectionPath, defaultAppId);
1269
+ if (!existing_app_purchase) {
1270
+ console.log(`Adding default app purchase for user ${this.id}, community ${community_id}, app ${defaultAppId}`);
1271
+ const defaultApp = await App.from_firestore(community_id, defaultAppId);
1272
+ if (defaultApp) {
1273
+ const default_app_purchase = new Purchase(
1274
+ defaultAppProductPath,
1275
+ community.token_symbol,
1276
+ defaultApp.price || 0.0,
1277
+ new Date(), this.id, ProductTypes.APP, defaultAppId
1278
+ );
1279
+ await default_app_purchase.to_firestore();
1280
+ } else {
1281
+ console.error(`Default app ${defaultAppId} not found in community ${community_id} when trying to grant purchase to user ${this.id}`);
1282
+ }
1283
+ }
1284
+ } else {
1285
+ console.error(`Could not find community ${community_id} when trying to add default app purchase for user ${this.id}`);
1286
+ }
1287
+ }
1288
+ }
1289
+ return { success: purchase_success, isNewPurchase: true };
1290
+ }
1291
+ }
1292
+
1293
+ // --- Community Class ---
1294
+
1295
+ export class Community {
1296
+ constructor(
1297
+ community_id, community_name, community_description, community_email,
1298
+ default_app_id, ip_site_gcs_path_url, default_knowledgebase_name,
1299
+ is_public = false, member_count = 1, disccusion_count = 0,
1300
+ token_symbol = null, token_contract_address = null, icon_url = "", owner_id = "",
1301
+ treasury_wallet_address = null, total_community_rep = 0, total_community_ref = 0, total_community_dip = 0,
1302
+ airdrop_config = null, price = 0,
1303
+ ref_reward_rate = 10, guild_ref_commission_rate = 0.1,
1304
+ guild_rep_commission_rate = 0.1, guild_dip_commission_rate = 0.1,
1305
+ mcp_rag_min_tokens = 0, auto_purchase_apps = null,
1306
+ signup_bonus_ref = null,
1307
+ pool_config = null,
1308
+ google_group_email = null,
1309
+ discord_guild_id = null,
1310
+ sponsor_slots = [],
1311
+ token_lifecycle = null,
1312
+ reserve_wallets = null,
1313
+ reserves_by_chain = null,
1314
+ drive_folder_id = "",
1315
+ promo_video_url = null
1316
+ ) {
1317
+ const utils = getCloudConfig();
1318
+ this.community_id = community_id;
1319
+ this.community_name = community_name;
1320
+ this.community_description = community_description;
1321
+ this.community_email = community_email;
1322
+ this.is_public = is_public;
1323
+ this.member_count = member_count;
1324
+ this.disccusion_count = disccusion_count;
1325
+ this.default_knowledgebase_name = default_knowledgebase_name;
1326
+ this.default_app_id = default_app_id || utils.DEFAULT_APP_ID;
1327
+ this.token_symbol = token_symbol ? String(token_symbol).toUpperCase() : community_id.split("@")[0].toUpperCase().substring(0, 5);
1328
+ this.token_contract_address = token_contract_address;
1329
+ this.icon_url = icon_url;
1330
+ this.owner_id = owner_id;
1331
+ this.ip_site_gcs_path_url = ip_site_gcs_path_url;
1332
+ this.treasury_wallet_address = treasury_wallet_address;
1333
+ this.total_community_rep = total_community_rep;
1334
+ this.total_community_ref = total_community_ref;
1335
+ this.total_community_dip = total_community_dip;
1336
+ this.airdrop_config = airdrop_config || {
1337
+ next_airdrop_timestamp: null, frequency_days: 30, dip_percentage: 25, ref_percentage: 10
1338
+ };
1339
+ this.price = price;
1340
+ this.ref_reward_rate = ref_reward_rate;
1341
+ this.guild_ref_commission_rate = guild_ref_commission_rate;
1342
+ this.guild_rep_commission_rate = guild_rep_commission_rate;
1343
+ this.guild_dip_commission_rate = guild_dip_commission_rate;
1344
+ this.mcp_rag_min_tokens = mcp_rag_min_tokens || 0;
1345
+ this.auto_purchase_apps = auto_purchase_apps || ['daita'];
1346
+ this.pool_config = pool_config || null;
1347
+ this.google_group_email = google_group_email || null;
1348
+ this.discord_guild_id = discord_guild_id || null;
1349
+ this.sponsor_slots = sponsor_slots || [];
1350
+ this.token_lifecycle = token_lifecycle || null;
1351
+ this.reserve_wallets = reserve_wallets || null;
1352
+ this.reserves_by_chain = reserves_by_chain || null;
1353
+ this.drive_folder_id = drive_folder_id || "";
1354
+ this.promo_video_url = promo_video_url || null;
1355
+
1356
+ this.db = new CacheFirestore();
1357
+ }
1358
+
1359
+ get product_path() {
1360
+ return FirestoreDocumentPath.COMMUNITY(this.community_id);
1361
+ }
1362
+
1363
+ to_dict() {
1364
+ const copy = { ...this };
1365
+ delete copy.db;
1366
+ if (copy.airdrop_config && copy.airdrop_config.next_airdrop_timestamp instanceof Date) {
1367
+ copy.airdrop_config.next_airdrop_timestamp = Timestamp.fromDate(copy.airdrop_config.next_airdrop_timestamp);
1368
+ } else if (copy.airdrop_config && copy.airdrop_config.next_airdrop_timestamp && !(copy.airdrop_config.next_airdrop_timestamp instanceof Timestamp)) {
1369
+ try {
1370
+ const parsedDate = new Date(copy.airdrop_config.next_airdrop_timestamp);
1371
+ copy.airdrop_config.next_airdrop_timestamp = !isNaN(parsedDate) ? Timestamp.fromDate(parsedDate) : null;
1372
+ } catch (e) { copy.airdrop_config.next_airdrop_timestamp = null; }
1373
+ }
1374
+ if (copy.token_symbol) copy.token_symbol = copy.token_symbol.toUpperCase();
1375
+ if (copy.ref_reward_rate === undefined) copy.ref_reward_rate = 10;
1376
+ if (copy.guild_ref_commission_rate === undefined) copy.guild_ref_commission_rate = 0.1;
1377
+ if (copy.guild_rep_commission_rate === undefined) copy.guild_rep_commission_rate = 0.1;
1378
+ if (copy.guild_dip_commission_rate === undefined) copy.guild_dip_commission_rate = 0.1;
1379
+ if (copy.mcp_rag_min_tokens === undefined) copy.mcp_rag_min_tokens = 0;
1380
+ if (copy.auto_purchase_apps === undefined) copy.auto_purchase_apps = ['daita'];
1381
+ if (copy.pool_config === undefined) copy.pool_config = null;
1382
+ if (copy.google_group_email === undefined) copy.google_group_email = null;
1383
+ if (copy.discord_guild_id === undefined) copy.discord_guild_id = null;
1384
+ if (copy.sponsor_slots === undefined) copy.sponsor_slots = [];
1385
+ if (copy.token_lifecycle === undefined) copy.token_lifecycle = null;
1386
+ if (copy.reserve_wallets === undefined) copy.reserve_wallets = null;
1387
+ if (copy.reserves_by_chain === undefined) copy.reserves_by_chain = null;
1388
+ if (copy.promo_video_url === undefined) copy.promo_video_url = null;
1389
+ return copy;
1390
+ }
1391
+
1392
+ static from_dict(doc) {
1393
+ if (!doc) return null;
1394
+
1395
+ let airdrop_config = doc.airdrop_config || null;
1396
+ if (airdrop_config?.next_airdrop_timestamp instanceof Timestamp) {
1397
+ airdrop_config = { ...airdrop_config, next_airdrop_timestamp: airdrop_config.next_airdrop_timestamp.toDate() };
1398
+ }
1399
+
1400
+ return new Community(
1401
+ doc.community_id,
1402
+ doc.community_name, doc.community_description, doc.community_email,
1403
+ doc.default_app_id, doc.ip_site_gcs_path_url, doc.default_knowledgebase_name,
1404
+ doc.is_public, doc.member_count, doc.disccusion_count,
1405
+ doc.token_symbol, doc.token_contract_address || null,
1406
+ doc.icon_url, doc.owner_id || "", doc.treasury_wallet_address || null,
1407
+ doc.total_community_rep || 0, doc.total_community_ref || 0, doc.total_community_dip || 0,
1408
+ airdrop_config, doc.price || 0,
1409
+ doc.ref_reward_rate !== undefined ? doc.ref_reward_rate : 10,
1410
+ doc.guild_ref_commission_rate !== undefined ? doc.guild_ref_commission_rate : 0.1,
1411
+ doc.guild_rep_commission_rate !== undefined ? doc.guild_rep_commission_rate : 0.1,
1412
+ doc.guild_dip_commission_rate !== undefined ? doc.guild_dip_commission_rate : 0.1,
1413
+ doc.mcp_rag_min_tokens !== undefined ? doc.mcp_rag_min_tokens : 0,
1414
+ doc.auto_purchase_apps || null,
1415
+ doc.signup_bonus_ref !== undefined ? doc.signup_bonus_ref : null,
1416
+ doc.pool_config || null,
1417
+ doc.google_group_email || null,
1418
+ doc.discord_guild_id || null,
1419
+ doc.sponsor_slots || [],
1420
+ doc.token_lifecycle || null,
1421
+ doc.reserve_wallets || null,
1422
+ doc.reserves_by_chain || null,
1423
+ doc.drive_folder_id || "",
1424
+ doc.promo_video_url || null
1425
+ );
1426
+ }
1427
+
1428
+ async to_firestore() {
1429
+ if (this.token_symbol) this.token_symbol = this.token_symbol.toUpperCase();
1430
+ return await this.db.put_doc(FirestoreCollections.COMMUNITY(), this.community_id, this.to_dict());
1431
+ }
1432
+
1433
+ static async from_firestore(community_id) {
1434
+ const db = new CacheFirestore();
1435
+ const doc = await db.get_doc(FirestoreCollections.COMMUNITY(), community_id);
1436
+ if (!doc) return null;
1437
+
1438
+ let airdrop_config = doc.airdrop_config || null;
1439
+ if (airdrop_config?.next_airdrop_timestamp instanceof Timestamp) {
1440
+ airdrop_config = { ...airdrop_config, next_airdrop_timestamp: airdrop_config.next_airdrop_timestamp.toDate() };
1441
+ }
1442
+
1443
+ return new Community(
1444
+ doc.community_id || community_id,
1445
+ doc.community_name, doc.community_description, doc.community_email,
1446
+ doc.default_app_id, doc.ip_site_gcs_path_url, doc.default_knowledgebase_name,
1447
+ doc.is_public, doc.member_count, doc.disccusion_count,
1448
+ doc.token_symbol, doc.token_contract_address || null,
1449
+ doc.icon_url, doc.owner_id || "", doc.treasury_wallet_address || null,
1450
+ doc.total_community_rep || 0, doc.total_community_ref || 0, doc.total_community_dip || 0,
1451
+ airdrop_config, doc.price || 0,
1452
+ doc.ref_reward_rate !== undefined ? doc.ref_reward_rate : 10,
1453
+ doc.guild_ref_commission_rate !== undefined ? doc.guild_ref_commission_rate : 0.1,
1454
+ doc.guild_rep_commission_rate !== undefined ? doc.guild_rep_commission_rate : 0.1,
1455
+ doc.guild_dip_commission_rate !== undefined ? doc.guild_dip_commission_rate : 0.1,
1456
+ doc.mcp_rag_min_tokens !== undefined ? doc.mcp_rag_min_tokens : 0,
1457
+ doc.auto_purchase_apps || null,
1458
+ doc.signup_bonus_ref !== undefined ? doc.signup_bonus_ref : null,
1459
+ doc.pool_config || null,
1460
+ doc.google_group_email || null,
1461
+ doc.discord_guild_id || null,
1462
+ doc.sponsor_slots || [],
1463
+ doc.token_lifecycle || null,
1464
+ doc.reserve_wallets || null,
1465
+ doc.reserves_by_chain || null,
1466
+ doc.drive_folder_id || "",
1467
+ doc.promo_video_url || null
1468
+ );
1469
+ }
1470
+
1471
+ async incrementTotalRep(amount) {
1472
+ return await this.db.update_doc_field(FirestoreCollections.COMMUNITY(), this.community_id, 'total_community_rep', FieldValue.increment(amount));
1473
+ }
1474
+ async incrementTotalRef(amount) {
1475
+ return await this.db.update_doc_field(FirestoreCollections.COMMUNITY(), this.community_id, 'total_community_ref', FieldValue.increment(amount));
1476
+ }
1477
+ async incrementTotalDip(amount) {
1478
+ return await this.db.update_doc_field(FirestoreCollections.COMMUNITY(), this.community_id, 'total_community_dip', FieldValue.increment(amount));
1479
+ }
1480
+ async incrementMemberCount(amount = 1) {
1481
+ return await this.db.update_doc_field(FirestoreCollections.COMMUNITY(), this.community_id, 'member_count', FieldValue.increment(amount));
1482
+ }
1483
+ async updateAirdropConfig(newConfig) {
1484
+ if (newConfig.next_airdrop_timestamp instanceof Date) {
1485
+ newConfig.next_airdrop_timestamp = Timestamp.fromDate(newConfig.next_airdrop_timestamp);
1486
+ } else if (typeof newConfig.next_airdrop_timestamp === 'string') {
1487
+ try {
1488
+ const parsedDate = new Date(newConfig.next_airdrop_timestamp);
1489
+ newConfig.next_airdrop_timestamp = !isNaN(parsedDate) ? Timestamp.fromDate(parsedDate) : null;
1490
+ } catch (e) { newConfig.next_airdrop_timestamp = null; }
1491
+ } else if (newConfig.next_airdrop_timestamp !== null && !(newConfig.next_airdrop_timestamp instanceof Timestamp)) {
1492
+ newConfig.next_airdrop_timestamp = null;
1493
+ }
1494
+ return await this.db.update_doc_fields(FirestoreCollections.COMMUNITY(), this.community_id, { airdrop_config: newConfig });
1495
+ }
1496
+
1497
+ /**
1498
+ * The apps of one community.
1499
+ *
1500
+ * THROWS on an unreadable collection; returns `[]` only for a community that genuinely has no
1501
+ * apps. `CacheFirestore.get_docs` signals the two outcomes differently — `[]` for an empty
1502
+ * collection, `null` for a read that FAILED (it logs and swallows the Firestore error, see
1503
+ * `@descix/cloud-core` storageUtils.js) — and this method used to collapse both to `[]`. That
1504
+ * made "the read broke" indistinguishable from "there is nothing here" at every call site: a
1505
+ * caller deriving a permission scope, a listing, or a count from the result would report a
1506
+ * FABRICATED ZERO as fact, with no error anywhere. Failing loud here is the only place the
1507
+ * distinction still exists.
1508
+ *
1509
+ * @param {string} community_id
1510
+ * @param {Array|null} [where_clause]
1511
+ * @returns {Promise<App[]>} the community's apps; `[]` means MEASURED-empty
1512
+ * @throws {Error} code `COMMUNITY_APPS_UNREADABLE` when the underlying read failed
1513
+ */
1514
+ static async get_apps(community_id, where_clause = null) {
1515
+ const db = new CacheFirestore();
1516
+ const appDocs = await db.get_docs(FirestoreCollections.APPS(community_id), null, where_clause);
1517
+ if (appDocs === null) {
1518
+ const err = new Error(
1519
+ `Community.get_apps("${community_id}") could not read ${FirestoreCollections.APPS(community_id)}: ` +
1520
+ `the underlying CacheFirestore.get_docs returned null, which means the read FAILED (an empty ` +
1521
+ `collection returns []). Refusing to report an empty app list for a community whose apps are ` +
1522
+ `unknown — a fabricated zero read as fact is worse than an error.`
1523
+ );
1524
+ err.code = 'COMMUNITY_APPS_UNREADABLE';
1525
+ err.statusCode = 503;
1526
+ err.data = { code: 'COMMUNITY_APPS_UNREADABLE', community_id };
1527
+ throw err;
1528
+ }
1529
+ return appDocs.map(doc => App.from_dict(doc)).filter(app => app !== null);
1530
+ }
1531
+ }
1532
+
1533
+ // --- UserCommunityStats Class ---
1534
+
1535
+ export class UserCommunityStats {
1536
+ constructor(user_id, community_id, community_rep = 0, community_ref = 0, community_dip = 0) {
1537
+ this.user_id = user_id;
1538
+ this.community_id = community_id;
1539
+ this.community_rep = community_rep;
1540
+ this.community_ref = community_ref;
1541
+ this.community_dip = community_dip;
1542
+ this.db = new CacheFirestore();
1543
+ }
1544
+
1545
+ get doc_id() { return this.community_id; }
1546
+ get collection_path() { return FirestoreCollections.USER_COMMUNITY_STATS(this.user_id); }
1547
+
1548
+ to_dict() {
1549
+ const copy = { ...this };
1550
+ delete copy.db;
1551
+ if (copy.community_rep === undefined) copy.community_rep = 0;
1552
+ if (copy.community_ref === undefined) copy.community_ref = 0;
1553
+ if (copy.community_dip === undefined) copy.community_dip = 0;
1554
+ return copy;
1555
+ }
1556
+
1557
+ async to_firestore() {
1558
+ return await this.db.put_doc(this.collection_path, this.doc_id, this.to_dict());
1559
+ }
1560
+
1561
+ static async from_firestore(user_id, community_id) {
1562
+ const db = new CacheFirestore();
1563
+ const stats_path = FirestoreCollections.USER_COMMUNITY_STATS(user_id);
1564
+ const doc = await db.get_doc(stats_path, community_id);
1565
+ if (!doc) return null;
1566
+ return new UserCommunityStats(
1567
+ doc.user_id || user_id, doc.community_id || community_id,
1568
+ doc.community_rep || 0, doc.community_ref || 0, doc.community_dip || 0
1569
+ );
1570
+ }
1571
+
1572
+ async incrementRep(amount) {
1573
+ return await this.db.update_doc_field(this.collection_path, this.doc_id, 'community_rep', FieldValue.increment(amount));
1574
+ }
1575
+ async incrementRef(amount) {
1576
+ return await this.db.update_doc_field(this.collection_path, this.doc_id, 'community_ref', FieldValue.increment(amount));
1577
+ }
1578
+ async incrementDip(amount) {
1579
+ return await this.db.update_doc_field(this.collection_path, this.doc_id, 'community_dip', FieldValue.increment(amount));
1580
+ }
1581
+ async resetRef() {
1582
+ return await this.db.update_doc_field(this.collection_path, this.doc_id, 'community_ref', 0);
1583
+ }
1584
+ async resetDip() {
1585
+ return await this.db.update_doc_field(this.collection_path, this.doc_id, 'community_dip', 0);
1586
+ }
1587
+ }
1588
+
1589
+ // --- GuildSettings Class ---
1590
+
1591
+ export class GuildSettings {
1592
+ constructor(
1593
+ guild_id, owner_id, associated_community_id = null,
1594
+ accumulated_ref_commission = 0,
1595
+ accumulated_rep_commission = 0,
1596
+ accumulated_dip_commission = 0
1597
+ ) {
1598
+ this.guild_id = guild_id;
1599
+ this.owner_id = owner_id;
1600
+ this.associated_community_id = associated_community_id;
1601
+ this.accumulated_ref_commission = accumulated_ref_commission;
1602
+ this.accumulated_rep_commission = accumulated_rep_commission;
1603
+ this.accumulated_dip_commission = accumulated_dip_commission;
1604
+ this.db = new CacheFirestore();
1605
+ }
1606
+
1607
+ to_dict() {
1608
+ const copy = { ...this };
1609
+ delete copy.db;
1610
+ if (copy.accumulated_ref_commission === undefined) copy.accumulated_ref_commission = 0;
1611
+ if (copy.accumulated_rep_commission === undefined) copy.accumulated_rep_commission = 0;
1612
+ if (copy.accumulated_dip_commission === undefined) copy.accumulated_dip_commission = 0;
1613
+ return copy;
1614
+ }
1615
+
1616
+ async to_firestore() {
1617
+ return await this.db.put_doc(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, this.to_dict());
1618
+ }
1619
+
1620
+ static async from_firestore(guild_id) {
1621
+ const db = new CacheFirestore();
1622
+ const doc = await db.get_doc(FirestoreCollections.GUILD_SETTINGS(), guild_id);
1623
+ if (!doc) return null;
1624
+ return new GuildSettings(
1625
+ doc.guild_id || guild_id,
1626
+ doc.owner_id,
1627
+ doc.associated_community_id || null,
1628
+ doc.accumulated_ref_commission || 0,
1629
+ doc.accumulated_rep_commission || 0,
1630
+ doc.accumulated_dip_commission || 0
1631
+ );
1632
+ }
1633
+
1634
+ async incrementRefCommission(amount) {
1635
+ return await this.db.update_doc_field(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, 'accumulated_ref_commission', FieldValue.increment(amount));
1636
+ }
1637
+ async incrementRepCommission(amount) {
1638
+ return await this.db.update_doc_field(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, 'accumulated_rep_commission', FieldValue.increment(amount));
1639
+ }
1640
+ async incrementDipCommission(amount) {
1641
+ return await this.db.update_doc_field(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, 'accumulated_dip_commission', FieldValue.increment(amount));
1642
+ }
1643
+ async resetRefCommission() {
1644
+ return await this.db.update_doc_field(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, 'accumulated_ref_commission', 0);
1645
+ }
1646
+ async resetRepCommission() {
1647
+ return await this.db.update_doc_field(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, 'accumulated_rep_commission', 0);
1648
+ }
1649
+ async resetDipCommission() {
1650
+ return await this.db.update_doc_field(FirestoreCollections.GUILD_SETTINGS(), this.guild_id, 'accumulated_dip_commission', 0);
1651
+ }
1652
+ }
1653
+
1654
+ // --- Promotion Class ---
1655
+
1656
+ export class Promotion {
1657
+ constructor(
1658
+ custom_id, campaign_name, start_date, end_date, is_active,
1659
+ reward_type = 'REF', reward_data = {}, target_community_id = null
1660
+ ) {
1661
+ if (!custom_id || String(custom_id).trim() === "") {
1662
+ custom_id = crypto.randomUUID();
1663
+ }
1664
+ this.custom_id = custom_id;
1665
+ this.campaign_name = campaign_name;
1666
+ this.start_date = start_date;
1667
+ this.end_date = end_date;
1668
+ this.is_active = is_active;
1669
+ this.reward_type = reward_type;
1670
+ this.reward_data = reward_data;
1671
+ this.target_community_id = target_community_id;
1672
+ this.db = new CacheFirestore();
1673
+ }
1674
+
1675
+ to_dict() {
1676
+ const copy = { ...this };
1677
+ if (copy.start_date instanceof Date) copy.start_date = Timestamp.fromDate(copy.start_date);
1678
+ if (copy.end_date instanceof Date) copy.end_date = Timestamp.fromDate(copy.end_date);
1679
+ if (copy.reward_data === undefined) copy.reward_data = {};
1680
+ if (copy.reward_type === undefined) copy.reward_type = 'REF';
1681
+ delete copy.db;
1682
+ return copy;
1683
+ }
1684
+
1685
+ async to_firestore() {
1686
+ return await this.db.put_doc(FirestoreCollections.PROMOTIONS(), this.custom_id, this.to_dict());
1687
+ }
1688
+
1689
+ static async from_firestore(custom_id) {
1690
+ const db = new CacheFirestore();
1691
+ const doc = await db.get_doc(FirestoreCollections.PROMOTIONS(), custom_id);
1692
+ if (!doc) return null;
1693
+ const start_date_obj = doc.start_date instanceof Timestamp ? doc.start_date.toDate() : null;
1694
+ const end_date_obj = doc.end_date instanceof Timestamp ? doc.end_date.toDate() : null;
1695
+ return new Promotion(
1696
+ doc.custom_id || custom_id,
1697
+ doc.campaign_name, start_date_obj, end_date_obj,
1698
+ doc.is_active,
1699
+ doc.reward_type || 'REF',
1700
+ doc.reward_data || {},
1701
+ doc.target_community_id || null
1702
+ );
1703
+ }
1704
+
1705
+ static async findActivePromotion() {
1706
+ const db = new CacheFirestore();
1707
+ const now = new Date();
1708
+ const promotions = await db.get_docs(FirestoreCollections.PROMOTIONS(), null, [
1709
+ ['is_active', '==', true]
1710
+ ]);
1711
+ if (promotions && promotions.length > 0) {
1712
+ const validPromotions = promotions.filter(p_data => {
1713
+ const p = Promotion.from_dict(p_data);
1714
+ return (!p.start_date || p.start_date <= now) && (!p.end_date || p.end_date >= now);
1715
+ });
1716
+ if (validPromotions.length > 0) {
1717
+ return Promotion.from_dict(validPromotions[0]);
1718
+ }
1719
+ }
1720
+ return null;
1721
+ }
1722
+
1723
+ static from_dict(doc) {
1724
+ const start_date_obj = doc.start_date instanceof Timestamp ? doc.start_date.toDate() : null;
1725
+ const end_date_obj = doc.end_date instanceof Timestamp ? doc.end_date.toDate() : null;
1726
+ return new Promotion(
1727
+ doc.custom_id, doc.campaign_name, start_date_obj, end_date_obj, doc.is_active,
1728
+ doc.reward_type || 'REF', doc.reward_data || {}, doc.target_community_id || null
1729
+ );
1730
+ }
1731
+ }
1732
+
1733
+ // --- NFT Class ---
1734
+
1735
+ export class NFT {
1736
+ constructor(
1737
+ nft_id, owner_id, community_id, token_symbol, batch_number,
1738
+ ad_credits = 0, is_app_creator = false,
1739
+ created_at = new Date(), updated_at = new Date()
1740
+ ) {
1741
+ this.nft_id = nft_id;
1742
+ this.owner_id = owner_id;
1743
+ this.community_id = community_id;
1744
+ this.token_symbol = token_symbol;
1745
+ this.batch_number = batch_number;
1746
+ this.ad_credits = ad_credits;
1747
+ this.is_app_creator = is_app_creator;
1748
+ this.created_at = created_at instanceof Date ? created_at : new Date(created_at);
1749
+ this.updated_at = updated_at instanceof Date ? updated_at : new Date(updated_at);
1750
+ this.db = new CacheFirestore();
1751
+ }
1752
+
1753
+ get collection_path() { return 'NFTs'; }
1754
+ get doc_id() { return this.nft_id; }
1755
+
1756
+ to_dict() {
1757
+ const copy = { ...this };
1758
+ delete copy.db;
1759
+ if (copy.created_at instanceof Date) copy.created_at = Timestamp.fromDate(copy.created_at);
1760
+ if (copy.updated_at instanceof Date) copy.updated_at = Timestamp.fromDate(copy.updated_at);
1761
+ return copy;
1762
+ }
1763
+
1764
+ async to_firestore() {
1765
+ this.updated_at = new Date();
1766
+ return await this.db.put_doc(this.collection_path, this.doc_id, this.to_dict());
1767
+ }
1768
+
1769
+ static async from_firestore(nft_id) {
1770
+ const db = new CacheFirestore();
1771
+ const doc = await db.get_doc('NFTs', nft_id);
1772
+ if (!doc) return null;
1773
+ return NFT.from_dict(doc);
1774
+ }
1775
+
1776
+ static from_dict(data) {
1777
+ if (!data) return null;
1778
+ const created = data.created_at instanceof Timestamp ? data.created_at.toDate() : new Date(data.created_at);
1779
+ const updated = data.updated_at instanceof Timestamp ? data.updated_at.toDate() : new Date(data.updated_at);
1780
+ return new NFT(
1781
+ data.nft_id, data.owner_id, data.community_id, data.token_symbol,
1782
+ data.batch_number, data.ad_credits, data.is_app_creator,
1783
+ created, updated
1784
+ );
1785
+ }
1786
+ }
1787
+
1788
+ // --- AdCampaign Class ---
1789
+
1790
+ export class AdCampaign {
1791
+ constructor(
1792
+ campaign_id, owner_id, nft_id, app_id, community_id,
1793
+ content, keywords = [], locations = [],
1794
+ status = 'ACTIVE', stats = { impressions: 0, clicks: 0 },
1795
+ created_at = new Date(), updated_at = new Date()
1796
+ ) {
1797
+ this.campaign_id = campaign_id;
1798
+ this.owner_id = owner_id;
1799
+ this.nft_id = nft_id;
1800
+ this.app_id = app_id;
1801
+ this.community_id = community_id;
1802
+ this.content = content;
1803
+ this.keywords = keywords || [];
1804
+ this.locations = locations || [];
1805
+ this.status = status;
1806
+ this.stats = stats || { impressions: 0, clicks: 0 };
1807
+ this.created_at = created_at instanceof Date ? created_at : new Date(created_at);
1808
+ this.updated_at = updated_at instanceof Date ? updated_at : new Date(updated_at);
1809
+ this.db = new CacheFirestore();
1810
+ }
1811
+
1812
+ get collection_path() { return 'AdCampaigns'; }
1813
+ get doc_id() { return this.campaign_id; }
1814
+
1815
+ to_dict() {
1816
+ const copy = { ...this };
1817
+ delete copy.db;
1818
+ if (copy.created_at instanceof Date) copy.created_at = Timestamp.fromDate(copy.created_at);
1819
+ if (copy.updated_at instanceof Date) copy.updated_at = Timestamp.fromDate(copy.updated_at);
1820
+ return copy;
1821
+ }
1822
+
1823
+ async to_firestore() {
1824
+ this.updated_at = new Date();
1825
+ return await this.db.put_doc(this.collection_path, this.doc_id, this.to_dict());
1826
+ }
1827
+
1828
+ static async from_firestore(campaign_id) {
1829
+ const db = new CacheFirestore();
1830
+ const doc = await db.get_doc('AdCampaigns', campaign_id);
1831
+ if (!doc) return null;
1832
+ return AdCampaign.from_dict(doc);
1833
+ }
1834
+
1835
+ static from_dict(data) {
1836
+ if (!data) return null;
1837
+ const created = data.created_at instanceof Timestamp ? data.created_at.toDate() : new Date(data.created_at);
1838
+ const updated = data.updated_at instanceof Timestamp ? data.updated_at.toDate() : new Date(data.updated_at);
1839
+ return new AdCampaign(
1840
+ data.campaign_id, data.owner_id, data.nft_id, data.app_id, data.community_id,
1841
+ data.content, data.keywords, data.locations,
1842
+ data.status, data.stats,
1843
+ created, updated
1844
+ );
1845
+ }
1846
+
1847
+ async track_impression() {
1848
+ this.stats.impressions = (this.stats.impressions || 0) + 1;
1849
+ await this.to_firestore();
1850
+ }
1851
+
1852
+ async track_click() {
1853
+ this.stats.clicks = (this.stats.clicks || 0) + 1;
1854
+ await this.to_firestore();
1855
+ }
1856
+ }
1857
+
1858
+ // --- SharedAsset Class ---
1859
+
1860
+ export class SharedAsset {
1861
+ constructor(asset_id, owner_id, community_id, app_id, asset_type, asset_name, source_drive_folder_id, creation_timestamp = new Date(), kb_token_count = 0, status = 'PENDING') {
1862
+ this.asset_id = asset_id;
1863
+ this.owner_id = owner_id;
1864
+ this.community_id = community_id;
1865
+ this.app_id = app_id;
1866
+ this.asset_type = asset_type;
1867
+ this.asset_name = asset_name;
1868
+ this.source_drive_folder_id = source_drive_folder_id;
1869
+ this.creation_timestamp = creation_timestamp instanceof Date ? creation_timestamp : new Date(creation_timestamp);
1870
+ this.kb_token_count = kb_token_count;
1871
+ this.status = status;
1872
+ this.db = new CacheFirestore();
1873
+ }
1874
+
1875
+ get doc_id() { return clean_name_for_id(this.asset_id); }
1876
+ get collection_path() { return FirestoreCollections.SHARED_ASSETS(this.community_id, this.app_id); }
1877
+
1878
+ to_dict() {
1879
+ const copy = { ...this };
1880
+ if (copy.creation_timestamp instanceof Date) copy.creation_timestamp = Timestamp.fromDate(copy.creation_timestamp);
1881
+ delete copy.db;
1882
+ return copy;
1883
+ }
1884
+
1885
+ async to_firestore() {
1886
+ return await this.db.put_doc(this.collection_path, this.doc_id, this.to_dict());
1887
+ }
1888
+
1889
+ static async from_firestore(community_id, app_id, asset_doc_id) {
1890
+ const db = new CacheFirestore();
1891
+ const asset_path = FirestoreCollections.SHARED_ASSETS(community_id, app_id);
1892
+ const doc = await db.get_doc(asset_path, asset_doc_id);
1893
+ if (!doc) return null;
1894
+ const creation_ts = doc.creation_timestamp instanceof Timestamp ? doc.creation_timestamp.toDate() : new Date(doc.creation_timestamp);
1895
+ return new SharedAsset(
1896
+ doc.asset_id, doc.owner_id, doc.community_id || community_id, doc.app_id || app_id,
1897
+ doc.asset_type, doc.asset_name, doc.source_drive_folder_id,
1898
+ creation_ts, doc.kb_token_count || 0, doc.status || 'PENDING'
1899
+ );
1900
+ }
1901
+ }