@sonatel-os/strapi-plugin-split 0.0.0-stage → 0.2.0

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,2447 @@
1
+ "use strict";
2
+ const node_crypto = require("node:crypto");
3
+ const PLUGIN_ID = "split";
4
+ const PLUGIN_DISPLAY_NAME = "Split";
5
+ const LOG_PREFIX = "[split]";
6
+ const UID = Object.freeze({
7
+ PERSON: "plugin::split.person",
8
+ GROUP: "plugin::split.group",
9
+ MEMBER: "plugin::split.member",
10
+ EXPENSE: "plugin::split.expense",
11
+ SHARE: "plugin::split.share",
12
+ SETTLEMENT: "plugin::split.settlement",
13
+ EVENT: "plugin::split.event"
14
+ });
15
+ const RBAC = Object.freeze({
16
+ ACCESS: "access",
17
+ DASHBOARD_READ: "dashboard.read",
18
+ GROUPS_READ: "groups.read",
19
+ GROUPS_WRITE: "groups.write",
20
+ PEOPLE_READ: "people.read",
21
+ PEOPLE_PHONE: "people.phone",
22
+ PEOPLE_WRITE: "people.write",
23
+ SETTLEMENTS_READ: "settlements.read",
24
+ AUDIT_READ: "audit.read",
25
+ SETTINGS_READ: "settings.read"
26
+ });
27
+ const SPLIT_MODE = Object.freeze({ EQUAL: "equal", WEIGHTED: "weighted", FREE: "free" });
28
+ const ROLE = Object.freeze({ OWNER: "owner", MEMBER: "member" });
29
+ const SETTLEMENT_STATUS = Object.freeze({
30
+ /** Declared; the receiver has not confirmed yet. Does not move balances. */
31
+ PENDING: "pending",
32
+ /** Counts in the balances. */
33
+ CONFIRMED: "confirmed",
34
+ /** The receiver said no. */
35
+ REJECTED: "rejected",
36
+ /** The payer withdrew it. */
37
+ CANCELLED: "cancelled"
38
+ });
39
+ const DEFAULT_METHODS = Object.freeze({
40
+ mobile_money: { instant: true },
41
+ cash: { instant: false },
42
+ other: { instant: false }
43
+ });
44
+ const EVENT = Object.freeze({
45
+ GROUP_CREATED: "group.created",
46
+ GROUP_RENAMED: "group.renamed",
47
+ GROUP_ARCHIVED: "group.archived",
48
+ MEMBER_ADDED: "member.added",
49
+ MEMBER_JOINED: "member.joined",
50
+ MEMBER_LEFT: "member.left",
51
+ MEMBER_REMOVED: "member.removed",
52
+ EXPENSE_CREATED: "expense.created",
53
+ EXPENSE_UPDATED: "expense.updated",
54
+ EXPENSE_DELETED: "expense.deleted",
55
+ SETTLEMENT_CREATED: "settlement.created",
56
+ SETTLEMENT_CONFIRMED: "settlement.confirmed",
57
+ SETTLEMENT_REJECTED: "settlement.rejected",
58
+ SETTLEMENT_CANCELLED: "settlement.cancelled"
59
+ });
60
+ const DEFAULT_LIMITS = Object.freeze({
61
+ maxGroupsPerPerson: 50,
62
+ maxMembersPerGroup: 50,
63
+ /** Largest single expense or settlement, in the currency's smallest unit. */
64
+ maxAmount: 5e7
65
+ });
66
+ const DEFAULT_INVITE_PREFIX = "SPL";
67
+ const DEFAULT_COUNTRY_CODE = "";
68
+ const CODE_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
69
+ const INVITE_CODE_LENGTH = 6;
70
+ const MAX_CODE_ATTEMPTS = 10;
71
+ const MAX_WEIGHT = 99;
72
+ const NAME_MAX = 80;
73
+ const LABEL_MAX = 120;
74
+ const NOTE_MAX = 500;
75
+ const REF_MAX = 190;
76
+ const DEFAULT_PAGE_SIZE = 20;
77
+ const MAX_PAGE_SIZE = 100;
78
+ const GROUP_RECENT_EXPENSES = 20;
79
+ const DASHBOARD_DAYS = 7;
80
+ const DAY_MS = 24 * 60 * 60 * 1e3;
81
+ const ERROR_CODES = Object.freeze({
82
+ VALIDATION: "VALIDATION",
83
+ PERSON_REQUIRED: "PERSON_REQUIRED",
84
+ PERSON_NOT_FOUND: "PERSON_NOT_FOUND",
85
+ PERSON_INACTIVE: "PERSON_INACTIVE",
86
+ GROUP_NOT_FOUND: "GROUP_NOT_FOUND",
87
+ GROUP_ARCHIVED: "GROUP_ARCHIVED",
88
+ GROUP_LIMIT: "GROUP_LIMIT",
89
+ NOT_A_MEMBER: "NOT_A_MEMBER",
90
+ NOT_ALLOWED: "NOT_ALLOWED",
91
+ INVITE_INVALID: "INVITE_INVALID",
92
+ MEMBER_NOT_FOUND: "MEMBER_NOT_FOUND",
93
+ MEMBER_EXISTS: "MEMBER_EXISTS",
94
+ MEMBER_LIMIT: "MEMBER_LIMIT",
95
+ MEMBER_NOT_SETTLED: "MEMBER_NOT_SETTLED",
96
+ EXPENSE_NOT_FOUND: "EXPENSE_NOT_FOUND",
97
+ SPLIT_INVALID: "SPLIT_INVALID",
98
+ SETTLEMENT_NOT_FOUND: "SETTLEMENT_NOT_FOUND",
99
+ SETTLEMENT_EXCEEDS_DEBT: "SETTLEMENT_EXCEEDS_DEBT",
100
+ SETTLEMENT_NOT_PENDING: "SETTLEMENT_NOT_PENDING",
101
+ METHOD_UNKNOWN: "METHOD_UNKNOWN"
102
+ });
103
+ const ACTIONS = [
104
+ { section: "plugins", uid: RBAC.ACCESS, displayName: `Access the ${PLUGIN_DISPLAY_NAME} module` },
105
+ { section: "plugins", uid: RBAC.DASHBOARD_READ, displayName: "Read the dashboard" },
106
+ { section: "plugins", uid: RBAC.GROUPS_READ, displayName: "Read groups, expenses and balances" },
107
+ { section: "plugins", uid: RBAC.GROUPS_WRITE, displayName: "Archive groups" },
108
+ { section: "plugins", uid: RBAC.PEOPLE_READ, displayName: "Read people (phone numbers masked)" },
109
+ { section: "plugins", uid: RBAC.PEOPLE_PHONE, displayName: "Reveal a full phone number" },
110
+ { section: "plugins", uid: RBAC.PEOPLE_WRITE, displayName: "Deactivate and reactivate people" },
111
+ { section: "plugins", uid: RBAC.SETTLEMENTS_READ, displayName: "Read settlements" },
112
+ { section: "plugins", uid: RBAC.AUDIT_READ, displayName: "Read the audit trail" },
113
+ {
114
+ section: "settings",
115
+ category: PLUGIN_DISPLAY_NAME,
116
+ uid: RBAC.SETTINGS_READ,
117
+ displayName: "Read settings"
118
+ }
119
+ ].map((a) => ({ ...a, pluginName: PLUGIN_ID }));
120
+ const UNIQUE_COLUMNS = [
121
+ [UID.PERSON, "external_id"],
122
+ [UID.GROUP, "invite_code"],
123
+ [UID.EXPENSE, "client_ref"],
124
+ [UID.SETTLEMENT, "client_ref"]
125
+ ];
126
+ const INDEX_CHECK_DELAY_MS = 5e3;
127
+ const hasIndex = async (knex, table, name) => {
128
+ const client = String(knex.client?.config?.client ?? "");
129
+ if (/mysql/.test(client)) {
130
+ const rows2 = await knex.raw("SHOW INDEX FROM ?? WHERE Key_name = ?", [table, name]);
131
+ return (rows2?.[0] ?? []).length > 0;
132
+ }
133
+ if (/pg|postgres/.test(client)) {
134
+ const rows2 = await knex.raw("SELECT 1 FROM pg_indexes WHERE tablename = ? AND indexname = ?", [
135
+ table,
136
+ name
137
+ ]);
138
+ return (rows2?.rows ?? []).length > 0;
139
+ }
140
+ const rows = await knex.raw("PRAGMA index_list(??)", [table]);
141
+ return (rows ?? []).some((r) => r.name === name);
142
+ };
143
+ const ensureUniqueIndexes = async (strapi) => {
144
+ const knex = strapi.db.connection;
145
+ for (const [uid, column] of UNIQUE_COLUMNS) {
146
+ const table = strapi.db.metadata.get(uid)?.tableName;
147
+ if (!table) continue;
148
+ const name = `${table}_${column}_split_uq`;
149
+ try {
150
+ if (await hasIndex(knex, table, name)) continue;
151
+ await knex.schema.alterTable(table, (t) => t.unique([column], { indexName: name }));
152
+ strapi.log.info(`${LOG_PREFIX} unique index ${name} created`);
153
+ } catch (err) {
154
+ if (!/exist|duplicate/i.test(err.message))
155
+ strapi.log.warn(`${LOG_PREFIX} unique index ${name}: ${err.message}`);
156
+ }
157
+ }
158
+ };
159
+ const bootstrap = async ({ strapi }) => {
160
+ await strapi.service("admin::permission").actionProvider.registerMany(ACTIONS);
161
+ const timer = setTimeout(
162
+ () => ensureUniqueIndexes(strapi).catch(
163
+ (err) => strapi.log.warn(`${LOG_PREFIX} unique indexes: ${err.message}`)
164
+ ),
165
+ INDEX_CHECK_DELAY_MS
166
+ );
167
+ timer.unref();
168
+ strapi.log.info(
169
+ `${LOG_PREFIX} ready — ${ACTIONS.length} RBAC actions, content API at /api/${PLUGIN_ID}`
170
+ );
171
+ };
172
+ const register = ({ strapi }) => {
173
+ strapi.log.info(`${LOG_PREFIX} registered`);
174
+ };
175
+ const fail = (message) => {
176
+ throw new Error(`${LOG_PREFIX} ${message}`);
177
+ };
178
+ const HEADER_NAME = /^[a-z0-9-]{2,64}$/i;
179
+ const METHOD_NAME = /^[a-z0-9_]{2,40}$/;
180
+ const config = {
181
+ default: {
182
+ inviteCodePrefix: DEFAULT_INVITE_PREFIX,
183
+ countryCode: DEFAULT_COUNTRY_CODE,
184
+ people: { idHeader: "x-person-id", nameHeader: "x-person-name", autoProvision: true },
185
+ methods: DEFAULT_METHODS,
186
+ limits: DEFAULT_LIMITS
187
+ },
188
+ /**
189
+ * @param {Object} config - resolved plugin config
190
+ */
191
+ validator(config2) {
192
+ if (config2.inviteCodePrefix && !/^[A-Z0-9]{2,6}$/.test(config2.inviteCodePrefix)) {
193
+ fail("inviteCodePrefix must be 2 to 6 uppercase letters or digits.");
194
+ }
195
+ if (config2.countryCode && !/^\d{1,4}$/.test(String(config2.countryCode))) {
196
+ fail("countryCode must be 1 to 4 digits.");
197
+ }
198
+ const people = config2.people ?? {};
199
+ for (const key of ["idHeader", "nameHeader"]) {
200
+ if (people[key] != null && !HEADER_NAME.test(String(people[key]))) {
201
+ fail(`people.${key} must be a valid header name.`);
202
+ }
203
+ }
204
+ const methods = Object.keys(config2.methods ?? {});
205
+ if (config2.methods && methods.length === 0) fail("methods must name at least one method.");
206
+ for (const name of methods) {
207
+ if (!METHOD_NAME.test(name)) fail(`methods.${name}: lowercase letters, digits and _ only.`);
208
+ }
209
+ for (const [key, value] of Object.entries(config2.limits ?? {})) {
210
+ if (!Number.isInteger(value) || value <= 0) fail(`limits.${key} must be a positive integer.`);
211
+ }
212
+ }
213
+ };
214
+ const kind$6 = "collectionType";
215
+ const collectionName$6 = "split_people";
216
+ const info$6 = {
217
+ singularName: "person",
218
+ pluralName: "people",
219
+ displayName: "Split Person",
220
+ description: "Someone using the ledger, identified by the external id the host sends in the person header."
221
+ };
222
+ const options$6 = {
223
+ draftAndPublish: false
224
+ };
225
+ const pluginOptions$6 = {
226
+ "content-manager": {
227
+ visible: false
228
+ },
229
+ "content-type-builder": {
230
+ visible: false
231
+ }
232
+ };
233
+ const attributes$6 = {
234
+ externalId: {
235
+ type: "string",
236
+ maxLength: 190,
237
+ required: true,
238
+ unique: true
239
+ },
240
+ phone: {
241
+ type: "string",
242
+ maxLength: 20,
243
+ "private": true
244
+ },
245
+ displayName: {
246
+ type: "string",
247
+ maxLength: 100
248
+ },
249
+ isActive: {
250
+ type: "boolean",
251
+ "default": true,
252
+ required: true
253
+ },
254
+ lastActiveAt: {
255
+ type: "datetime"
256
+ },
257
+ memberships: {
258
+ type: "relation",
259
+ relation: "oneToMany",
260
+ target: "plugin::split.member",
261
+ mappedBy: "person"
262
+ }
263
+ };
264
+ const schema$6 = {
265
+ kind: kind$6,
266
+ collectionName: collectionName$6,
267
+ info: info$6,
268
+ options: options$6,
269
+ pluginOptions: pluginOptions$6,
270
+ attributes: attributes$6
271
+ };
272
+ const person$2 = { schema: schema$6 };
273
+ const kind$5 = "collectionType";
274
+ const collectionName$5 = "split_groups";
275
+ const info$5 = {
276
+ singularName: "group",
277
+ pluralName: "groups",
278
+ displayName: "Split Group",
279
+ description: "People sharing expenses."
280
+ };
281
+ const options$5 = {
282
+ draftAndPublish: false
283
+ };
284
+ const pluginOptions$5 = {
285
+ "content-manager": {
286
+ visible: false
287
+ },
288
+ "content-type-builder": {
289
+ visible: false
290
+ }
291
+ };
292
+ const attributes$5 = {
293
+ name: {
294
+ type: "string",
295
+ maxLength: 80,
296
+ required: true
297
+ },
298
+ inviteCode: {
299
+ type: "string",
300
+ maxLength: 24,
301
+ required: true,
302
+ unique: true
303
+ },
304
+ founder: {
305
+ type: "relation",
306
+ relation: "manyToOne",
307
+ target: "plugin::split.person"
308
+ },
309
+ archivedAt: {
310
+ type: "datetime"
311
+ },
312
+ lastActivityAt: {
313
+ type: "datetime"
314
+ },
315
+ members: {
316
+ type: "relation",
317
+ relation: "oneToMany",
318
+ target: "plugin::split.member",
319
+ mappedBy: "group"
320
+ }
321
+ };
322
+ const schema$5 = {
323
+ kind: kind$5,
324
+ collectionName: collectionName$5,
325
+ info: info$5,
326
+ options: options$5,
327
+ pluginOptions: pluginOptions$5,
328
+ attributes: attributes$5
329
+ };
330
+ const group$1 = { schema: schema$5 };
331
+ const kind$4 = "collectionType";
332
+ const collectionName$4 = "split_members";
333
+ const info$4 = {
334
+ singularName: "member",
335
+ pluralName: "members",
336
+ displayName: "Split Member",
337
+ description: "A seat in a group: a registered person, or someone a member added by name (and maybe phone) who has not opened the app yet."
338
+ };
339
+ const options$4 = {
340
+ draftAndPublish: false
341
+ };
342
+ const pluginOptions$4 = {
343
+ "content-manager": {
344
+ visible: false
345
+ },
346
+ "content-type-builder": {
347
+ visible: false
348
+ }
349
+ };
350
+ const attributes$4 = {
351
+ group: {
352
+ type: "relation",
353
+ relation: "manyToOne",
354
+ target: "plugin::split.group",
355
+ inversedBy: "members"
356
+ },
357
+ person: {
358
+ type: "relation",
359
+ relation: "manyToOne",
360
+ target: "plugin::split.person",
361
+ inversedBy: "memberships"
362
+ },
363
+ displayName: {
364
+ type: "string",
365
+ maxLength: 100,
366
+ required: true
367
+ },
368
+ phone: {
369
+ type: "string",
370
+ maxLength: 20,
371
+ "private": true
372
+ },
373
+ role: {
374
+ type: "enumeration",
375
+ "enum": [
376
+ "owner",
377
+ "member"
378
+ ],
379
+ "default": "member",
380
+ required: true
381
+ },
382
+ joinedAt: {
383
+ type: "datetime"
384
+ },
385
+ leftAt: {
386
+ type: "datetime"
387
+ }
388
+ };
389
+ const schema$4 = {
390
+ kind: kind$4,
391
+ collectionName: collectionName$4,
392
+ info: info$4,
393
+ options: options$4,
394
+ pluginOptions: pluginOptions$4,
395
+ attributes: attributes$4
396
+ };
397
+ const member$1 = { schema: schema$4 };
398
+ const kind$3 = "collectionType";
399
+ const collectionName$3 = "split_expenses";
400
+ const info$3 = {
401
+ singularName: "expense",
402
+ pluralName: "expenses",
403
+ displayName: "Split Expense",
404
+ description: "Something one member paid for the others."
405
+ };
406
+ const options$3 = {
407
+ draftAndPublish: false
408
+ };
409
+ const pluginOptions$3 = {
410
+ "content-manager": {
411
+ visible: false
412
+ },
413
+ "content-type-builder": {
414
+ visible: false
415
+ }
416
+ };
417
+ const attributes$3 = {
418
+ group: {
419
+ type: "relation",
420
+ relation: "manyToOne",
421
+ target: "plugin::split.group"
422
+ },
423
+ paidBy: {
424
+ type: "relation",
425
+ relation: "manyToOne",
426
+ target: "plugin::split.member"
427
+ },
428
+ addedBy: {
429
+ type: "relation",
430
+ relation: "manyToOne",
431
+ target: "plugin::split.member"
432
+ },
433
+ label: {
434
+ type: "string",
435
+ maxLength: 120,
436
+ required: true
437
+ },
438
+ category: {
439
+ type: "string",
440
+ maxLength: 40
441
+ },
442
+ amount: {
443
+ type: "integer",
444
+ required: true,
445
+ min: 1
446
+ },
447
+ mode: {
448
+ type: "enumeration",
449
+ "enum": [
450
+ "equal",
451
+ "weighted",
452
+ "free"
453
+ ],
454
+ "default": "equal",
455
+ required: true
456
+ },
457
+ spentAt: {
458
+ type: "datetime",
459
+ required: true
460
+ },
461
+ clientRef: {
462
+ type: "string",
463
+ maxLength: 190,
464
+ unique: true
465
+ },
466
+ deletedAt: {
467
+ type: "datetime"
468
+ },
469
+ shares: {
470
+ type: "relation",
471
+ relation: "oneToMany",
472
+ target: "plugin::split.share",
473
+ mappedBy: "expense"
474
+ }
475
+ };
476
+ const schema$3 = {
477
+ kind: kind$3,
478
+ collectionName: collectionName$3,
479
+ info: info$3,
480
+ options: options$3,
481
+ pluginOptions: pluginOptions$3,
482
+ attributes: attributes$3
483
+ };
484
+ const expense$1 = { schema: schema$3 };
485
+ const kind$2 = "collectionType";
486
+ const collectionName$2 = "split_shares";
487
+ const info$2 = {
488
+ singularName: "share",
489
+ pluralName: "shares",
490
+ displayName: "Split Share",
491
+ description: "What one member owes of one expense."
492
+ };
493
+ const options$2 = {
494
+ draftAndPublish: false
495
+ };
496
+ const pluginOptions$2 = {
497
+ "content-manager": {
498
+ visible: false
499
+ },
500
+ "content-type-builder": {
501
+ visible: false
502
+ }
503
+ };
504
+ const attributes$2 = {
505
+ expense: {
506
+ type: "relation",
507
+ relation: "manyToOne",
508
+ target: "plugin::split.expense",
509
+ inversedBy: "shares"
510
+ },
511
+ member: {
512
+ type: "relation",
513
+ relation: "manyToOne",
514
+ target: "plugin::split.member"
515
+ },
516
+ amount: {
517
+ type: "integer",
518
+ required: true,
519
+ min: 0
520
+ },
521
+ weight: {
522
+ type: "integer",
523
+ "default": 0
524
+ }
525
+ };
526
+ const schema$2 = {
527
+ kind: kind$2,
528
+ collectionName: collectionName$2,
529
+ info: info$2,
530
+ options: options$2,
531
+ pluginOptions: pluginOptions$2,
532
+ attributes: attributes$2
533
+ };
534
+ const share = { schema: schema$2 };
535
+ const kind$1 = "collectionType";
536
+ const collectionName$1 = "split_settlements";
537
+ const info$1 = {
538
+ singularName: "settlement",
539
+ pluralName: "settlements",
540
+ displayName: "Split Settlement",
541
+ description: "A payment from one member to another that reduces what is owed."
542
+ };
543
+ const options$1 = {
544
+ draftAndPublish: false
545
+ };
546
+ const pluginOptions$1 = {
547
+ "content-manager": {
548
+ visible: false
549
+ },
550
+ "content-type-builder": {
551
+ visible: false
552
+ }
553
+ };
554
+ const attributes$1 = {
555
+ group: {
556
+ type: "relation",
557
+ relation: "manyToOne",
558
+ target: "plugin::split.group"
559
+ },
560
+ from: {
561
+ type: "relation",
562
+ relation: "manyToOne",
563
+ target: "plugin::split.member"
564
+ },
565
+ to: {
566
+ type: "relation",
567
+ relation: "manyToOne",
568
+ target: "plugin::split.member"
569
+ },
570
+ amount: {
571
+ type: "integer",
572
+ required: true,
573
+ min: 1
574
+ },
575
+ method: {
576
+ type: "string",
577
+ maxLength: 40,
578
+ required: true
579
+ },
580
+ status: {
581
+ type: "enumeration",
582
+ "enum": [
583
+ "pending",
584
+ "confirmed",
585
+ "rejected",
586
+ "cancelled"
587
+ ],
588
+ "default": "pending",
589
+ required: true
590
+ },
591
+ reference: {
592
+ type: "string",
593
+ maxLength: 190
594
+ },
595
+ note: {
596
+ type: "string",
597
+ maxLength: 500
598
+ },
599
+ clientRef: {
600
+ type: "string",
601
+ maxLength: 190,
602
+ unique: true
603
+ },
604
+ declaredAt: {
605
+ type: "datetime",
606
+ required: true
607
+ },
608
+ resolvedAt: {
609
+ type: "datetime"
610
+ },
611
+ resolvedBy: {
612
+ type: "relation",
613
+ relation: "manyToOne",
614
+ target: "plugin::split.person"
615
+ }
616
+ };
617
+ const schema$1 = {
618
+ kind: kind$1,
619
+ collectionName: collectionName$1,
620
+ info: info$1,
621
+ options: options$1,
622
+ pluginOptions: pluginOptions$1,
623
+ attributes: attributes$1
624
+ };
625
+ const settlement$1 = { schema: schema$1 };
626
+ const kind = "collectionType";
627
+ const collectionName = "split_events";
628
+ const info = {
629
+ singularName: "event",
630
+ pluralName: "events",
631
+ displayName: "Split Event",
632
+ description: "Audit trail: who did what in which group."
633
+ };
634
+ const options = {
635
+ draftAndPublish: false
636
+ };
637
+ const pluginOptions = {
638
+ "content-manager": {
639
+ visible: false
640
+ },
641
+ "content-type-builder": {
642
+ visible: false
643
+ }
644
+ };
645
+ const attributes = {
646
+ group: {
647
+ type: "relation",
648
+ relation: "manyToOne",
649
+ target: "plugin::split.group"
650
+ },
651
+ actor: {
652
+ type: "relation",
653
+ relation: "manyToOne",
654
+ target: "plugin::split.person"
655
+ },
656
+ action: {
657
+ type: "string",
658
+ maxLength: 40,
659
+ required: true
660
+ },
661
+ targetId: {
662
+ type: "string",
663
+ maxLength: 64
664
+ },
665
+ data: {
666
+ type: "json"
667
+ },
668
+ at: {
669
+ type: "datetime",
670
+ required: true
671
+ }
672
+ };
673
+ const schema = {
674
+ kind,
675
+ collectionName,
676
+ info,
677
+ options,
678
+ pluginOptions,
679
+ attributes
680
+ };
681
+ const event = { schema };
682
+ const contentTypes = { person: person$2, group: group$1, member: member$1, expense: expense$1, share, settlement: settlement$1, event };
683
+ class SplitError extends Error {
684
+ /**
685
+ * @param {number} status HTTP status
686
+ * @param {string} code stable machine code (see constants.ERROR_CODES)
687
+ * @param {string} message human message (French is fine; the client branches on `code`)
688
+ * @param {Object} [details]
689
+ */
690
+ constructor(status, code, message, details) {
691
+ super(message);
692
+ this.name = "SplitError";
693
+ this.status = status;
694
+ this.code = code;
695
+ this.details = details;
696
+ }
697
+ }
698
+ const badRequest = (code, message, details) => new SplitError(400, code, message, details);
699
+ const forbidden = (code, message, details) => new SplitError(403, code, message, details);
700
+ const notFound = (code, message, details) => new SplitError(404, code, message, details);
701
+ const conflict = (code, message, details) => new SplitError(409, code, message, details);
702
+ const unprocessable = (code, message, details) => new SplitError(422, code, message, details);
703
+ const sendError = (ctx, err, strapi) => {
704
+ if (err instanceof SplitError) {
705
+ ctx.status = err.status;
706
+ ctx.body = {
707
+ error: { status: err.status, code: err.code, message: err.message, details: err.details }
708
+ };
709
+ return;
710
+ }
711
+ strapi?.log?.error(`[split] unexpected: ${err?.stack || err}`);
712
+ ctx.status = 500;
713
+ ctx.body = {
714
+ error: { status: 500, code: "INTERNAL", message: "Une erreur interne est survenue." }
715
+ };
716
+ };
717
+ const parsePagination = (query = {}) => {
718
+ const page = Math.max(1, parseInt(query.page, 10) || 1);
719
+ const pageSize = Math.min(
720
+ MAX_PAGE_SIZE,
721
+ Math.max(1, parseInt(query.pageSize ?? query.limit, 10) || DEFAULT_PAGE_SIZE)
722
+ );
723
+ return { page, pageSize, offset: (page - 1) * pageSize, limit: pageSize };
724
+ };
725
+ const paged = (items, total, { page, pageSize }) => ({
726
+ data: items,
727
+ meta: {
728
+ pagination: { page, pageSize, total, pageCount: Math.max(1, Math.ceil(total / pageSize)) }
729
+ }
730
+ });
731
+ const handle = (strapi, fn) => async (ctx) => {
732
+ try {
733
+ await fn(ctx);
734
+ } catch (err) {
735
+ sendError(ctx, err, strapi);
736
+ }
737
+ };
738
+ const body = (ctx) => ctx.request.body && typeof ctx.request.body === "object" ? ctx.request.body.data ?? ctx.request.body : {};
739
+ const ok = (ctx, data, meta) => {
740
+ ctx.body = meta ? { data, meta } : { data };
741
+ };
742
+ const written = (ctx, data, replayed) => {
743
+ ctx.status = replayed ? 200 : 201;
744
+ ctx.body = { data, meta: { replayed } };
745
+ };
746
+ const noContent = (ctx) => {
747
+ ctx.status = 204;
748
+ };
749
+ const app = ({ strapi }) => {
750
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
751
+ const viewer = (ctx) => ctx.state.splitPerson;
752
+ const seat = (ctx, options2) => svc("group").seat(viewer(ctx), ctx.params.group, options2);
753
+ const writable = (ctx) => seat(ctx, { writable: true });
754
+ return {
755
+ // ── Person ───────────────────────────────────────────────────────────
756
+ me: handle(strapi, async (ctx) => {
757
+ ok(ctx, svc("format").person(viewer(ctx), Boolean(ctx.state.splitPersonIsNew)));
758
+ }),
759
+ overview: handle(strapi, async (ctx) => ok(ctx, await svc("view").overview(viewer(ctx)))),
760
+ activity: handle(strapi, async (ctx) => {
761
+ const page = parsePagination(ctx.query);
762
+ const { items, total } = await svc("view").activity(viewer(ctx), page);
763
+ ctx.body = paged(items, total, page);
764
+ }),
765
+ // ── Groups ───────────────────────────────────────────────────────────
766
+ createGroup: handle(strapi, async (ctx) => {
767
+ const group2 = await svc("group").create(viewer(ctx), body(ctx));
768
+ const mine = await svc("group").seat(viewer(ctx), group2.documentId);
769
+ written(ctx, await svc("view").group(mine, viewer(ctx)), false);
770
+ }),
771
+ joinGroup: handle(strapi, async (ctx) => {
772
+ const group2 = await svc("group").join(viewer(ctx), body(ctx).code);
773
+ const mine = await svc("group").seat(viewer(ctx), group2.documentId);
774
+ ok(ctx, await svc("view").group(mine, viewer(ctx)));
775
+ }),
776
+ group: handle(
777
+ strapi,
778
+ async (ctx) => ok(ctx, await svc("view").group(await seat(ctx), viewer(ctx)))
779
+ ),
780
+ renameGroup: handle(strapi, async (ctx) => {
781
+ const mine = await writable(ctx);
782
+ const group2 = await svc("group").rename(mine, body(ctx).name);
783
+ ok(ctx, svc("format").group(group2));
784
+ }),
785
+ archiveGroup: handle(strapi, async (ctx) => {
786
+ const mine = await seat(ctx);
787
+ svc("group").assertOwner(mine.me);
788
+ ok(ctx, svc("format").group(await svc("group").archive(mine.group, viewer(ctx))));
789
+ }),
790
+ leaveGroup: handle(strapi, async (ctx) => {
791
+ await svc("member").leave(await seat(ctx));
792
+ noContent(ctx);
793
+ }),
794
+ // ── Members ──────────────────────────────────────────────────────────
795
+ addMember: handle(strapi, async (ctx) => {
796
+ const added = await svc("member").add(await writable(ctx), body(ctx));
797
+ written(ctx, svc("format").member(added, viewer(ctx)), false);
798
+ }),
799
+ removeMember: handle(strapi, async (ctx) => {
800
+ await svc("member").remove(await writable(ctx), ctx.params.member);
801
+ noContent(ctx);
802
+ }),
803
+ // ── Expenses ─────────────────────────────────────────────────────────
804
+ expenses: handle(strapi, async (ctx) => {
805
+ const mine = await seat(ctx);
806
+ const page = parsePagination(ctx.query);
807
+ const { items, total } = await svc("expense").list(mine.group, page);
808
+ ctx.body = paged(
809
+ items.map((e) => svc("format").expense(e, mine.me, viewer(ctx))),
810
+ total,
811
+ page
812
+ );
813
+ }),
814
+ createExpense: handle(strapi, async (ctx) => {
815
+ const mine = await writable(ctx);
816
+ const { expense: expense2, replayed } = await svc("expense").create(mine, body(ctx));
817
+ written(ctx, svc("format").expense(expense2, mine.me, viewer(ctx)), replayed);
818
+ }),
819
+ updateExpense: handle(strapi, async (ctx) => {
820
+ const mine = await writable(ctx);
821
+ const expense2 = await svc("expense").update(mine, ctx.params.expense, body(ctx));
822
+ ok(ctx, svc("format").expense(expense2, mine.me, viewer(ctx)));
823
+ }),
824
+ deleteExpense: handle(strapi, async (ctx) => {
825
+ await svc("expense").remove(await writable(ctx), ctx.params.expense);
826
+ noContent(ctx);
827
+ }),
828
+ // ── Settlements ──────────────────────────────────────────────────────
829
+ settlements: handle(strapi, async (ctx) => {
830
+ const page = parsePagination(ctx.query);
831
+ const { total, ...data } = await svc("view").settlements(await seat(ctx), viewer(ctx), page);
832
+ ok(ctx, data, paged([], total, page).meta);
833
+ }),
834
+ createSettlement: handle(strapi, async (ctx) => {
835
+ const mine = await writable(ctx);
836
+ const { settlement: settlement2, replayed } = await svc("settlement").create(mine, body(ctx));
837
+ written(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)), replayed);
838
+ }),
839
+ confirmSettlement: handle(strapi, async (ctx) => {
840
+ const mine = await seat(ctx);
841
+ const settlement2 = await svc("settlement").confirm(mine, ctx.params.settlement);
842
+ ok(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)));
843
+ }),
844
+ rejectSettlement: handle(strapi, async (ctx) => {
845
+ const mine = await seat(ctx);
846
+ const settlement2 = await svc("settlement").reject(mine, ctx.params.settlement);
847
+ ok(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)));
848
+ }),
849
+ cancelSettlement: handle(strapi, async (ctx) => {
850
+ const mine = await seat(ctx);
851
+ const settlement2 = await svc("settlement").cancel(mine, ctx.params.settlement);
852
+ ok(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)));
853
+ })
854
+ };
855
+ };
856
+ const randomCode = (length) => {
857
+ let out = "";
858
+ for (let i = 0; i < length; i += 1) out += CODE_CHARSET[node_crypto.randomInt(CODE_CHARSET.length)];
859
+ return out;
860
+ };
861
+ const PHONE_MIN = 7;
862
+ const PHONE_MAX = 15;
863
+ const normalizePhone = (raw, countryCode) => {
864
+ if (!/^[\d\s+().-]+$/.test(String(raw ?? ""))) return null;
865
+ let digits = String(raw).replace(/\D/g, "").replace(/^00/, "");
866
+ if (countryCode && digits.startsWith(countryCode) && digits.length > countryCode.length + 6) {
867
+ digits = digits.slice(countryCode.length);
868
+ }
869
+ return digits.length >= PHONE_MIN && digits.length <= PHONE_MAX ? digits : null;
870
+ };
871
+ const maskPhone = (phone) => {
872
+ if (!phone) return null;
873
+ const s = String(phone);
874
+ return s.length <= 4 ? "••••" : `${s.slice(0, 2)}${"•".repeat(s.length - 4)}${s.slice(-2)}`;
875
+ };
876
+ const idOf = (relation) => relation !== null && typeof relation === "object" ? relation.id : relation ?? null;
877
+ const NOBODY = Object.freeze({ id: null, role: null });
878
+ const EXPENSE_POPULATE = {
879
+ group: { select: ["id", "documentId", "name"] },
880
+ paidBy: { populate: { person: true } },
881
+ addedBy: { select: ["id"] },
882
+ shares: { populate: { member: { populate: { person: true } } } }
883
+ };
884
+ const SETTLEMENT_POPULATE = {
885
+ group: { select: ["id", "documentId", "name"] },
886
+ from: { populate: { person: true } },
887
+ to: { populate: { person: true } }
888
+ };
889
+ const byDateDesc = (a, b) => new Date(b.at) - new Date(a.at);
890
+ const view = ({ strapi }) => {
891
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
892
+ return {
893
+ /** What the viewer still has to pay, with the number to pay it to. */
894
+ debts(books, me, viewer) {
895
+ const format2 = svc("format");
896
+ return books.payments.filter((p) => p.from === me.id).map((p) => {
897
+ const to = books.seatById.get(p.to);
898
+ return {
899
+ to: { ...format2.member(to, viewer), phone: format2.phoneOf(to) },
900
+ amount: p.amount,
901
+ payable: Math.min(p.amount, books.room(me.id, p.to)),
902
+ pending: svc("ledger").pendingBetween(books, me.id, p.to)
903
+ };
904
+ });
905
+ },
906
+ /** What the viewer is waiting for. */
907
+ credits(books, me, viewer) {
908
+ const format2 = svc("format");
909
+ return books.payments.filter((p) => p.to === me.id).map((p) => ({
910
+ from: format2.member(books.seatById.get(p.from), viewer),
911
+ amount: p.amount,
912
+ receivable: Math.min(p.amount, books.room(p.from, me.id)),
913
+ pending: svc("ledger").pendingBetween(books, p.from, me.id)
914
+ }));
915
+ },
916
+ /** Everyone who is in the group or still has something on the books. */
917
+ balances(books, viewer) {
918
+ const format2 = svc("format");
919
+ return books.seats.filter((s) => !s.leftAt || books.balanceOf(s.id) !== 0).map((s) => ({ member: format2.member(s, viewer), amount: books.balanceOf(s.id) }));
920
+ },
921
+ /** One group, as its first screen shows it. */
922
+ async group({ group: group2, me }, viewer) {
923
+ const format2 = svc("format");
924
+ const [books, recent] = await Promise.all([
925
+ svc("ledger").of(group2),
926
+ svc("expense").list(group2, { offset: 0, limit: GROUP_RECENT_EXPENSES })
927
+ ]);
928
+ return {
929
+ ...format2.group(group2),
930
+ role: me.role,
931
+ you: format2.member(me, viewer),
932
+ balance: books.balanceOf(me.id),
933
+ memberCount: books.active.length,
934
+ expenseCount: books.expenseCount,
935
+ total: books.total,
936
+ members: books.active.map((s) => format2.member(s, viewer)),
937
+ balances: this.balances(books, viewer),
938
+ debts: this.debts(books, me, viewer),
939
+ credits: this.credits(books, me, viewer),
940
+ expenses: recent.items.map((e) => format2.expense(e, me, viewer))
941
+ };
942
+ },
943
+ /** The home screen: every group at a glance, what to pay first, who owes the viewer. */
944
+ async overview(viewer) {
945
+ const format2 = svc("format");
946
+ const seats = await svc("group").seatsOf(viewer);
947
+ const perGroup = await Promise.all(
948
+ seats.map(async (me) => {
949
+ const books = await svc("ledger").of(me.group);
950
+ const tag = { id: me.group.documentId, name: me.group.name };
951
+ return {
952
+ summary: {
953
+ ...format2.group(me.group),
954
+ role: me.role,
955
+ memberCount: books.active.length,
956
+ balance: books.balanceOf(me.id)
957
+ },
958
+ debts: this.debts(books, me, viewer).map((d) => ({ ...d, group: tag })),
959
+ credits: this.credits(books, me, viewer).map((c) => ({ ...c, group: tag }))
960
+ };
961
+ })
962
+ );
963
+ const debts = perGroup.flatMap((g) => g.debts).sort((a, b) => b.amount - a.amount);
964
+ const credits = perGroup.flatMap((g) => g.credits).sort((a, b) => b.amount - a.amount);
965
+ const sum = (list) => list.reduce((total, item) => total + item.amount, 0);
966
+ return {
967
+ owe: sum(debts),
968
+ owed: sum(credits),
969
+ debts,
970
+ credits,
971
+ groups: perGroup.map((g) => g.summary).sort((a, b) => new Date(b.lastActivityAt ?? 0) - new Date(a.lastActivityAt ?? 0))
972
+ };
973
+ },
974
+ /** The settle screens of one group: what to pay, what is awaited, how, and what happened. */
975
+ async settlements({ group: group2, me }, viewer, page) {
976
+ const format2 = svc("format");
977
+ const [books, history] = await Promise.all([
978
+ svc("ledger").of(group2),
979
+ svc("settlement").list({ group: group2.id }, page)
980
+ ]);
981
+ return {
982
+ debts: this.debts(books, me, viewer),
983
+ credits: this.credits(books, me, viewer),
984
+ methods: Object.entries(svc("settings").methods()).map(([key, m]) => ({ key, ...m })),
985
+ history: history.items.map((s) => format2.settlement(s, me, viewer)),
986
+ total: history.total
987
+ };
988
+ },
989
+ /**
990
+ * Expenses and settlements across the viewer's groups, newest first.
991
+ * @param {Object} viewer
992
+ * @param {{ offset: number, limit: number }} page
993
+ * @returns {Promise<{ items: Object[], total: number }>}
994
+ */
995
+ async activity(viewer, page) {
996
+ const format2 = svc("format");
997
+ const seats = await svc("group").seatsOf(viewer);
998
+ if (seats.length === 0) return { items: [], total: 0 };
999
+ const seatByGroup = new Map(seats.map((s) => [s.group.id, s]));
1000
+ const inGroups = { group: { id: { $in: [...seatByGroup.keys()] } } };
1001
+ const upTo = page.offset + page.limit;
1002
+ const expenseWhere = { ...inGroups, deletedAt: { $null: true } };
1003
+ const [expenses, settlements, expenseTotal, settlementTotal] = await Promise.all([
1004
+ strapi.db.query(UID.EXPENSE).findMany({
1005
+ where: expenseWhere,
1006
+ populate: EXPENSE_POPULATE,
1007
+ orderBy: { spentAt: "desc" },
1008
+ limit: upTo
1009
+ }),
1010
+ strapi.db.query(UID.SETTLEMENT).findMany({
1011
+ where: inGroups,
1012
+ populate: SETTLEMENT_POPULATE,
1013
+ orderBy: { declaredAt: "desc" },
1014
+ limit: upTo
1015
+ }),
1016
+ strapi.db.query(UID.EXPENSE).count({ where: expenseWhere }),
1017
+ strapi.db.query(UID.SETTLEMENT).count({ where: inGroups })
1018
+ ]);
1019
+ const tag = (g) => ({ id: g.documentId, name: g.name });
1020
+ const items = [
1021
+ ...expenses.map((e) => ({
1022
+ type: "expense",
1023
+ at: e.spentAt,
1024
+ group: tag(e.group),
1025
+ ...format2.expense(e, seatByGroup.get(e.group.id), viewer)
1026
+ })),
1027
+ ...settlements.map((s) => ({
1028
+ type: "settlement",
1029
+ at: s.declaredAt,
1030
+ group: tag(s.group),
1031
+ ...format2.settlement(s, seatByGroup.get(s.group.id), viewer)
1032
+ }))
1033
+ ].sort(byDateDesc).slice(page.offset, upTo).map((item) => ({ ...item, at: new Date(item.at).toISOString() }));
1034
+ return { items, total: expenseTotal + settlementTotal };
1035
+ }
1036
+ };
1037
+ };
1038
+ const flag = (value) => value === "true" ? true : value === "false" ? false : void 0;
1039
+ const admin$1 = ({ strapi }) => {
1040
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
1041
+ const adminPerson = (p) => ({
1042
+ id: p.documentId,
1043
+ displayName: p.displayName ?? null,
1044
+ phone: maskPhone(p.phone),
1045
+ isActive: p.isActive,
1046
+ lastActiveAt: p.lastActiveAt ?? null,
1047
+ createdAt: p.createdAt ?? null
1048
+ });
1049
+ return {
1050
+ dashboard: handle(strapi, async (ctx) => ok(ctx, await svc("stats").dashboard())),
1051
+ // ── Groups ───────────────────────────────────────────────────────────
1052
+ groups: handle(strapi, async (ctx) => {
1053
+ const page = parsePagination(ctx.query);
1054
+ const filters = { q: ctx.query.q, archived: flag(ctx.query.archived) };
1055
+ const { items, total } = await svc("group").search(filters, page);
1056
+ ctx.body = paged(
1057
+ items.map((g) => svc("format").group(g)),
1058
+ total,
1059
+ page
1060
+ );
1061
+ }),
1062
+ group: handle(strapi, async (ctx) => ok(ctx, await svc("stats").group(ctx.params.id))),
1063
+ archiveGroup: handle(strapi, async (ctx) => {
1064
+ const group2 = await svc("group").byDocumentId(ctx.params.id);
1065
+ ok(ctx, svc("format").group(await svc("group").archive(group2, null)));
1066
+ }),
1067
+ // ── People ───────────────────────────────────────────────────────────
1068
+ people: handle(strapi, async (ctx) => {
1069
+ const page = parsePagination(ctx.query);
1070
+ const filters = { q: ctx.query.q, isActive: flag(ctx.query.active) };
1071
+ const { items, total } = await svc("person").search(filters, page);
1072
+ ctx.body = paged(items.map(adminPerson), total, page);
1073
+ }),
1074
+ person: handle(strapi, async (ctx) => {
1075
+ const person2 = await svc("person").byDocumentId(ctx.params.id);
1076
+ ok(ctx, { ...adminPerson(person2), groups: await svc("stats").groupsOf(person2) });
1077
+ }),
1078
+ personPhone: handle(strapi, async (ctx) => {
1079
+ const person2 = await svc("person").byDocumentId(ctx.params.id);
1080
+ strapi.log.info(
1081
+ `[split] phone of ${person2.documentId} revealed to admin ${ctx.state.user?.id}`
1082
+ );
1083
+ ok(ctx, { phone: person2.phone ?? null });
1084
+ }),
1085
+ setPersonActive: handle(strapi, async (ctx) => {
1086
+ ok(ctx, adminPerson(await svc("person").setActive(ctx.params.id, body(ctx).isActive)));
1087
+ }),
1088
+ // ── Settlements & audit ──────────────────────────────────────────────
1089
+ settlements: handle(strapi, async (ctx) => {
1090
+ const page = parsePagination(ctx.query);
1091
+ const { status, method, reference } = ctx.query;
1092
+ const { items, total } = await svc("settlement").list({ status, method, reference }, page);
1093
+ const rows = items.map((s) => ({
1094
+ ...svc("format").settlement(s, NOBODY, null),
1095
+ group: s.group ? { id: s.group.documentId, name: s.group.name } : null
1096
+ }));
1097
+ ctx.body = paged(rows, total, page);
1098
+ }),
1099
+ events: handle(strapi, async (ctx) => {
1100
+ const page = parsePagination(ctx.query);
1101
+ const group2 = ctx.query.group ? await svc("group").byDocumentId(ctx.query.group) : null;
1102
+ const { items, total } = await svc("audit").list(
1103
+ { group: group2?.id, action: ctx.query.action },
1104
+ page
1105
+ );
1106
+ const rows = items.map((e) => ({
1107
+ id: e.documentId,
1108
+ action: e.action,
1109
+ at: e.at,
1110
+ targetId: e.targetId ?? null,
1111
+ data: e.data ?? null,
1112
+ group: e.group ? { id: e.group.documentId, name: e.group.name } : null,
1113
+ actor: e.actor ? { id: e.actor.documentId, displayName: e.actor.displayName } : null
1114
+ }));
1115
+ ctx.body = paged(rows, total, page);
1116
+ }),
1117
+ settings: handle(strapi, async (ctx) => {
1118
+ const settings2 = svc("settings");
1119
+ ok(ctx, {
1120
+ inviteCodePrefix: settings2.inviteCodePrefix(),
1121
+ countryCode: settings2.countryCode(),
1122
+ people: settings2.people(),
1123
+ methods: settings2.methods(),
1124
+ limits: settings2.limits()
1125
+ });
1126
+ })
1127
+ };
1128
+ };
1129
+ const controllers = { app, admin: admin$1 };
1130
+ const header = (ctx, name) => {
1131
+ const value = ctx.request.header[String(name).toLowerCase()];
1132
+ if (typeof value !== "string") return "";
1133
+ try {
1134
+ return decodeURIComponent(value).trim();
1135
+ } catch {
1136
+ return value.trim();
1137
+ }
1138
+ };
1139
+ const person$1 = (_config, { strapi }) => async (ctx, next) => {
1140
+ try {
1141
+ const plugin = strapi.plugin(PLUGIN_ID);
1142
+ const cfg = plugin.service("settings").people();
1143
+ const externalId = header(ctx, cfg.idHeader).slice(0, REF_MAX);
1144
+ if (!externalId) {
1145
+ throw badRequest(
1146
+ ERROR_CODES.PERSON_REQUIRED,
1147
+ `En-tête ${cfg.idHeader} requis : l'identifiant de la personne.`
1148
+ );
1149
+ }
1150
+ const found = await plugin.service("person").resolve({
1151
+ externalId,
1152
+ displayName: header(ctx, cfg.nameHeader) || null,
1153
+ autoProvision: cfg.autoProvision
1154
+ });
1155
+ if (!found.isActive) throw forbidden(ERROR_CODES.PERSON_INACTIVE, "Ce compte est désactivé.");
1156
+ ctx.state.splitPerson = found;
1157
+ ctx.state.splitPersonIsNew = Boolean(found.__created);
1158
+ ctx.set("Cache-Control", "private, no-store");
1159
+ } catch (err) {
1160
+ sendError(ctx, err, strapi);
1161
+ return;
1162
+ }
1163
+ await next();
1164
+ };
1165
+ const middlewares = { person: person$1 };
1166
+ const policies = {};
1167
+ const PERSON = { middlewares: ["plugin::split.person"] };
1168
+ const route$1 = (method, path, handler) => ({
1169
+ method,
1170
+ path,
1171
+ handler: `app.${handler}`,
1172
+ config: PERSON
1173
+ });
1174
+ const contentApi = [
1175
+ // person
1176
+ route$1("GET", "/me", "me"),
1177
+ route$1("GET", "/overview", "overview"),
1178
+ route$1("GET", "/activity", "activity"),
1179
+ // groups
1180
+ route$1("POST", "/groups", "createGroup"),
1181
+ route$1("POST", "/groups/join", "joinGroup"),
1182
+ route$1("GET", "/groups/:group", "group"),
1183
+ route$1("PATCH", "/groups/:group", "renameGroup"),
1184
+ // The same under PUT: some app runtimes (mini-programs) cannot send PATCH.
1185
+ route$1("PUT", "/groups/:group", "renameGroup"),
1186
+ route$1("POST", "/groups/:group/archive", "archiveGroup"),
1187
+ route$1("POST", "/groups/:group/leave", "leaveGroup"),
1188
+ // members
1189
+ route$1("POST", "/groups/:group/members", "addMember"),
1190
+ route$1("DELETE", "/groups/:group/members/:member", "removeMember"),
1191
+ // expenses
1192
+ route$1("GET", "/groups/:group/expenses", "expenses"),
1193
+ route$1("POST", "/groups/:group/expenses", "createExpense"),
1194
+ route$1("PUT", "/groups/:group/expenses/:expense", "updateExpense"),
1195
+ route$1("DELETE", "/groups/:group/expenses/:expense", "deleteExpense"),
1196
+ // settlements
1197
+ route$1("GET", "/groups/:group/settlements", "settlements"),
1198
+ route$1("POST", "/groups/:group/settlements", "createSettlement"),
1199
+ route$1("POST", "/groups/:group/settlements/:settlement/confirm", "confirmSettlement"),
1200
+ route$1("POST", "/groups/:group/settlements/:settlement/reject", "rejectSettlement"),
1201
+ route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement")
1202
+ ];
1203
+ const can = (...actions) => ({
1204
+ policies: [
1205
+ {
1206
+ name: "admin::hasPermissions",
1207
+ config: { actions: actions.map((a) => `plugin::split.${a}`) }
1208
+ }
1209
+ ]
1210
+ });
1211
+ const route = (method, path, handler, action) => ({
1212
+ method,
1213
+ path,
1214
+ handler: `admin.${handler}`,
1215
+ config: can(action)
1216
+ });
1217
+ const admin = [
1218
+ route("GET", "/dashboard", "dashboard", RBAC.DASHBOARD_READ),
1219
+ route("GET", "/groups", "groups", RBAC.GROUPS_READ),
1220
+ route("GET", "/groups/:id", "group", RBAC.GROUPS_READ),
1221
+ route("POST", "/groups/:id/archive", "archiveGroup", RBAC.GROUPS_WRITE),
1222
+ route("GET", "/people", "people", RBAC.PEOPLE_READ),
1223
+ route("GET", "/people/:id", "person", RBAC.PEOPLE_READ),
1224
+ route("GET", "/people/:id/phone", "personPhone", RBAC.PEOPLE_PHONE),
1225
+ route("PUT", "/people/:id/active", "setPersonActive", RBAC.PEOPLE_WRITE),
1226
+ route("GET", "/settlements", "settlements", RBAC.SETTLEMENTS_READ),
1227
+ route("GET", "/events", "events", RBAC.AUDIT_READ),
1228
+ route("GET", "/settings", "settings", RBAC.SETTINGS_READ)
1229
+ ];
1230
+ const routes = {
1231
+ "content-api": { type: "content-api", routes: contentApi },
1232
+ admin: { type: "admin", routes: admin }
1233
+ };
1234
+ const DEFAULT_PEOPLE = Object.freeze({ idHeader: "x-person-id", nameHeader: "x-person-name" });
1235
+ const settings = ({ strapi }) => ({
1236
+ /** @returns {Object} the full plugin config */
1237
+ all() {
1238
+ return strapi.config.get(`plugin::${PLUGIN_ID}`) ?? {};
1239
+ },
1240
+ /** How the caller names the person: header names and whether unknown ids create a person. */
1241
+ people() {
1242
+ const p = this.all().people ?? {};
1243
+ return {
1244
+ autoProvision: p.autoProvision !== false,
1245
+ idHeader: String(p.idHeader || DEFAULT_PEOPLE.idHeader).toLowerCase(),
1246
+ nameHeader: String(p.nameHeader || DEFAULT_PEOPLE.nameHeader).toLowerCase()
1247
+ };
1248
+ },
1249
+ inviteCodePrefix() {
1250
+ return this.all().inviteCodePrefix ?? DEFAULT_INVITE_PREFIX;
1251
+ },
1252
+ countryCode() {
1253
+ return String(this.all().countryCode ?? DEFAULT_COUNTRY_CODE);
1254
+ },
1255
+ /** @returns {Object<string, { instant: boolean }>} every way a debt can be settled */
1256
+ methods() {
1257
+ const methods = this.all().methods ?? DEFAULT_METHODS;
1258
+ return Object.fromEntries(
1259
+ Object.entries(methods).map(([name, m]) => [name, { instant: Boolean(m?.instant) }])
1260
+ );
1261
+ },
1262
+ limits() {
1263
+ return { ...DEFAULT_LIMITS, ...this.all().limits ?? {} };
1264
+ }
1265
+ });
1266
+ const audit = ({ strapi }) => ({
1267
+ /**
1268
+ * @param {{ group: Object, actor: Object|null, action: string, targetId?: string, data?: Object }} event
1269
+ */
1270
+ async log({ group: group2, actor, action, targetId = null, data = null }) {
1271
+ try {
1272
+ await strapi.db.query(UID.EVENT).create({
1273
+ data: { group: group2.id, actor: actor?.id ?? null, action, targetId, data, at: /* @__PURE__ */ new Date() }
1274
+ });
1275
+ } catch (err) {
1276
+ strapi.log.warn(`${LOG_PREFIX} audit ${action}: ${err.message}`);
1277
+ }
1278
+ },
1279
+ /**
1280
+ * @param {{ group?: number, action?: string }} filters
1281
+ * @param {{ offset: number, limit: number }} page
1282
+ */
1283
+ async list(filters, page) {
1284
+ const where = {};
1285
+ if (filters.group) where.group = filters.group;
1286
+ if (filters.action) where.action = filters.action;
1287
+ const [items, total] = await Promise.all([
1288
+ strapi.db.query(UID.EVENT).findMany({
1289
+ where,
1290
+ populate: {
1291
+ group: { select: ["documentId", "name"] },
1292
+ actor: { select: ["documentId", "displayName"] }
1293
+ },
1294
+ orderBy: { at: "desc" },
1295
+ offset: page.offset,
1296
+ limit: page.limit
1297
+ }),
1298
+ strapi.db.query(UID.EVENT).count({ where })
1299
+ ]);
1300
+ return { items, total };
1301
+ }
1302
+ });
1303
+ const iso = (date) => date ? new Date(date).toISOString() : null;
1304
+ const format = () => ({
1305
+ person(p, isNew = false) {
1306
+ return { id: p.documentId, displayName: p.displayName ?? null, phone: p.phone ?? null, isNew };
1307
+ },
1308
+ /** The name a seat goes by: the person's own once they have one, the name it was added under otherwise. */
1309
+ nameOf(member2) {
1310
+ return member2.person?.displayName || member2.displayName;
1311
+ },
1312
+ /** The number money for this seat goes to. */
1313
+ phoneOf(member2) {
1314
+ return member2.person?.phone ?? member2.phone ?? null;
1315
+ },
1316
+ /**
1317
+ * @param {Object} m member row, `person` populated
1318
+ * @param {Object|null} viewer the person asking
1319
+ */
1320
+ member(m, viewer = null) {
1321
+ return {
1322
+ id: m.documentId,
1323
+ displayName: this.nameOf(m),
1324
+ isYou: Boolean(viewer) && idOf(m.person) === viewer.id,
1325
+ isRegistered: Boolean(m.person),
1326
+ role: m.role,
1327
+ hasLeft: Boolean(m.leftAt)
1328
+ };
1329
+ },
1330
+ /** A seat as an administrator sees it: the phone masked. */
1331
+ adminMember(m) {
1332
+ return { ...this.member(m), phone: maskPhone(this.phoneOf(m)), joinedAt: iso(m.joinedAt) };
1333
+ },
1334
+ group(g) {
1335
+ return {
1336
+ id: g.documentId,
1337
+ name: g.name,
1338
+ inviteCode: g.inviteCode,
1339
+ isArchived: Boolean(g.archivedAt),
1340
+ lastActivityAt: iso(g.lastActivityAt)
1341
+ };
1342
+ },
1343
+ /**
1344
+ * @param {Object} e expense row, `paidBy`, `addedBy` and `shares.member` populated with people
1345
+ * @param {Object} me the viewer's seat
1346
+ * @param {Object} viewer the person asking
1347
+ */
1348
+ expense(e, me, viewer) {
1349
+ const shares = (e.shares ?? []).map((s) => ({
1350
+ member: this.member(s.member, viewer),
1351
+ amount: s.amount,
1352
+ weight: s.weight ?? 0
1353
+ }));
1354
+ const mine = (e.shares ?? []).find((s) => idOf(s.member) === me.id);
1355
+ const canEdit = Boolean(me.id) && (me.role === ROLE.OWNER || [idOf(e.paidBy), idOf(e.addedBy)].includes(me.id));
1356
+ return {
1357
+ id: e.documentId,
1358
+ label: e.label,
1359
+ category: e.category ?? null,
1360
+ amount: e.amount,
1361
+ mode: e.mode,
1362
+ spentAt: iso(e.spentAt),
1363
+ paidBy: this.member(e.paidBy, viewer),
1364
+ yourShare: mine ? mine.amount : 0,
1365
+ shares,
1366
+ canEdit
1367
+ };
1368
+ },
1369
+ /**
1370
+ * @param {Object} s settlement row, `from` and `to` populated with people
1371
+ * @param {Object} me the viewer's seat
1372
+ * @param {Object} viewer the person asking
1373
+ */
1374
+ settlement(s, me, viewer) {
1375
+ const pending = s.status === SETTLEMENT_STATUS.PENDING;
1376
+ return {
1377
+ id: s.documentId,
1378
+ from: this.member(s.from, viewer),
1379
+ to: this.member(s.to, viewer),
1380
+ amount: s.amount,
1381
+ method: s.method,
1382
+ status: s.status,
1383
+ reference: s.reference ?? null,
1384
+ note: s.note ?? null,
1385
+ declaredAt: iso(s.declaredAt),
1386
+ resolvedAt: iso(s.resolvedAt),
1387
+ canConfirm: pending && idOf(s.to) === me.id,
1388
+ canCancel: pending && idOf(s.from) === me.id
1389
+ };
1390
+ }
1391
+ });
1392
+ const ACTIVITY_STAMP_MS = 5 * 60 * 1e3;
1393
+ const isDuplicate$2 = (err) => /unique|duplicate/i.test(String(err?.message));
1394
+ const person = ({ strapi }) => ({
1395
+ /** The stored spelling of an id: a phone number has one spelling, anything else is kept as sent. */
1396
+ canonical(externalId) {
1397
+ const raw = String(externalId).trim();
1398
+ const country = strapi.plugin(PLUGIN_ID).service("settings").countryCode();
1399
+ const phone = normalizePhone(raw, country);
1400
+ return { externalId: phone ?? raw, phone };
1401
+ },
1402
+ /** What changed on a returning person, or null when nothing is worth a write. */
1403
+ refresh(existing, displayName, now) {
1404
+ const patch = {};
1405
+ const name = displayName ? displayName.slice(0, NAME_MAX) : null;
1406
+ if (name && name !== existing.displayName) patch.displayName = name;
1407
+ const seen = existing.lastActiveAt ? new Date(existing.lastActiveAt).getTime() : 0;
1408
+ if (now.getTime() - seen > ACTIVITY_STAMP_MS) patch.lastActiveAt = now;
1409
+ return Object.keys(patch).length ? patch : null;
1410
+ },
1411
+ /**
1412
+ * The person behind an external id, created on first sight when `autoProvision` is on.
1413
+ * @param {{ externalId: string, displayName?: string|null, autoProvision?: boolean }} p
1414
+ * @returns {Promise<Object>} the person row (`__created` is true when it was just provisioned)
1415
+ */
1416
+ async resolve({ externalId, displayName = null, autoProvision = true }) {
1417
+ const now = /* @__PURE__ */ new Date();
1418
+ const id = this.canonical(externalId);
1419
+ const people = strapi.db.query(UID.PERSON);
1420
+ const existing = await people.findOne({ where: { externalId: id.externalId } });
1421
+ if (existing) {
1422
+ const patch = this.refresh(existing, displayName, now);
1423
+ return patch ? people.update({ where: { id: existing.id }, data: patch }) : existing;
1424
+ }
1425
+ if (!autoProvision) throw notFound(ERROR_CODES.PERSON_NOT_FOUND, "Personne inconnue.");
1426
+ try {
1427
+ const person2 = await people.create({
1428
+ data: {
1429
+ ...id,
1430
+ displayName: displayName ? displayName.slice(0, NAME_MAX) : null,
1431
+ isActive: true,
1432
+ lastActiveAt: now
1433
+ }
1434
+ });
1435
+ await this.claimSeats(person2);
1436
+ return { ...person2, __created: true };
1437
+ } catch (err) {
1438
+ if (!isDuplicate$2(err)) throw err;
1439
+ return people.findOne({ where: { externalId: id.externalId } });
1440
+ }
1441
+ },
1442
+ /**
1443
+ * Seats added by phone before this person existed become theirs.
1444
+ * @param {Object} person
1445
+ * @returns {Promise<number>} seats claimed
1446
+ */
1447
+ async claimSeats(person2) {
1448
+ if (!person2.phone) return 0;
1449
+ const seats = await strapi.db.query(UID.MEMBER).findMany({
1450
+ where: { phone: person2.phone, person: { id: { $null: true } }, leftAt: { $null: true } },
1451
+ select: ["id"]
1452
+ });
1453
+ for (const seat of seats) {
1454
+ await strapi.db.query(UID.MEMBER).update({ where: { id: seat.id }, data: { person: person2.id, joinedAt: /* @__PURE__ */ new Date() } });
1455
+ }
1456
+ return seats.length;
1457
+ },
1458
+ /** The registered person with this phone, if any. */
1459
+ async byPhone(phone) {
1460
+ return phone ? strapi.db.query(UID.PERSON).findOne({ where: { phone } }) : null;
1461
+ },
1462
+ async byDocumentId(documentId) {
1463
+ const person2 = await strapi.db.query(UID.PERSON).findOne({ where: { documentId } });
1464
+ if (!person2) throw notFound(ERROR_CODES.PERSON_NOT_FOUND, "Personne introuvable.");
1465
+ return person2;
1466
+ },
1467
+ /**
1468
+ * Admin search by name, phone fragment or external id.
1469
+ * @param {{ q?: string, isActive?: boolean }} filters
1470
+ * @param {{ offset: number, limit: number }} page
1471
+ */
1472
+ async search(filters, page) {
1473
+ const where = {};
1474
+ if (filters.q) {
1475
+ const q = String(filters.q).trim();
1476
+ const digits = q.replace(/\D/g, "");
1477
+ where.$or = [{ displayName: { $containsi: q } }, { externalId: { $containsi: q } }];
1478
+ if (digits) where.$or.push({ phone: { $contains: digits } });
1479
+ }
1480
+ if (typeof filters.isActive === "boolean") where.isActive = filters.isActive;
1481
+ const [items, total] = await Promise.all([
1482
+ strapi.db.query(UID.PERSON).findMany({
1483
+ where,
1484
+ orderBy: { lastActiveAt: "desc" },
1485
+ offset: page.offset,
1486
+ limit: page.limit
1487
+ }),
1488
+ strapi.db.query(UID.PERSON).count({ where })
1489
+ ]);
1490
+ return { items, total };
1491
+ },
1492
+ async setActive(documentId, isActive) {
1493
+ const person2 = await this.byDocumentId(documentId);
1494
+ return strapi.db.query(UID.PERSON).update({ where: { id: person2.id }, data: { isActive: Boolean(isActive) } });
1495
+ }
1496
+ });
1497
+ const add = (map, key, delta) => map.set(key, (map.get(key) ?? 0) + delta);
1498
+ const computeBalances = ({ expenses, settlements }) => {
1499
+ const balances = /* @__PURE__ */ new Map();
1500
+ for (const expense2 of expenses) {
1501
+ add(balances, expense2.paidBy, expense2.amount);
1502
+ for (const share2 of expense2.shares) add(balances, share2.member, -share2.amount);
1503
+ }
1504
+ for (const s of settlements) {
1505
+ if (s.status !== SETTLEMENT_STATUS.CONFIRMED) continue;
1506
+ add(balances, s.from, s.amount);
1507
+ add(balances, s.to, -s.amount);
1508
+ }
1509
+ return balances;
1510
+ };
1511
+ const bySize = (a, b) => b.amount - a.amount || String(a.member).localeCompare(String(b.member));
1512
+ const suggestPayments = (balances) => {
1513
+ const creditors = [];
1514
+ const debtors = [];
1515
+ for (const [member2, balance] of balances) {
1516
+ if (balance > 0) creditors.push({ member: member2, amount: balance });
1517
+ if (balance < 0) debtors.push({ member: member2, amount: -balance });
1518
+ }
1519
+ creditors.sort(bySize);
1520
+ debtors.sort(bySize);
1521
+ const payments = [];
1522
+ let c = 0;
1523
+ let d = 0;
1524
+ while (c < creditors.length && d < debtors.length) {
1525
+ const amount = Math.min(creditors[c].amount, debtors[d].amount);
1526
+ payments.push({ from: debtors[d].member, to: creditors[c].member, amount });
1527
+ creditors[c].amount -= amount;
1528
+ debtors[d].amount -= amount;
1529
+ if (creditors[c].amount === 0) c += 1;
1530
+ if (debtors[d].amount === 0) d += 1;
1531
+ }
1532
+ return payments;
1533
+ };
1534
+ const headroom = ({ balances, settlements, from, to }) => {
1535
+ const owes = Math.max(0, -(balances.get(from) ?? 0));
1536
+ const owed = Math.max(0, balances.get(to) ?? 0);
1537
+ const pendingOut = settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.from === from).reduce((sum, s) => sum + s.amount, 0);
1538
+ const pendingIn = settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.to === to).reduce((sum, s) => sum + s.amount, 0);
1539
+ return Math.max(0, Math.min(owes - pendingOut, owed - pendingIn));
1540
+ };
1541
+ const LIVE_STATUSES = [SETTLEMENT_STATUS.PENDING, SETTLEMENT_STATUS.CONFIRMED];
1542
+ const ledger = ({ strapi }) => ({
1543
+ /** Every seat of a group, people populated, in the order they joined. */
1544
+ async seats(group2) {
1545
+ return strapi.db.query(UID.MEMBER).findMany({
1546
+ where: { group: group2.id },
1547
+ populate: { person: true },
1548
+ orderBy: { id: "asc" }
1549
+ });
1550
+ },
1551
+ /** Expenses that count, flattened to ids. */
1552
+ async expenses(group2) {
1553
+ const rows = await strapi.db.query(UID.EXPENSE).findMany({
1554
+ where: { group: group2.id, deletedAt: { $null: true } },
1555
+ select: ["id", "amount"],
1556
+ populate: {
1557
+ paidBy: { select: ["id"] },
1558
+ shares: { select: ["amount"], populate: { member: { select: ["id"] } } }
1559
+ }
1560
+ });
1561
+ return rows.map((e) => ({
1562
+ paidBy: idOf(e.paidBy),
1563
+ amount: e.amount,
1564
+ shares: (e.shares ?? []).map((s) => ({ member: idOf(s.member), amount: s.amount }))
1565
+ }));
1566
+ },
1567
+ /** Settlements that count or reserve room, flattened to ids. */
1568
+ async settlements(group2) {
1569
+ const rows = await strapi.db.query(UID.SETTLEMENT).findMany({
1570
+ where: { group: group2.id, status: { $in: LIVE_STATUSES } },
1571
+ select: ["id", "amount", "status"],
1572
+ populate: { from: { select: ["id"] }, to: { select: ["id"] } }
1573
+ });
1574
+ return rows.map((s) => ({
1575
+ from: idOf(s.from),
1576
+ to: idOf(s.to),
1577
+ amount: s.amount,
1578
+ status: s.status
1579
+ }));
1580
+ },
1581
+ /**
1582
+ * @param {Object} group
1583
+ * @returns {Promise<{ seats: Object[], active: Object[], seatById: Map, balances: Map, payments: Array,
1584
+ * settlements: Array, expenseCount: number, total: number, room: Function, balanceOf: Function }>}
1585
+ */
1586
+ async of(group2) {
1587
+ const [seats, expenses, settlements] = await Promise.all([
1588
+ this.seats(group2),
1589
+ this.expenses(group2),
1590
+ this.settlements(group2)
1591
+ ]);
1592
+ const balances = computeBalances({ expenses, settlements });
1593
+ return {
1594
+ seats,
1595
+ active: seats.filter((s) => !s.leftAt),
1596
+ seatById: new Map(seats.map((s) => [s.id, s])),
1597
+ balances,
1598
+ payments: suggestPayments(balances),
1599
+ settlements,
1600
+ expenseCount: expenses.length,
1601
+ total: expenses.reduce((sum, e) => sum + e.amount, 0),
1602
+ /** The most seat `from` may still settle towards seat `to`. */
1603
+ room: (from, to) => headroom({ balances, settlements, from, to }),
1604
+ balanceOf: (seatId) => balances.get(seatId) ?? 0
1605
+ };
1606
+ },
1607
+ /** What is declared and awaiting confirmation from one seat to another. */
1608
+ pendingBetween(books, from, to) {
1609
+ return books.settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.from === from && s.to === to).reduce((sum, s) => sum + s.amount, 0);
1610
+ }
1611
+ });
1612
+ const cleanName = (raw) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, NAME_MAX);
1613
+ const group = ({ strapi }) => {
1614
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
1615
+ const groups = () => strapi.db.query(UID.GROUP);
1616
+ const members = () => strapi.db.query(UID.MEMBER);
1617
+ return {
1618
+ cleanName,
1619
+ async generateInviteCode() {
1620
+ const prefix = svc("settings").inviteCodePrefix();
1621
+ for (let i = 0; i < MAX_CODE_ATTEMPTS; i += 1) {
1622
+ const inviteCode = `${prefix}-${randomCode(INVITE_CODE_LENGTH)}`;
1623
+ const taken = await groups().findOne({ where: { inviteCode }, select: ["id"] });
1624
+ if (!taken) return inviteCode;
1625
+ }
1626
+ throw conflict(ERROR_CODES.VALIDATION, "Impossible de générer un code d'invitation unique.");
1627
+ },
1628
+ /**
1629
+ * The group and the caller's seat in it.
1630
+ * @param {Object} person
1631
+ * @param {string} documentId
1632
+ * @param {{ writable?: boolean }} [options] `writable` refuses an archived group
1633
+ * @returns {Promise<{ group: Object, me: Object }>}
1634
+ */
1635
+ async seat(person2, documentId, { writable = false } = {}) {
1636
+ const group2 = await groups().findOne({ where: { documentId: String(documentId) } });
1637
+ const me = group2 && await members().findOne({
1638
+ where: { group: group2.id, person: person2.id, leftAt: { $null: true } },
1639
+ populate: { person: true }
1640
+ });
1641
+ if (!me) throw notFound(ERROR_CODES.GROUP_NOT_FOUND, "Groupe introuvable.");
1642
+ if (writable && group2.archivedAt)
1643
+ throw conflict(ERROR_CODES.GROUP_ARCHIVED, "Ce groupe est archivé.");
1644
+ return { group: group2, me };
1645
+ },
1646
+ /** Only the owner. */
1647
+ assertOwner(me) {
1648
+ if (me.role !== ROLE.OWNER)
1649
+ throw forbidden(ERROR_CODES.NOT_ALLOWED, "Seul le créateur du groupe peut faire ça.");
1650
+ },
1651
+ /** The seats a person holds, groups populated; archived groups only on request. */
1652
+ async seatsOf(person2, { archived = false } = {}) {
1653
+ const rows = await members().findMany({
1654
+ where: { person: person2.id, leftAt: { $null: true } },
1655
+ populate: { group: true, person: true }
1656
+ });
1657
+ return rows.filter((m) => m.group && Boolean(m.group.archivedAt) === archived);
1658
+ },
1659
+ /** A write that every other write of the group waits behind: taken first in a transaction. */
1660
+ async lock(group2) {
1661
+ await groups().update({ where: { id: group2.id }, data: { lastActivityAt: /* @__PURE__ */ new Date() } });
1662
+ },
1663
+ /**
1664
+ * @param {Object} person the creator, who becomes the owner
1665
+ * @param {{ name: string, members?: Array<{ name: string, phone?: string }> }} input
1666
+ */
1667
+ async create(person2, input) {
1668
+ const name = cleanName(input.name);
1669
+ if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
1670
+ const limits = svc("settings").limits();
1671
+ const held = await members().count({ where: { person: person2.id, leftAt: { $null: true } } });
1672
+ if (held >= limits.maxGroupsPerPerson)
1673
+ throw unprocessable(
1674
+ ERROR_CODES.GROUP_LIMIT,
1675
+ `Maximum ${limits.maxGroupsPerPerson} groupes.`
1676
+ );
1677
+ const others = svc("member").parseMany(input.members ?? [], person2);
1678
+ if (others.length + 1 > limits.maxMembersPerGroup)
1679
+ throw unprocessable(
1680
+ ERROR_CODES.MEMBER_LIMIT,
1681
+ `Maximum ${limits.maxMembersPerGroup} membres.`
1682
+ );
1683
+ const inviteCode = await this.generateInviteCode();
1684
+ const now = /* @__PURE__ */ new Date();
1685
+ const group2 = await strapi.db.transaction(async () => {
1686
+ const g = await groups().create({
1687
+ data: { name, inviteCode, founder: person2.id, lastActivityAt: now }
1688
+ });
1689
+ await members().create({
1690
+ data: {
1691
+ group: g.id,
1692
+ person: person2.id,
1693
+ displayName: person2.displayName || "Moi",
1694
+ phone: person2.phone ?? null,
1695
+ role: ROLE.OWNER,
1696
+ joinedAt: now
1697
+ }
1698
+ });
1699
+ for (const other of others) await svc("member").seatFor(g, other);
1700
+ return g;
1701
+ });
1702
+ await svc("audit").log({
1703
+ group: group2,
1704
+ actor: person2,
1705
+ action: EVENT.GROUP_CREATED,
1706
+ data: { members: others.length + 1 }
1707
+ });
1708
+ return group2;
1709
+ },
1710
+ async rename({ group: group2, me }, rawName) {
1711
+ this.assertOwner(me);
1712
+ const name = cleanName(rawName);
1713
+ if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
1714
+ const updated = await groups().update({ where: { id: group2.id }, data: { name } });
1715
+ await svc("audit").log({
1716
+ group: group2,
1717
+ actor: me.person,
1718
+ action: EVENT.GROUP_RENAMED,
1719
+ data: { from: group2.name, to: name }
1720
+ });
1721
+ return updated;
1722
+ },
1723
+ /** @param {Object} group @param {Object|null} actor a person, or null for an administrator */
1724
+ async archive(group2, actor) {
1725
+ if (group2.archivedAt) return group2;
1726
+ const updated = await groups().update({
1727
+ where: { id: group2.id },
1728
+ data: { archivedAt: /* @__PURE__ */ new Date() }
1729
+ });
1730
+ await svc("audit").log({ group: group2, actor, action: EVENT.GROUP_ARCHIVED });
1731
+ return updated;
1732
+ },
1733
+ /**
1734
+ * Take a seat with an invite code. A seat that was waiting for this person's phone is theirs
1735
+ * already; joining twice is not an error.
1736
+ */
1737
+ async join(person2, rawCode) {
1738
+ const inviteCode = String(rawCode ?? "").trim().toUpperCase();
1739
+ const group2 = inviteCode && await groups().findOne({ where: { inviteCode } });
1740
+ if (!group2 || group2.archivedAt)
1741
+ throw notFound(ERROR_CODES.INVITE_INVALID, "Ce code d'invitation n'existe pas.");
1742
+ const existing = await members().findOne({
1743
+ where: { group: group2.id, person: person2.id, leftAt: { $null: true } }
1744
+ });
1745
+ if (existing) return group2;
1746
+ const limits = svc("settings").limits();
1747
+ const count = await members().count({ where: { group: group2.id, leftAt: { $null: true } } });
1748
+ if (count >= limits.maxMembersPerGroup)
1749
+ throw unprocessable(ERROR_CODES.MEMBER_LIMIT, "Ce groupe est complet.");
1750
+ await members().create({
1751
+ data: {
1752
+ group: group2.id,
1753
+ person: person2.id,
1754
+ displayName: person2.displayName || "Membre",
1755
+ phone: person2.phone ?? null,
1756
+ role: ROLE.MEMBER,
1757
+ joinedAt: /* @__PURE__ */ new Date()
1758
+ }
1759
+ });
1760
+ await svc("audit").log({ group: group2, actor: person2, action: EVENT.MEMBER_JOINED });
1761
+ return group2;
1762
+ },
1763
+ async byDocumentId(documentId) {
1764
+ const group2 = await groups().findOne({ where: { documentId: String(documentId) } });
1765
+ if (!group2) throw notFound(ERROR_CODES.GROUP_NOT_FOUND, "Groupe introuvable.");
1766
+ return group2;
1767
+ },
1768
+ /**
1769
+ * Admin search by name or invite code.
1770
+ * @param {{ q?: string, archived?: boolean }} filters
1771
+ * @param {{ offset: number, limit: number }} page
1772
+ */
1773
+ async search(filters, page) {
1774
+ const where = {};
1775
+ if (filters.q) {
1776
+ const q = String(filters.q).trim();
1777
+ where.$or = [{ name: { $containsi: q } }, { inviteCode: { $containsi: q } }];
1778
+ }
1779
+ if (typeof filters.archived === "boolean")
1780
+ where.archivedAt = filters.archived ? { $notNull: true } : { $null: true };
1781
+ const [items, total] = await Promise.all([
1782
+ groups().findMany({
1783
+ where,
1784
+ orderBy: { lastActivityAt: "desc" },
1785
+ offset: page.offset,
1786
+ limit: page.limit
1787
+ }),
1788
+ groups().count({ where })
1789
+ ]);
1790
+ return { items, total };
1791
+ }
1792
+ };
1793
+ };
1794
+ const member = ({ strapi }) => {
1795
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
1796
+ const members = () => strapi.db.query(UID.MEMBER);
1797
+ return {
1798
+ /** One `{ name, phone }` as sent, checked. */
1799
+ parse(raw) {
1800
+ const displayName = String(raw?.name ?? "").trim().replace(/\s+/g, " ").slice(0, NAME_MAX);
1801
+ if (!displayName) throw badRequest(ERROR_CODES.VALIDATION, "Chaque membre a un nom.");
1802
+ const sent = String(raw?.phone ?? "").trim();
1803
+ const phone = sent ? normalizePhone(sent, svc("settings").countryCode()) : null;
1804
+ if (sent && !phone) throw badRequest(ERROR_CODES.VALIDATION, "Numéro de téléphone invalide.");
1805
+ return { displayName, phone };
1806
+ },
1807
+ /** Several at once (a new group): nobody twice, and not the creator. */
1808
+ parseMany(list, creator) {
1809
+ if (!Array.isArray(list))
1810
+ throw badRequest(ERROR_CODES.VALIDATION, "Liste de membres invalide.");
1811
+ const parsed = list.map((raw) => this.parse(raw));
1812
+ const phones = parsed.map((m) => m.phone).filter(Boolean);
1813
+ if (new Set(phones).size !== phones.length || phones.includes(creator.phone))
1814
+ throw conflict(ERROR_CODES.MEMBER_EXISTS, "Un numéro apparaît deux fois.");
1815
+ return parsed;
1816
+ },
1817
+ /** Create the seat; it is the person's at once when that phone already uses the app. */
1818
+ async seatFor(group2, { displayName, phone }) {
1819
+ const person2 = await svc("person").byPhone(phone);
1820
+ return members().create({
1821
+ data: {
1822
+ group: group2.id,
1823
+ person: person2?.id ?? null,
1824
+ displayName,
1825
+ phone,
1826
+ role: ROLE.MEMBER,
1827
+ joinedAt: person2 ? /* @__PURE__ */ new Date() : null
1828
+ }
1829
+ });
1830
+ },
1831
+ /**
1832
+ * @param {{ group: Object, me: Object }} seat the caller's
1833
+ * @param {{ name: string, phone?: string }} raw
1834
+ * @returns {Promise<Object>} the new seat, person populated
1835
+ */
1836
+ async add({ group: group2, me }, raw) {
1837
+ const input = this.parse(raw);
1838
+ const limits = svc("settings").limits();
1839
+ const seats = await members().findMany({
1840
+ where: { group: group2.id, leftAt: { $null: true } },
1841
+ populate: { person: true }
1842
+ });
1843
+ if (seats.length >= limits.maxMembersPerGroup)
1844
+ throw unprocessable(
1845
+ ERROR_CODES.MEMBER_LIMIT,
1846
+ `Maximum ${limits.maxMembersPerGroup} membres.`
1847
+ );
1848
+ const format2 = svc("format");
1849
+ if (input.phone && seats.some((s) => format2.phoneOf(s) === input.phone))
1850
+ throw conflict(ERROR_CODES.MEMBER_EXISTS, "Ce numéro est déjà dans le groupe.");
1851
+ const created = await this.seatFor(group2, input);
1852
+ await svc("audit").log({
1853
+ group: group2,
1854
+ actor: me.person,
1855
+ action: EVENT.MEMBER_ADDED,
1856
+ targetId: created.documentId
1857
+ });
1858
+ return members().findOne({ where: { id: created.id }, populate: { person: true } });
1859
+ },
1860
+ /** A seat of this group by its document id. */
1861
+ async find(group2, documentId) {
1862
+ const seat = await members().findOne({
1863
+ where: { group: group2.id, documentId: String(documentId), leftAt: { $null: true } },
1864
+ populate: { person: true }
1865
+ });
1866
+ if (!seat) throw notFound(ERROR_CODES.MEMBER_NOT_FOUND, "Membre introuvable.");
1867
+ return seat;
1868
+ },
1869
+ /** A seat is only vacated once it is even and nothing awaits confirmation on it. */
1870
+ async assertSettled(group2, seat) {
1871
+ const books = await svc("ledger").of(group2);
1872
+ const busy = books.settlements.some(
1873
+ (s) => s.status === SETTLEMENT_STATUS.PENDING && [s.from, s.to].includes(seat.id)
1874
+ );
1875
+ if (books.balanceOf(seat.id) !== 0 || busy)
1876
+ throw unprocessable(
1877
+ ERROR_CODES.MEMBER_NOT_SETTLED,
1878
+ "Les comptes de ce membre ne sont pas à zéro.",
1879
+ { balance: books.balanceOf(seat.id) }
1880
+ );
1881
+ },
1882
+ /** The owner removes someone else. */
1883
+ async remove({ group: group2, me }, documentId) {
1884
+ svc("group").assertOwner(me);
1885
+ const seat = await this.find(group2, documentId);
1886
+ if (seat.id === me.id)
1887
+ throw forbidden(ERROR_CODES.NOT_ALLOWED, "Le créateur ne peut pas se retirer.");
1888
+ await this.assertSettled(group2, seat);
1889
+ await members().update({ where: { id: seat.id }, data: { leftAt: /* @__PURE__ */ new Date() } });
1890
+ await svc("audit").log({
1891
+ group: group2,
1892
+ actor: me.person,
1893
+ action: EVENT.MEMBER_REMOVED,
1894
+ targetId: seat.documentId
1895
+ });
1896
+ },
1897
+ /** Someone leaves by themselves. The owner cannot: the group would have nobody to run it. */
1898
+ async leave({ group: group2, me }) {
1899
+ if (me.role === ROLE.OWNER)
1900
+ throw forbidden(ERROR_CODES.NOT_ALLOWED, "Le créateur ne peut pas quitter le groupe.");
1901
+ await this.assertSettled(group2, me);
1902
+ await members().update({ where: { id: me.id }, data: { leftAt: /* @__PURE__ */ new Date() } });
1903
+ await svc("audit").log({
1904
+ group: group2,
1905
+ actor: me.person,
1906
+ action: EVENT.MEMBER_LEFT,
1907
+ targetId: me.documentId
1908
+ });
1909
+ },
1910
+ /** Is this seat held by this person? */
1911
+ isHeldBy(seat, person2) {
1912
+ return idOf(seat.person) === person2.id;
1913
+ }
1914
+ };
1915
+ };
1916
+ const invalid = (message, details) => unprocessable(ERROR_CODES.SPLIT_INVALID, message, details);
1917
+ const sharesByWeight = (amount, weights) => {
1918
+ const total = weights.reduce((sum, w) => sum + w, 0);
1919
+ if (total === 0) return weights.map(() => 0);
1920
+ const shares = weights.map((w) => Math.floor(amount * w / total));
1921
+ let leftover = amount - shares.reduce((sum, s) => sum + s, 0);
1922
+ return shares.map((share2, i) => {
1923
+ const extra = weights[i] > 0 && leftover > 0 ? 1 : 0;
1924
+ leftover -= extra;
1925
+ return share2 + extra;
1926
+ });
1927
+ };
1928
+ const isCount = (n) => Number.isInteger(n) && n >= 0;
1929
+ const weightOf = (part, mode) => {
1930
+ if (mode === SPLIT_MODE.EQUAL) return 1;
1931
+ if (!isCount(part.weight) || part.weight > MAX_WEIGHT)
1932
+ throw invalid(`Chaque part est un entier entre 0 et ${MAX_WEIGHT}.`);
1933
+ return part.weight;
1934
+ };
1935
+ const freeShares = (amount, parts) => {
1936
+ if (!parts.every((p) => isCount(p.amount)))
1937
+ throw invalid("Chaque montant est un entier positif.");
1938
+ const sum = parts.reduce((total, p) => total + p.amount, 0);
1939
+ if (sum !== amount)
1940
+ throw invalid("La somme des parts ne correspond pas au montant.", { amount, sum });
1941
+ return parts.map((p) => p.amount);
1942
+ };
1943
+ const resolveShares = ({ amount, mode, parts }) => {
1944
+ if (!Object.values(SPLIT_MODE).includes(mode)) throw invalid("Mode de partage inconnu.");
1945
+ if (!Array.isArray(parts) || parts.length === 0) throw invalid("Personne ne participe.");
1946
+ if (new Set(parts.map((p) => String(p.member))).size !== parts.length)
1947
+ throw invalid("Un membre apparaît deux fois.");
1948
+ const weights = mode === SPLIT_MODE.FREE ? null : parts.map((p) => weightOf(p, mode));
1949
+ const amounts = weights ? sharesByWeight(amount, weights) : freeShares(amount, parts);
1950
+ const shares = parts.map((p, i) => ({ member: p.member, amount: amounts[i], weight: weights ? weights[i] : 0 })).filter((s) => s.amount > 0);
1951
+ if (shares.length === 0) throw invalid("Personne ne participe.");
1952
+ return shares;
1953
+ };
1954
+ const POPULATE$1 = {
1955
+ paidBy: { populate: { person: true } },
1956
+ addedBy: { select: ["id"] },
1957
+ shares: { populate: { member: { populate: { person: true } } } }
1958
+ };
1959
+ const isDuplicate$1 = (err) => /unique|duplicate/i.test(String(err?.message));
1960
+ const expense = ({ strapi }) => {
1961
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
1962
+ const expenses = () => strapi.db.query(UID.EXPENSE);
1963
+ const shares = () => strapi.db.query(UID.SHARE);
1964
+ return {
1965
+ /** When the expense happened: the caller's date when it is a real one and not in the future. */
1966
+ spentAt(raw) {
1967
+ const date = raw ? new Date(raw) : /* @__PURE__ */ new Date();
1968
+ return Number.isNaN(date.getTime()) || date > /* @__PURE__ */ new Date() ? /* @__PURE__ */ new Date() : date;
1969
+ },
1970
+ /**
1971
+ * What the caller sent, checked against the group's active seats.
1972
+ * @returns {{ label: string, category: string|null, amount: number, mode: string, spentAt: Date,
1973
+ * paidBy: number, shares: Array<{ member: number, amount: number, weight: number }> }}
1974
+ */
1975
+ parse(input, active) {
1976
+ const label = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
1977
+ if (!label) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
1978
+ const { maxAmount } = svc("settings").limits();
1979
+ const amount = input?.amount;
1980
+ if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
1981
+ throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
1982
+ const seatByDoc = new Map(active.map((s) => [s.documentId, s]));
1983
+ const seat = (documentId) => {
1984
+ const found = seatByDoc.get(String(documentId));
1985
+ if (!found)
1986
+ throw badRequest(ERROR_CODES.MEMBER_NOT_FOUND, "Membre introuvable dans ce groupe.");
1987
+ return found.id;
1988
+ };
1989
+ const mode = input?.mode ?? SPLIT_MODE.EQUAL;
1990
+ const parts = (Array.isArray(input?.shares) ? input.shares : []).map((p) => ({
1991
+ member: seat(p?.member),
1992
+ weight: p?.weight,
1993
+ amount: p?.amount
1994
+ }));
1995
+ return {
1996
+ label,
1997
+ category: input?.category ? String(input.category).slice(0, 40) : null,
1998
+ amount,
1999
+ mode,
2000
+ spentAt: this.spentAt(input?.spentAt),
2001
+ paidBy: seat(input?.paidBy),
2002
+ shares: resolveShares({ amount, mode, parts })
2003
+ };
2004
+ },
2005
+ async one(id) {
2006
+ return expenses().findOne({ where: { id }, populate: POPULATE$1 });
2007
+ },
2008
+ /** An expense already written under this reference, in this group. */
2009
+ async replayed(group2, clientRef) {
2010
+ if (!clientRef) return null;
2011
+ const found = await expenses().findOne({
2012
+ where: { clientRef, group: group2.id },
2013
+ populate: POPULATE$1
2014
+ });
2015
+ return found ?? null;
2016
+ },
2017
+ async writeShares(expenseId, list) {
2018
+ for (const s of list) {
2019
+ await shares().create({
2020
+ data: { expense: expenseId, member: s.member, amount: s.amount, weight: s.weight }
2021
+ });
2022
+ }
2023
+ },
2024
+ /**
2025
+ * @param {{ group: Object, me: Object }} seat the caller's
2026
+ * @param {Object} input `{ label, amount, mode, paidBy, shares, category?, spentAt?, clientRef? }`
2027
+ * @returns {Promise<{ expense: Object, replayed: boolean }>}
2028
+ */
2029
+ async create({ group: group2, me }, input) {
2030
+ const clientRef = input?.clientRef ? String(input.clientRef).slice(0, REF_MAX) : null;
2031
+ const earlier = await this.replayed(group2, clientRef);
2032
+ if (earlier) return { expense: earlier, replayed: true };
2033
+ const { active } = await svc("ledger").of(group2);
2034
+ const { shares: list, ...data } = this.parse(input, active);
2035
+ try {
2036
+ const created = await strapi.db.transaction(async () => {
2037
+ await svc("group").lock(group2);
2038
+ const e = await expenses().create({
2039
+ data: { ...data, group: group2.id, addedBy: me.id, clientRef }
2040
+ });
2041
+ await this.writeShares(e.id, list);
2042
+ return e;
2043
+ });
2044
+ await svc("audit").log({
2045
+ group: group2,
2046
+ actor: me.person,
2047
+ action: EVENT.EXPENSE_CREATED,
2048
+ targetId: created.documentId,
2049
+ data: { amount: data.amount }
2050
+ });
2051
+ return { expense: await this.one(created.id), replayed: false };
2052
+ } catch (err) {
2053
+ const twin = isDuplicate$1(err) ? await this.replayed(group2, clientRef) : null;
2054
+ if (!twin) throw err;
2055
+ return { expense: twin, replayed: true };
2056
+ }
2057
+ },
2058
+ /** An expense of this group the caller may change. */
2059
+ async editable({ group: group2, me }, documentId) {
2060
+ const expense2 = await expenses().findOne({
2061
+ where: { group: group2.id, documentId: String(documentId), deletedAt: { $null: true } },
2062
+ populate: POPULATE$1
2063
+ });
2064
+ if (!expense2) throw notFound(ERROR_CODES.EXPENSE_NOT_FOUND, "Dépense introuvable.");
2065
+ const mine = [idOf(expense2.paidBy), idOf(expense2.addedBy)].includes(me.id);
2066
+ if (!mine && me.role !== ROLE.OWNER)
2067
+ throw forbidden(
2068
+ ERROR_CODES.NOT_ALLOWED,
2069
+ "Seul celui qui a payé ou noté la dépense peut la modifier."
2070
+ );
2071
+ return expense2;
2072
+ },
2073
+ async update(seat, documentId, input) {
2074
+ const { group: group2, me } = seat;
2075
+ const expense2 = await this.editable(seat, documentId);
2076
+ const { active } = await svc("ledger").of(group2);
2077
+ const { shares: list, ...data } = this.parse(input, active);
2078
+ await strapi.db.transaction(async () => {
2079
+ await svc("group").lock(group2);
2080
+ await expenses().update({ where: { id: expense2.id }, data });
2081
+ await shares().deleteMany({ where: { expense: expense2.id } });
2082
+ await this.writeShares(expense2.id, list);
2083
+ });
2084
+ await svc("audit").log({
2085
+ group: group2,
2086
+ actor: me.person,
2087
+ action: EVENT.EXPENSE_UPDATED,
2088
+ targetId: expense2.documentId,
2089
+ data: { from: expense2.amount, to: data.amount }
2090
+ });
2091
+ return this.one(expense2.id);
2092
+ },
2093
+ async remove(seat, documentId) {
2094
+ const { group: group2, me } = seat;
2095
+ const expense2 = await this.editable(seat, documentId);
2096
+ await strapi.db.transaction(async () => {
2097
+ await svc("group").lock(group2);
2098
+ await expenses().update({ where: { id: expense2.id }, data: { deletedAt: /* @__PURE__ */ new Date() } });
2099
+ });
2100
+ await svc("audit").log({
2101
+ group: group2,
2102
+ actor: me.person,
2103
+ action: EVENT.EXPENSE_DELETED,
2104
+ targetId: expense2.documentId,
2105
+ data: { amount: expense2.amount }
2106
+ });
2107
+ },
2108
+ /**
2109
+ * @param {Object} group
2110
+ * @param {{ offset: number, limit: number }} page
2111
+ */
2112
+ async list(group2, page) {
2113
+ const where = { group: group2.id, deletedAt: { $null: true } };
2114
+ const [items, total] = await Promise.all([
2115
+ expenses().findMany({
2116
+ where,
2117
+ populate: POPULATE$1,
2118
+ orderBy: [{ spentAt: "desc" }, { id: "desc" }],
2119
+ offset: page.offset,
2120
+ limit: page.limit
2121
+ }),
2122
+ expenses().count({ where })
2123
+ ]);
2124
+ return { items, total };
2125
+ }
2126
+ };
2127
+ };
2128
+ const POPULATE = { from: { populate: { person: true } }, to: { populate: { person: true } } };
2129
+ const isDuplicate = (err) => /unique|duplicate/i.test(String(err?.message));
2130
+ const text = (raw, max) => raw ? String(raw).trim().slice(0, max) || null : null;
2131
+ const settlement = ({ strapi }) => {
2132
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
2133
+ const settlements = () => strapi.db.query(UID.SETTLEMENT);
2134
+ return {
2135
+ /**
2136
+ * What the caller sent, checked. The other seat is looked up in the group: the one paid
2137
+ * (`to`) when the caller pays, the one who paid (`from`) when the caller received.
2138
+ */
2139
+ async parse({ group: group2, me }, input) {
2140
+ const { maxAmount } = svc("settings").limits();
2141
+ const amount = input?.amount;
2142
+ if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
2143
+ throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
2144
+ const method = svc("settings").methods()[String(input?.method)];
2145
+ if (!method) throw badRequest(ERROR_CODES.METHOD_UNKNOWN, "Moyen de paiement inconnu.");
2146
+ const received = input?.from != null;
2147
+ if (received && input?.to != null)
2148
+ throw badRequest(ERROR_CODES.VALIDATION, "Indique qui paie ou qui reçoit, pas les deux.");
2149
+ const other = await svc("member").find(group2, received ? input.from : input?.to);
2150
+ if (other.id === me.id)
2151
+ throw badRequest(ERROR_CODES.VALIDATION, "Tu ne peux pas te régler à toi-même.");
2152
+ const [from, to] = received ? [other, me] : [me, other];
2153
+ return {
2154
+ amount,
2155
+ from,
2156
+ to,
2157
+ received,
2158
+ method: String(input.method),
2159
+ instant: received || method.instant || !to.person,
2160
+ reference: text(input?.reference, REF_MAX),
2161
+ note: text(input?.note, NOTE_MAX),
2162
+ clientRef: text(input?.clientRef, REF_MAX)
2163
+ };
2164
+ },
2165
+ /** A settlement already written under one of these references, in this group. */
2166
+ async replayed(group2, { clientRef, reference }) {
2167
+ const keys = [clientRef && { clientRef }, reference && { reference }].filter(Boolean);
2168
+ if (keys.length === 0) return null;
2169
+ const found = await settlements().findOne({
2170
+ where: { group: group2.id, $or: keys },
2171
+ populate: POPULATE
2172
+ });
2173
+ return found ?? null;
2174
+ },
2175
+ async one(id) {
2176
+ return settlements().findOne({ where: { id }, populate: POPULATE });
2177
+ },
2178
+ /** Inside the transaction: read the books behind the lock, refuse what exceeds them, write. */
2179
+ async write({ group: group2, me }, data) {
2180
+ await svc("group").lock(group2);
2181
+ const books = await svc("ledger").of(group2);
2182
+ const outstanding = books.room(data.from.id, data.to.id);
2183
+ if (data.amount > outstanding)
2184
+ throw unprocessable(
2185
+ ERROR_CODES.SETTLEMENT_EXCEEDS_DEBT,
2186
+ outstanding > 0 ? "Le montant dépasse ce qui est dû." : "Rien à régler envers ce membre.",
2187
+ { outstanding }
2188
+ );
2189
+ const now = /* @__PURE__ */ new Date();
2190
+ return settlements().create({
2191
+ data: {
2192
+ group: group2.id,
2193
+ from: data.from.id,
2194
+ to: data.to.id,
2195
+ amount: data.amount,
2196
+ method: data.method,
2197
+ status: data.instant ? SETTLEMENT_STATUS.CONFIRMED : SETTLEMENT_STATUS.PENDING,
2198
+ reference: data.reference,
2199
+ note: data.note,
2200
+ clientRef: data.clientRef,
2201
+ declaredAt: now,
2202
+ resolvedAt: data.instant ? now : null,
2203
+ resolvedBy: data.instant ? idOf(me.person) : null
2204
+ }
2205
+ });
2206
+ },
2207
+ /**
2208
+ * @param {{ group: Object, me: Object }} seat the caller's: the payer's, or the receiver's
2209
+ * @param {Object} input `{ to | from, amount, method, reference?, note?, clientRef? }`
2210
+ * @returns {Promise<{ settlement: Object, replayed: boolean }>}
2211
+ */
2212
+ async create(seat, input) {
2213
+ const data = await this.parse(seat, input);
2214
+ const earlier = await this.replayed(seat.group, data);
2215
+ if (earlier) return { settlement: earlier, replayed: true };
2216
+ try {
2217
+ const created = await strapi.db.transaction(() => this.write(seat, data));
2218
+ await svc("audit").log({
2219
+ group: seat.group,
2220
+ actor: seat.me.person,
2221
+ action: EVENT.SETTLEMENT_CREATED,
2222
+ targetId: created.documentId,
2223
+ data: {
2224
+ amount: data.amount,
2225
+ method: data.method,
2226
+ status: created.status,
2227
+ reference: data.reference,
2228
+ declaredBy: data.received ? "receiver" : "payer"
2229
+ }
2230
+ });
2231
+ return { settlement: await this.one(created.id), replayed: false };
2232
+ } catch (err) {
2233
+ const twin = isDuplicate(err) ? await this.replayed(seat.group, data) : null;
2234
+ if (!twin) throw err;
2235
+ return { settlement: twin, replayed: true };
2236
+ }
2237
+ },
2238
+ /** A pending settlement of this group. */
2239
+ async pending(group2, documentId) {
2240
+ const s = await settlements().findOne({
2241
+ where: { group: group2.id, documentId: String(documentId) },
2242
+ populate: POPULATE
2243
+ });
2244
+ if (!s) throw notFound(ERROR_CODES.SETTLEMENT_NOT_FOUND, "Règlement introuvable.");
2245
+ if (s.status !== SETTLEMENT_STATUS.PENDING)
2246
+ throw unprocessable(
2247
+ ERROR_CODES.SETTLEMENT_NOT_PENDING,
2248
+ `Ce règlement est déjà ${s.status}.`,
2249
+ { status: s.status }
2250
+ );
2251
+ return s;
2252
+ },
2253
+ /**
2254
+ * Close a pending settlement. Only the seat named by `side` may: the receiver confirms or
2255
+ * rejects, the payer cancels.
2256
+ */
2257
+ async resolve({ group: group2, me }, documentId, { status, side, action }) {
2258
+ const s = await this.pending(group2, documentId);
2259
+ if (idOf(s[side]) !== me.id)
2260
+ throw forbidden(ERROR_CODES.NOT_ALLOWED, "Ce n'est pas à toi de faire ça.");
2261
+ await strapi.db.transaction(async () => {
2262
+ await svc("group").lock(group2);
2263
+ const fresh = await settlements().findOne({ where: { id: s.id }, select: ["status"] });
2264
+ if (fresh.status !== SETTLEMENT_STATUS.PENDING)
2265
+ throw unprocessable(ERROR_CODES.SETTLEMENT_NOT_PENDING, "Règlement déjà traité.");
2266
+ await settlements().update({
2267
+ where: { id: s.id },
2268
+ data: { status, resolvedAt: /* @__PURE__ */ new Date(), resolvedBy: idOf(me.person) }
2269
+ });
2270
+ });
2271
+ await svc("audit").log({
2272
+ group: group2,
2273
+ actor: me.person,
2274
+ action,
2275
+ targetId: s.documentId,
2276
+ data: { amount: s.amount }
2277
+ });
2278
+ return this.one(s.id);
2279
+ },
2280
+ confirm(seat, documentId) {
2281
+ return this.resolve(seat, documentId, {
2282
+ status: SETTLEMENT_STATUS.CONFIRMED,
2283
+ side: "to",
2284
+ action: EVENT.SETTLEMENT_CONFIRMED
2285
+ });
2286
+ },
2287
+ reject(seat, documentId) {
2288
+ return this.resolve(seat, documentId, {
2289
+ status: SETTLEMENT_STATUS.REJECTED,
2290
+ side: "to",
2291
+ action: EVENT.SETTLEMENT_REJECTED
2292
+ });
2293
+ },
2294
+ cancel(seat, documentId) {
2295
+ return this.resolve(seat, documentId, {
2296
+ status: SETTLEMENT_STATUS.CANCELLED,
2297
+ side: "from",
2298
+ action: EVENT.SETTLEMENT_CANCELLED
2299
+ });
2300
+ },
2301
+ /**
2302
+ * @param {{ group?: number, status?: string, method?: string, reference?: string }} filters
2303
+ * @param {{ offset: number, limit: number }} page
2304
+ */
2305
+ async list(filters, page) {
2306
+ const where = {};
2307
+ if (filters.group) where.group = filters.group;
2308
+ if (filters.status) where.status = filters.status;
2309
+ if (filters.method) where.method = filters.method;
2310
+ if (filters.reference) where.reference = { $containsi: String(filters.reference).trim() };
2311
+ const [items, total] = await Promise.all([
2312
+ settlements().findMany({
2313
+ where,
2314
+ populate: { ...POPULATE, group: { select: ["documentId", "name"] } },
2315
+ orderBy: [{ declaredAt: "desc" }, { id: "desc" }],
2316
+ offset: page.offset,
2317
+ limit: page.limit
2318
+ }),
2319
+ settlements().count({ where })
2320
+ ]);
2321
+ return { items, total };
2322
+ }
2323
+ };
2324
+ };
2325
+ const ADMIN_RECENT = 50;
2326
+ const stats = ({ strapi }) => {
2327
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
2328
+ const count = (uid, where = {}) => strapi.db.query(uid).count({ where });
2329
+ const table = (uid) => strapi.db.metadata.get(uid).tableName;
2330
+ const tally = async (uid, narrow) => {
2331
+ const row = await narrow(strapi.db.connection(table(uid))).count({ count: "*" }).sum({ total: "amount" }).first();
2332
+ return { count: Number(row?.count ?? 0), total: Number(row?.total ?? 0) };
2333
+ };
2334
+ return {
2335
+ async dashboard() {
2336
+ const since = new Date(Date.now() - DASHBOARD_DAYS * DAY_MS);
2337
+ const recent = { createdAt: { $gte: since } };
2338
+ const [
2339
+ people,
2340
+ activePeople,
2341
+ newPeople,
2342
+ groups,
2343
+ archived,
2344
+ newGroups,
2345
+ expenses,
2346
+ weekExpenses,
2347
+ confirmed,
2348
+ pending,
2349
+ byMethod
2350
+ ] = await Promise.all([
2351
+ count(UID.PERSON),
2352
+ count(UID.PERSON, { lastActiveAt: { $gte: since } }),
2353
+ count(UID.PERSON, recent),
2354
+ count(UID.GROUP),
2355
+ count(UID.GROUP, { archivedAt: { $notNull: true } }),
2356
+ count(UID.GROUP, recent),
2357
+ tally(UID.EXPENSE, (q) => q.whereNull("deleted_at")),
2358
+ tally(UID.EXPENSE, (q) => q.whereNull("deleted_at").where("spent_at", ">=", since)),
2359
+ tally(UID.SETTLEMENT, (q) => q.where({ status: SETTLEMENT_STATUS.CONFIRMED })),
2360
+ tally(UID.SETTLEMENT, (q) => q.where({ status: SETTLEMENT_STATUS.PENDING })),
2361
+ strapi.db.connection(table(UID.SETTLEMENT)).where({ status: SETTLEMENT_STATUS.CONFIRMED }).groupBy("method").select("method").count({ count: "*" }).sum({ total: "amount" })
2362
+ ]);
2363
+ return {
2364
+ days: DASHBOARD_DAYS,
2365
+ people: { total: people, active: activePeople, new: newPeople },
2366
+ groups: { total: groups, archived, new: newGroups },
2367
+ expenses: { ...expenses, recent: weekExpenses },
2368
+ settlements: {
2369
+ confirmed,
2370
+ pending,
2371
+ byMethod: byMethod.map((m) => ({
2372
+ method: m.method,
2373
+ count: Number(m.count),
2374
+ total: Number(m.total ?? 0)
2375
+ }))
2376
+ }
2377
+ };
2378
+ },
2379
+ /** One group with its books, for support: phones masked. */
2380
+ async group(documentId) {
2381
+ const format2 = svc("format");
2382
+ const group2 = await svc("group").byDocumentId(documentId);
2383
+ const page = { offset: 0, limit: ADMIN_RECENT };
2384
+ const [books, expenses, settlements] = await Promise.all([
2385
+ svc("ledger").of(group2),
2386
+ svc("expense").list(group2, page),
2387
+ svc("settlement").list({ group: group2.id }, page)
2388
+ ]);
2389
+ return {
2390
+ ...format2.group(group2),
2391
+ createdAt: group2.createdAt,
2392
+ memberCount: books.active.length,
2393
+ expenseCount: books.expenseCount,
2394
+ total: books.total,
2395
+ members: books.seats.map((s) => ({
2396
+ ...format2.adminMember(s),
2397
+ balance: books.balanceOf(s.id)
2398
+ })),
2399
+ payments: books.payments.map((p) => ({
2400
+ from: format2.member(books.seatById.get(p.from)),
2401
+ to: format2.member(books.seatById.get(p.to)),
2402
+ amount: p.amount
2403
+ })),
2404
+ expenses: expenses.items.map((e) => format2.expense(e, NOBODY, null)),
2405
+ settlements: settlements.items.map((s) => format2.settlement(s, NOBODY, null))
2406
+ };
2407
+ },
2408
+ /** The groups a person sits in. */
2409
+ async groupsOf(person2) {
2410
+ const seats = await strapi.db.query(UID.MEMBER).findMany({
2411
+ where: { person: person2.id },
2412
+ populate: { group: true },
2413
+ orderBy: { id: "desc" }
2414
+ });
2415
+ return seats.filter((s) => s.group).map((s) => ({
2416
+ ...svc("format").group(s.group),
2417
+ role: s.role,
2418
+ hasLeft: Boolean(s.leftAt)
2419
+ }));
2420
+ }
2421
+ };
2422
+ };
2423
+ const services = {
2424
+ settings,
2425
+ audit,
2426
+ format,
2427
+ person,
2428
+ ledger,
2429
+ group,
2430
+ member,
2431
+ expense,
2432
+ settlement,
2433
+ view,
2434
+ stats
2435
+ };
2436
+ const index = {
2437
+ register,
2438
+ bootstrap,
2439
+ config,
2440
+ controllers,
2441
+ contentTypes,
2442
+ middlewares,
2443
+ policies,
2444
+ routes,
2445
+ services
2446
+ };
2447
+ module.exports = index;