@sonatel-os/strapi-plugin-split 0.0.0-stage → 0.1.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.
- package/README.md +131 -2
- package/dist/_chunks/App-8QwzQSyg.mjs +937 -0
- package/dist/_chunks/App-CLfoPnvq.js +937 -0
- package/dist/_chunks/SettingsPage-B746YfAA.js +101 -0
- package/dist/_chunks/SettingsPage-CH92IYGk.mjs +101 -0
- package/dist/_chunks/api-BCYZ56eI.mjs +466 -0
- package/dist/_chunks/api-cwZGoKZx.js +465 -0
- package/dist/_chunks/en-2Jxpmk_V.js +13 -0
- package/dist/_chunks/en-BB-FKqG6.mjs +13 -0
- package/dist/_chunks/fr-CKuK9t8l.mjs +13 -0
- package/dist/_chunks/fr-FgrMO3p9.js +13 -0
- package/dist/_chunks/index-PFbwTznf.mjs +98 -0
- package/dist/_chunks/index-oyRhs5fN.js +97 -0
- package/dist/admin/index.js +3 -0
- package/dist/admin/index.mjs +4 -0
- package/dist/server/index.js +2434 -0
- package/dist/server/index.mjs +2435 -0
- package/package.json +81 -4
|
@@ -0,0 +1,2434 @@
|
|
|
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
|
+
pending: svc("ledger").pendingBetween(books, p.from, me.id)
|
|
913
|
+
}));
|
|
914
|
+
},
|
|
915
|
+
/** Everyone who is in the group or still has something on the books. */
|
|
916
|
+
balances(books, viewer) {
|
|
917
|
+
const format2 = svc("format");
|
|
918
|
+
return books.seats.filter((s) => !s.leftAt || books.balanceOf(s.id) !== 0).map((s) => ({ member: format2.member(s, viewer), amount: books.balanceOf(s.id) }));
|
|
919
|
+
},
|
|
920
|
+
/** One group, as its first screen shows it. */
|
|
921
|
+
async group({ group: group2, me }, viewer) {
|
|
922
|
+
const format2 = svc("format");
|
|
923
|
+
const [books, recent] = await Promise.all([
|
|
924
|
+
svc("ledger").of(group2),
|
|
925
|
+
svc("expense").list(group2, { offset: 0, limit: GROUP_RECENT_EXPENSES })
|
|
926
|
+
]);
|
|
927
|
+
return {
|
|
928
|
+
...format2.group(group2),
|
|
929
|
+
role: me.role,
|
|
930
|
+
you: format2.member(me, viewer),
|
|
931
|
+
balance: books.balanceOf(me.id),
|
|
932
|
+
memberCount: books.active.length,
|
|
933
|
+
expenseCount: books.expenseCount,
|
|
934
|
+
total: books.total,
|
|
935
|
+
members: books.active.map((s) => format2.member(s, viewer)),
|
|
936
|
+
balances: this.balances(books, viewer),
|
|
937
|
+
debts: this.debts(books, me, viewer),
|
|
938
|
+
credits: this.credits(books, me, viewer),
|
|
939
|
+
expenses: recent.items.map((e) => format2.expense(e, me, viewer))
|
|
940
|
+
};
|
|
941
|
+
},
|
|
942
|
+
/** The home screen: every group at a glance, what to pay first, who owes the viewer. */
|
|
943
|
+
async overview(viewer) {
|
|
944
|
+
const format2 = svc("format");
|
|
945
|
+
const seats = await svc("group").seatsOf(viewer);
|
|
946
|
+
const perGroup = await Promise.all(
|
|
947
|
+
seats.map(async (me) => {
|
|
948
|
+
const books = await svc("ledger").of(me.group);
|
|
949
|
+
const tag = { id: me.group.documentId, name: me.group.name };
|
|
950
|
+
return {
|
|
951
|
+
summary: {
|
|
952
|
+
...format2.group(me.group),
|
|
953
|
+
role: me.role,
|
|
954
|
+
memberCount: books.active.length,
|
|
955
|
+
balance: books.balanceOf(me.id)
|
|
956
|
+
},
|
|
957
|
+
debts: this.debts(books, me, viewer).map((d) => ({ ...d, group: tag })),
|
|
958
|
+
credits: this.credits(books, me, viewer).map((c) => ({ ...c, group: tag }))
|
|
959
|
+
};
|
|
960
|
+
})
|
|
961
|
+
);
|
|
962
|
+
const debts = perGroup.flatMap((g) => g.debts).sort((a, b) => b.amount - a.amount);
|
|
963
|
+
const credits = perGroup.flatMap((g) => g.credits).sort((a, b) => b.amount - a.amount);
|
|
964
|
+
const sum = (list) => list.reduce((total, item) => total + item.amount, 0);
|
|
965
|
+
return {
|
|
966
|
+
owe: sum(debts),
|
|
967
|
+
owed: sum(credits),
|
|
968
|
+
debts,
|
|
969
|
+
credits,
|
|
970
|
+
groups: perGroup.map((g) => g.summary).sort((a, b) => new Date(b.lastActivityAt ?? 0) - new Date(a.lastActivityAt ?? 0))
|
|
971
|
+
};
|
|
972
|
+
},
|
|
973
|
+
/** The settle screens of one group: what to pay, what is awaited, how, and what happened. */
|
|
974
|
+
async settlements({ group: group2, me }, viewer, page) {
|
|
975
|
+
const format2 = svc("format");
|
|
976
|
+
const [books, history] = await Promise.all([
|
|
977
|
+
svc("ledger").of(group2),
|
|
978
|
+
svc("settlement").list({ group: group2.id }, page)
|
|
979
|
+
]);
|
|
980
|
+
return {
|
|
981
|
+
debts: this.debts(books, me, viewer),
|
|
982
|
+
credits: this.credits(books, me, viewer),
|
|
983
|
+
methods: Object.entries(svc("settings").methods()).map(([key, m]) => ({ key, ...m })),
|
|
984
|
+
history: history.items.map((s) => format2.settlement(s, me, viewer)),
|
|
985
|
+
total: history.total
|
|
986
|
+
};
|
|
987
|
+
},
|
|
988
|
+
/**
|
|
989
|
+
* Expenses and settlements across the viewer's groups, newest first.
|
|
990
|
+
* @param {Object} viewer
|
|
991
|
+
* @param {{ offset: number, limit: number }} page
|
|
992
|
+
* @returns {Promise<{ items: Object[], total: number }>}
|
|
993
|
+
*/
|
|
994
|
+
async activity(viewer, page) {
|
|
995
|
+
const format2 = svc("format");
|
|
996
|
+
const seats = await svc("group").seatsOf(viewer);
|
|
997
|
+
if (seats.length === 0) return { items: [], total: 0 };
|
|
998
|
+
const seatByGroup = new Map(seats.map((s) => [s.group.id, s]));
|
|
999
|
+
const inGroups = { group: { id: { $in: [...seatByGroup.keys()] } } };
|
|
1000
|
+
const upTo = page.offset + page.limit;
|
|
1001
|
+
const expenseWhere = { ...inGroups, deletedAt: { $null: true } };
|
|
1002
|
+
const [expenses, settlements, expenseTotal, settlementTotal] = await Promise.all([
|
|
1003
|
+
strapi.db.query(UID.EXPENSE).findMany({
|
|
1004
|
+
where: expenseWhere,
|
|
1005
|
+
populate: EXPENSE_POPULATE,
|
|
1006
|
+
orderBy: { spentAt: "desc" },
|
|
1007
|
+
limit: upTo
|
|
1008
|
+
}),
|
|
1009
|
+
strapi.db.query(UID.SETTLEMENT).findMany({
|
|
1010
|
+
where: inGroups,
|
|
1011
|
+
populate: SETTLEMENT_POPULATE,
|
|
1012
|
+
orderBy: { declaredAt: "desc" },
|
|
1013
|
+
limit: upTo
|
|
1014
|
+
}),
|
|
1015
|
+
strapi.db.query(UID.EXPENSE).count({ where: expenseWhere }),
|
|
1016
|
+
strapi.db.query(UID.SETTLEMENT).count({ where: inGroups })
|
|
1017
|
+
]);
|
|
1018
|
+
const tag = (g) => ({ id: g.documentId, name: g.name });
|
|
1019
|
+
const items = [
|
|
1020
|
+
...expenses.map((e) => ({
|
|
1021
|
+
type: "expense",
|
|
1022
|
+
at: e.spentAt,
|
|
1023
|
+
group: tag(e.group),
|
|
1024
|
+
...format2.expense(e, seatByGroup.get(e.group.id), viewer)
|
|
1025
|
+
})),
|
|
1026
|
+
...settlements.map((s) => ({
|
|
1027
|
+
type: "settlement",
|
|
1028
|
+
at: s.declaredAt,
|
|
1029
|
+
group: tag(s.group),
|
|
1030
|
+
...format2.settlement(s, seatByGroup.get(s.group.id), viewer)
|
|
1031
|
+
}))
|
|
1032
|
+
].sort(byDateDesc).slice(page.offset, upTo).map((item) => ({ ...item, at: new Date(item.at).toISOString() }));
|
|
1033
|
+
return { items, total: expenseTotal + settlementTotal };
|
|
1034
|
+
}
|
|
1035
|
+
};
|
|
1036
|
+
};
|
|
1037
|
+
const flag = (value) => value === "true" ? true : value === "false" ? false : void 0;
|
|
1038
|
+
const admin$1 = ({ strapi }) => {
|
|
1039
|
+
const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
|
|
1040
|
+
const adminPerson = (p) => ({
|
|
1041
|
+
id: p.documentId,
|
|
1042
|
+
displayName: p.displayName ?? null,
|
|
1043
|
+
phone: maskPhone(p.phone),
|
|
1044
|
+
isActive: p.isActive,
|
|
1045
|
+
lastActiveAt: p.lastActiveAt ?? null,
|
|
1046
|
+
createdAt: p.createdAt ?? null
|
|
1047
|
+
});
|
|
1048
|
+
return {
|
|
1049
|
+
dashboard: handle(strapi, async (ctx) => ok(ctx, await svc("stats").dashboard())),
|
|
1050
|
+
// ── Groups ───────────────────────────────────────────────────────────
|
|
1051
|
+
groups: handle(strapi, async (ctx) => {
|
|
1052
|
+
const page = parsePagination(ctx.query);
|
|
1053
|
+
const filters = { q: ctx.query.q, archived: flag(ctx.query.archived) };
|
|
1054
|
+
const { items, total } = await svc("group").search(filters, page);
|
|
1055
|
+
ctx.body = paged(
|
|
1056
|
+
items.map((g) => svc("format").group(g)),
|
|
1057
|
+
total,
|
|
1058
|
+
page
|
|
1059
|
+
);
|
|
1060
|
+
}),
|
|
1061
|
+
group: handle(strapi, async (ctx) => ok(ctx, await svc("stats").group(ctx.params.id))),
|
|
1062
|
+
archiveGroup: handle(strapi, async (ctx) => {
|
|
1063
|
+
const group2 = await svc("group").byDocumentId(ctx.params.id);
|
|
1064
|
+
ok(ctx, svc("format").group(await svc("group").archive(group2, null)));
|
|
1065
|
+
}),
|
|
1066
|
+
// ── People ───────────────────────────────────────────────────────────
|
|
1067
|
+
people: handle(strapi, async (ctx) => {
|
|
1068
|
+
const page = parsePagination(ctx.query);
|
|
1069
|
+
const filters = { q: ctx.query.q, isActive: flag(ctx.query.active) };
|
|
1070
|
+
const { items, total } = await svc("person").search(filters, page);
|
|
1071
|
+
ctx.body = paged(items.map(adminPerson), total, page);
|
|
1072
|
+
}),
|
|
1073
|
+
person: handle(strapi, async (ctx) => {
|
|
1074
|
+
const person2 = await svc("person").byDocumentId(ctx.params.id);
|
|
1075
|
+
ok(ctx, { ...adminPerson(person2), groups: await svc("stats").groupsOf(person2) });
|
|
1076
|
+
}),
|
|
1077
|
+
personPhone: handle(strapi, async (ctx) => {
|
|
1078
|
+
const person2 = await svc("person").byDocumentId(ctx.params.id);
|
|
1079
|
+
strapi.log.info(
|
|
1080
|
+
`[split] phone of ${person2.documentId} revealed to admin ${ctx.state.user?.id}`
|
|
1081
|
+
);
|
|
1082
|
+
ok(ctx, { phone: person2.phone ?? null });
|
|
1083
|
+
}),
|
|
1084
|
+
setPersonActive: handle(strapi, async (ctx) => {
|
|
1085
|
+
ok(ctx, adminPerson(await svc("person").setActive(ctx.params.id, body(ctx).isActive)));
|
|
1086
|
+
}),
|
|
1087
|
+
// ── Settlements & audit ──────────────────────────────────────────────
|
|
1088
|
+
settlements: handle(strapi, async (ctx) => {
|
|
1089
|
+
const page = parsePagination(ctx.query);
|
|
1090
|
+
const { status, method, reference } = ctx.query;
|
|
1091
|
+
const { items, total } = await svc("settlement").list({ status, method, reference }, page);
|
|
1092
|
+
const rows = items.map((s) => ({
|
|
1093
|
+
...svc("format").settlement(s, NOBODY, null),
|
|
1094
|
+
group: s.group ? { id: s.group.documentId, name: s.group.name } : null
|
|
1095
|
+
}));
|
|
1096
|
+
ctx.body = paged(rows, total, page);
|
|
1097
|
+
}),
|
|
1098
|
+
events: handle(strapi, async (ctx) => {
|
|
1099
|
+
const page = parsePagination(ctx.query);
|
|
1100
|
+
const group2 = ctx.query.group ? await svc("group").byDocumentId(ctx.query.group) : null;
|
|
1101
|
+
const { items, total } = await svc("audit").list(
|
|
1102
|
+
{ group: group2?.id, action: ctx.query.action },
|
|
1103
|
+
page
|
|
1104
|
+
);
|
|
1105
|
+
const rows = items.map((e) => ({
|
|
1106
|
+
id: e.documentId,
|
|
1107
|
+
action: e.action,
|
|
1108
|
+
at: e.at,
|
|
1109
|
+
targetId: e.targetId ?? null,
|
|
1110
|
+
data: e.data ?? null,
|
|
1111
|
+
group: e.group ? { id: e.group.documentId, name: e.group.name } : null,
|
|
1112
|
+
actor: e.actor ? { id: e.actor.documentId, displayName: e.actor.displayName } : null
|
|
1113
|
+
}));
|
|
1114
|
+
ctx.body = paged(rows, total, page);
|
|
1115
|
+
}),
|
|
1116
|
+
settings: handle(strapi, async (ctx) => {
|
|
1117
|
+
const settings2 = svc("settings");
|
|
1118
|
+
ok(ctx, {
|
|
1119
|
+
inviteCodePrefix: settings2.inviteCodePrefix(),
|
|
1120
|
+
countryCode: settings2.countryCode(),
|
|
1121
|
+
people: settings2.people(),
|
|
1122
|
+
methods: settings2.methods(),
|
|
1123
|
+
limits: settings2.limits()
|
|
1124
|
+
});
|
|
1125
|
+
})
|
|
1126
|
+
};
|
|
1127
|
+
};
|
|
1128
|
+
const controllers = { app, admin: admin$1 };
|
|
1129
|
+
const header = (ctx, name) => {
|
|
1130
|
+
const value = ctx.request.header[String(name).toLowerCase()];
|
|
1131
|
+
if (typeof value !== "string") return "";
|
|
1132
|
+
try {
|
|
1133
|
+
return decodeURIComponent(value).trim();
|
|
1134
|
+
} catch {
|
|
1135
|
+
return value.trim();
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
const person$1 = (_config, { strapi }) => async (ctx, next) => {
|
|
1139
|
+
try {
|
|
1140
|
+
const plugin = strapi.plugin(PLUGIN_ID);
|
|
1141
|
+
const cfg = plugin.service("settings").people();
|
|
1142
|
+
const externalId = header(ctx, cfg.idHeader).slice(0, REF_MAX);
|
|
1143
|
+
if (!externalId) {
|
|
1144
|
+
throw badRequest(
|
|
1145
|
+
ERROR_CODES.PERSON_REQUIRED,
|
|
1146
|
+
`En-tête ${cfg.idHeader} requis : l'identifiant de la personne.`
|
|
1147
|
+
);
|
|
1148
|
+
}
|
|
1149
|
+
const found = await plugin.service("person").resolve({
|
|
1150
|
+
externalId,
|
|
1151
|
+
displayName: header(ctx, cfg.nameHeader) || null,
|
|
1152
|
+
autoProvision: cfg.autoProvision
|
|
1153
|
+
});
|
|
1154
|
+
if (!found.isActive) throw forbidden(ERROR_CODES.PERSON_INACTIVE, "Ce compte est désactivé.");
|
|
1155
|
+
ctx.state.splitPerson = found;
|
|
1156
|
+
ctx.state.splitPersonIsNew = Boolean(found.__created);
|
|
1157
|
+
ctx.set("Cache-Control", "private, no-store");
|
|
1158
|
+
} catch (err) {
|
|
1159
|
+
sendError(ctx, err, strapi);
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
await next();
|
|
1163
|
+
};
|
|
1164
|
+
const middlewares = { person: person$1 };
|
|
1165
|
+
const policies = {};
|
|
1166
|
+
const PERSON = { middlewares: ["plugin::split.person"] };
|
|
1167
|
+
const route$1 = (method, path, handler) => ({
|
|
1168
|
+
method,
|
|
1169
|
+
path,
|
|
1170
|
+
handler: `app.${handler}`,
|
|
1171
|
+
config: PERSON
|
|
1172
|
+
});
|
|
1173
|
+
const contentApi = [
|
|
1174
|
+
// person
|
|
1175
|
+
route$1("GET", "/me", "me"),
|
|
1176
|
+
route$1("GET", "/overview", "overview"),
|
|
1177
|
+
route$1("GET", "/activity", "activity"),
|
|
1178
|
+
// groups
|
|
1179
|
+
route$1("POST", "/groups", "createGroup"),
|
|
1180
|
+
route$1("POST", "/groups/join", "joinGroup"),
|
|
1181
|
+
route$1("GET", "/groups/:group", "group"),
|
|
1182
|
+
route$1("PATCH", "/groups/:group", "renameGroup"),
|
|
1183
|
+
route$1("POST", "/groups/:group/archive", "archiveGroup"),
|
|
1184
|
+
route$1("POST", "/groups/:group/leave", "leaveGroup"),
|
|
1185
|
+
// members
|
|
1186
|
+
route$1("POST", "/groups/:group/members", "addMember"),
|
|
1187
|
+
route$1("DELETE", "/groups/:group/members/:member", "removeMember"),
|
|
1188
|
+
// expenses
|
|
1189
|
+
route$1("GET", "/groups/:group/expenses", "expenses"),
|
|
1190
|
+
route$1("POST", "/groups/:group/expenses", "createExpense"),
|
|
1191
|
+
route$1("PUT", "/groups/:group/expenses/:expense", "updateExpense"),
|
|
1192
|
+
route$1("DELETE", "/groups/:group/expenses/:expense", "deleteExpense"),
|
|
1193
|
+
// settlements
|
|
1194
|
+
route$1("GET", "/groups/:group/settlements", "settlements"),
|
|
1195
|
+
route$1("POST", "/groups/:group/settlements", "createSettlement"),
|
|
1196
|
+
route$1("POST", "/groups/:group/settlements/:settlement/confirm", "confirmSettlement"),
|
|
1197
|
+
route$1("POST", "/groups/:group/settlements/:settlement/reject", "rejectSettlement"),
|
|
1198
|
+
route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement")
|
|
1199
|
+
];
|
|
1200
|
+
const can = (...actions) => ({
|
|
1201
|
+
policies: [
|
|
1202
|
+
{
|
|
1203
|
+
name: "admin::hasPermissions",
|
|
1204
|
+
config: { actions: actions.map((a) => `plugin::split.${a}`) }
|
|
1205
|
+
}
|
|
1206
|
+
]
|
|
1207
|
+
});
|
|
1208
|
+
const route = (method, path, handler, action) => ({
|
|
1209
|
+
method,
|
|
1210
|
+
path,
|
|
1211
|
+
handler: `admin.${handler}`,
|
|
1212
|
+
config: can(action)
|
|
1213
|
+
});
|
|
1214
|
+
const admin = [
|
|
1215
|
+
route("GET", "/dashboard", "dashboard", RBAC.DASHBOARD_READ),
|
|
1216
|
+
route("GET", "/groups", "groups", RBAC.GROUPS_READ),
|
|
1217
|
+
route("GET", "/groups/:id", "group", RBAC.GROUPS_READ),
|
|
1218
|
+
route("POST", "/groups/:id/archive", "archiveGroup", RBAC.GROUPS_WRITE),
|
|
1219
|
+
route("GET", "/people", "people", RBAC.PEOPLE_READ),
|
|
1220
|
+
route("GET", "/people/:id", "person", RBAC.PEOPLE_READ),
|
|
1221
|
+
route("GET", "/people/:id/phone", "personPhone", RBAC.PEOPLE_PHONE),
|
|
1222
|
+
route("PUT", "/people/:id/active", "setPersonActive", RBAC.PEOPLE_WRITE),
|
|
1223
|
+
route("GET", "/settlements", "settlements", RBAC.SETTLEMENTS_READ),
|
|
1224
|
+
route("GET", "/events", "events", RBAC.AUDIT_READ),
|
|
1225
|
+
route("GET", "/settings", "settings", RBAC.SETTINGS_READ)
|
|
1226
|
+
];
|
|
1227
|
+
const routes = {
|
|
1228
|
+
"content-api": { type: "content-api", routes: contentApi },
|
|
1229
|
+
admin: { type: "admin", routes: admin }
|
|
1230
|
+
};
|
|
1231
|
+
const DEFAULT_PEOPLE = Object.freeze({ idHeader: "x-person-id", nameHeader: "x-person-name" });
|
|
1232
|
+
const settings = ({ strapi }) => ({
|
|
1233
|
+
/** @returns {Object} the full plugin config */
|
|
1234
|
+
all() {
|
|
1235
|
+
return strapi.config.get(`plugin::${PLUGIN_ID}`) ?? {};
|
|
1236
|
+
},
|
|
1237
|
+
/** How the caller names the person: header names and whether unknown ids create a person. */
|
|
1238
|
+
people() {
|
|
1239
|
+
const p = this.all().people ?? {};
|
|
1240
|
+
return {
|
|
1241
|
+
autoProvision: p.autoProvision !== false,
|
|
1242
|
+
idHeader: String(p.idHeader || DEFAULT_PEOPLE.idHeader).toLowerCase(),
|
|
1243
|
+
nameHeader: String(p.nameHeader || DEFAULT_PEOPLE.nameHeader).toLowerCase()
|
|
1244
|
+
};
|
|
1245
|
+
},
|
|
1246
|
+
inviteCodePrefix() {
|
|
1247
|
+
return this.all().inviteCodePrefix ?? DEFAULT_INVITE_PREFIX;
|
|
1248
|
+
},
|
|
1249
|
+
countryCode() {
|
|
1250
|
+
return String(this.all().countryCode ?? DEFAULT_COUNTRY_CODE);
|
|
1251
|
+
},
|
|
1252
|
+
/** @returns {Object<string, { instant: boolean }>} every way a debt can be settled */
|
|
1253
|
+
methods() {
|
|
1254
|
+
const methods = this.all().methods ?? DEFAULT_METHODS;
|
|
1255
|
+
return Object.fromEntries(
|
|
1256
|
+
Object.entries(methods).map(([name, m]) => [name, { instant: Boolean(m?.instant) }])
|
|
1257
|
+
);
|
|
1258
|
+
},
|
|
1259
|
+
limits() {
|
|
1260
|
+
return { ...DEFAULT_LIMITS, ...this.all().limits ?? {} };
|
|
1261
|
+
}
|
|
1262
|
+
});
|
|
1263
|
+
const audit = ({ strapi }) => ({
|
|
1264
|
+
/**
|
|
1265
|
+
* @param {{ group: Object, actor: Object|null, action: string, targetId?: string, data?: Object }} event
|
|
1266
|
+
*/
|
|
1267
|
+
async log({ group: group2, actor, action, targetId = null, data = null }) {
|
|
1268
|
+
try {
|
|
1269
|
+
await strapi.db.query(UID.EVENT).create({
|
|
1270
|
+
data: { group: group2.id, actor: actor?.id ?? null, action, targetId, data, at: /* @__PURE__ */ new Date() }
|
|
1271
|
+
});
|
|
1272
|
+
} catch (err) {
|
|
1273
|
+
strapi.log.warn(`${LOG_PREFIX} audit ${action}: ${err.message}`);
|
|
1274
|
+
}
|
|
1275
|
+
},
|
|
1276
|
+
/**
|
|
1277
|
+
* @param {{ group?: number, action?: string }} filters
|
|
1278
|
+
* @param {{ offset: number, limit: number }} page
|
|
1279
|
+
*/
|
|
1280
|
+
async list(filters, page) {
|
|
1281
|
+
const where = {};
|
|
1282
|
+
if (filters.group) where.group = filters.group;
|
|
1283
|
+
if (filters.action) where.action = filters.action;
|
|
1284
|
+
const [items, total] = await Promise.all([
|
|
1285
|
+
strapi.db.query(UID.EVENT).findMany({
|
|
1286
|
+
where,
|
|
1287
|
+
populate: {
|
|
1288
|
+
group: { select: ["documentId", "name"] },
|
|
1289
|
+
actor: { select: ["documentId", "displayName"] }
|
|
1290
|
+
},
|
|
1291
|
+
orderBy: { at: "desc" },
|
|
1292
|
+
offset: page.offset,
|
|
1293
|
+
limit: page.limit
|
|
1294
|
+
}),
|
|
1295
|
+
strapi.db.query(UID.EVENT).count({ where })
|
|
1296
|
+
]);
|
|
1297
|
+
return { items, total };
|
|
1298
|
+
}
|
|
1299
|
+
});
|
|
1300
|
+
const iso = (date) => date ? new Date(date).toISOString() : null;
|
|
1301
|
+
const format = () => ({
|
|
1302
|
+
person(p, isNew = false) {
|
|
1303
|
+
return { id: p.documentId, displayName: p.displayName ?? null, phone: p.phone ?? null, isNew };
|
|
1304
|
+
},
|
|
1305
|
+
/** The name a seat goes by: the person's own once they have one, the name it was added under otherwise. */
|
|
1306
|
+
nameOf(member2) {
|
|
1307
|
+
return member2.person?.displayName || member2.displayName;
|
|
1308
|
+
},
|
|
1309
|
+
/** The number money for this seat goes to. */
|
|
1310
|
+
phoneOf(member2) {
|
|
1311
|
+
return member2.person?.phone ?? member2.phone ?? null;
|
|
1312
|
+
},
|
|
1313
|
+
/**
|
|
1314
|
+
* @param {Object} m member row, `person` populated
|
|
1315
|
+
* @param {Object|null} viewer the person asking
|
|
1316
|
+
*/
|
|
1317
|
+
member(m, viewer = null) {
|
|
1318
|
+
return {
|
|
1319
|
+
id: m.documentId,
|
|
1320
|
+
displayName: this.nameOf(m),
|
|
1321
|
+
isYou: Boolean(viewer) && idOf(m.person) === viewer.id,
|
|
1322
|
+
isRegistered: Boolean(m.person),
|
|
1323
|
+
role: m.role,
|
|
1324
|
+
hasLeft: Boolean(m.leftAt)
|
|
1325
|
+
};
|
|
1326
|
+
},
|
|
1327
|
+
/** A seat as an administrator sees it: the phone masked. */
|
|
1328
|
+
adminMember(m) {
|
|
1329
|
+
return { ...this.member(m), phone: maskPhone(this.phoneOf(m)), joinedAt: iso(m.joinedAt) };
|
|
1330
|
+
},
|
|
1331
|
+
group(g) {
|
|
1332
|
+
return {
|
|
1333
|
+
id: g.documentId,
|
|
1334
|
+
name: g.name,
|
|
1335
|
+
inviteCode: g.inviteCode,
|
|
1336
|
+
isArchived: Boolean(g.archivedAt),
|
|
1337
|
+
lastActivityAt: iso(g.lastActivityAt)
|
|
1338
|
+
};
|
|
1339
|
+
},
|
|
1340
|
+
/**
|
|
1341
|
+
* @param {Object} e expense row, `paidBy`, `addedBy` and `shares.member` populated with people
|
|
1342
|
+
* @param {Object} me the viewer's seat
|
|
1343
|
+
* @param {Object} viewer the person asking
|
|
1344
|
+
*/
|
|
1345
|
+
expense(e, me, viewer) {
|
|
1346
|
+
const shares = (e.shares ?? []).map((s) => ({
|
|
1347
|
+
member: this.member(s.member, viewer),
|
|
1348
|
+
amount: s.amount,
|
|
1349
|
+
weight: s.weight ?? 0
|
|
1350
|
+
}));
|
|
1351
|
+
const mine = (e.shares ?? []).find((s) => idOf(s.member) === me.id);
|
|
1352
|
+
const canEdit = Boolean(me.id) && (me.role === ROLE.OWNER || [idOf(e.paidBy), idOf(e.addedBy)].includes(me.id));
|
|
1353
|
+
return {
|
|
1354
|
+
id: e.documentId,
|
|
1355
|
+
label: e.label,
|
|
1356
|
+
category: e.category ?? null,
|
|
1357
|
+
amount: e.amount,
|
|
1358
|
+
mode: e.mode,
|
|
1359
|
+
spentAt: iso(e.spentAt),
|
|
1360
|
+
paidBy: this.member(e.paidBy, viewer),
|
|
1361
|
+
yourShare: mine ? mine.amount : 0,
|
|
1362
|
+
shares,
|
|
1363
|
+
canEdit
|
|
1364
|
+
};
|
|
1365
|
+
},
|
|
1366
|
+
/**
|
|
1367
|
+
* @param {Object} s settlement row, `from` and `to` populated with people
|
|
1368
|
+
* @param {Object} me the viewer's seat
|
|
1369
|
+
* @param {Object} viewer the person asking
|
|
1370
|
+
*/
|
|
1371
|
+
settlement(s, me, viewer) {
|
|
1372
|
+
const pending = s.status === SETTLEMENT_STATUS.PENDING;
|
|
1373
|
+
return {
|
|
1374
|
+
id: s.documentId,
|
|
1375
|
+
from: this.member(s.from, viewer),
|
|
1376
|
+
to: this.member(s.to, viewer),
|
|
1377
|
+
amount: s.amount,
|
|
1378
|
+
method: s.method,
|
|
1379
|
+
status: s.status,
|
|
1380
|
+
reference: s.reference ?? null,
|
|
1381
|
+
note: s.note ?? null,
|
|
1382
|
+
declaredAt: iso(s.declaredAt),
|
|
1383
|
+
resolvedAt: iso(s.resolvedAt),
|
|
1384
|
+
canConfirm: pending && idOf(s.to) === me.id,
|
|
1385
|
+
canCancel: pending && idOf(s.from) === me.id
|
|
1386
|
+
};
|
|
1387
|
+
}
|
|
1388
|
+
});
|
|
1389
|
+
const ACTIVITY_STAMP_MS = 5 * 60 * 1e3;
|
|
1390
|
+
const isDuplicate$2 = (err) => /unique|duplicate/i.test(String(err?.message));
|
|
1391
|
+
const person = ({ strapi }) => ({
|
|
1392
|
+
/** The stored spelling of an id: a phone number has one spelling, anything else is kept as sent. */
|
|
1393
|
+
canonical(externalId) {
|
|
1394
|
+
const raw = String(externalId).trim();
|
|
1395
|
+
const country = strapi.plugin(PLUGIN_ID).service("settings").countryCode();
|
|
1396
|
+
const phone = normalizePhone(raw, country);
|
|
1397
|
+
return { externalId: phone ?? raw, phone };
|
|
1398
|
+
},
|
|
1399
|
+
/** What changed on a returning person, or null when nothing is worth a write. */
|
|
1400
|
+
refresh(existing, displayName, now) {
|
|
1401
|
+
const patch = {};
|
|
1402
|
+
const name = displayName ? displayName.slice(0, NAME_MAX) : null;
|
|
1403
|
+
if (name && name !== existing.displayName) patch.displayName = name;
|
|
1404
|
+
const seen = existing.lastActiveAt ? new Date(existing.lastActiveAt).getTime() : 0;
|
|
1405
|
+
if (now.getTime() - seen > ACTIVITY_STAMP_MS) patch.lastActiveAt = now;
|
|
1406
|
+
return Object.keys(patch).length ? patch : null;
|
|
1407
|
+
},
|
|
1408
|
+
/**
|
|
1409
|
+
* The person behind an external id, created on first sight when `autoProvision` is on.
|
|
1410
|
+
* @param {{ externalId: string, displayName?: string|null, autoProvision?: boolean }} p
|
|
1411
|
+
* @returns {Promise<Object>} the person row (`__created` is true when it was just provisioned)
|
|
1412
|
+
*/
|
|
1413
|
+
async resolve({ externalId, displayName = null, autoProvision = true }) {
|
|
1414
|
+
const now = /* @__PURE__ */ new Date();
|
|
1415
|
+
const id = this.canonical(externalId);
|
|
1416
|
+
const people = strapi.db.query(UID.PERSON);
|
|
1417
|
+
const existing = await people.findOne({ where: { externalId: id.externalId } });
|
|
1418
|
+
if (existing) {
|
|
1419
|
+
const patch = this.refresh(existing, displayName, now);
|
|
1420
|
+
return patch ? people.update({ where: { id: existing.id }, data: patch }) : existing;
|
|
1421
|
+
}
|
|
1422
|
+
if (!autoProvision) throw notFound(ERROR_CODES.PERSON_NOT_FOUND, "Personne inconnue.");
|
|
1423
|
+
try {
|
|
1424
|
+
const person2 = await people.create({
|
|
1425
|
+
data: {
|
|
1426
|
+
...id,
|
|
1427
|
+
displayName: displayName ? displayName.slice(0, NAME_MAX) : null,
|
|
1428
|
+
isActive: true,
|
|
1429
|
+
lastActiveAt: now
|
|
1430
|
+
}
|
|
1431
|
+
});
|
|
1432
|
+
await this.claimSeats(person2);
|
|
1433
|
+
return { ...person2, __created: true };
|
|
1434
|
+
} catch (err) {
|
|
1435
|
+
if (!isDuplicate$2(err)) throw err;
|
|
1436
|
+
return people.findOne({ where: { externalId: id.externalId } });
|
|
1437
|
+
}
|
|
1438
|
+
},
|
|
1439
|
+
/**
|
|
1440
|
+
* Seats added by phone before this person existed become theirs.
|
|
1441
|
+
* @param {Object} person
|
|
1442
|
+
* @returns {Promise<number>} seats claimed
|
|
1443
|
+
*/
|
|
1444
|
+
async claimSeats(person2) {
|
|
1445
|
+
if (!person2.phone) return 0;
|
|
1446
|
+
const seats = await strapi.db.query(UID.MEMBER).findMany({
|
|
1447
|
+
where: { phone: person2.phone, person: { id: { $null: true } }, leftAt: { $null: true } },
|
|
1448
|
+
select: ["id"]
|
|
1449
|
+
});
|
|
1450
|
+
for (const seat of seats) {
|
|
1451
|
+
await strapi.db.query(UID.MEMBER).update({ where: { id: seat.id }, data: { person: person2.id, joinedAt: /* @__PURE__ */ new Date() } });
|
|
1452
|
+
}
|
|
1453
|
+
return seats.length;
|
|
1454
|
+
},
|
|
1455
|
+
/** The registered person with this phone, if any. */
|
|
1456
|
+
async byPhone(phone) {
|
|
1457
|
+
return phone ? strapi.db.query(UID.PERSON).findOne({ where: { phone } }) : null;
|
|
1458
|
+
},
|
|
1459
|
+
async byDocumentId(documentId) {
|
|
1460
|
+
const person2 = await strapi.db.query(UID.PERSON).findOne({ where: { documentId } });
|
|
1461
|
+
if (!person2) throw notFound(ERROR_CODES.PERSON_NOT_FOUND, "Personne introuvable.");
|
|
1462
|
+
return person2;
|
|
1463
|
+
},
|
|
1464
|
+
/**
|
|
1465
|
+
* Admin search by name, phone fragment or external id.
|
|
1466
|
+
* @param {{ q?: string, isActive?: boolean }} filters
|
|
1467
|
+
* @param {{ offset: number, limit: number }} page
|
|
1468
|
+
*/
|
|
1469
|
+
async search(filters, page) {
|
|
1470
|
+
const where = {};
|
|
1471
|
+
if (filters.q) {
|
|
1472
|
+
const q = String(filters.q).trim();
|
|
1473
|
+
const digits = q.replace(/\D/g, "");
|
|
1474
|
+
where.$or = [{ displayName: { $containsi: q } }, { externalId: { $containsi: q } }];
|
|
1475
|
+
if (digits) where.$or.push({ phone: { $contains: digits } });
|
|
1476
|
+
}
|
|
1477
|
+
if (typeof filters.isActive === "boolean") where.isActive = filters.isActive;
|
|
1478
|
+
const [items, total] = await Promise.all([
|
|
1479
|
+
strapi.db.query(UID.PERSON).findMany({
|
|
1480
|
+
where,
|
|
1481
|
+
orderBy: { lastActiveAt: "desc" },
|
|
1482
|
+
offset: page.offset,
|
|
1483
|
+
limit: page.limit
|
|
1484
|
+
}),
|
|
1485
|
+
strapi.db.query(UID.PERSON).count({ where })
|
|
1486
|
+
]);
|
|
1487
|
+
return { items, total };
|
|
1488
|
+
},
|
|
1489
|
+
async setActive(documentId, isActive) {
|
|
1490
|
+
const person2 = await this.byDocumentId(documentId);
|
|
1491
|
+
return strapi.db.query(UID.PERSON).update({ where: { id: person2.id }, data: { isActive: Boolean(isActive) } });
|
|
1492
|
+
}
|
|
1493
|
+
});
|
|
1494
|
+
const add = (map, key, delta) => map.set(key, (map.get(key) ?? 0) + delta);
|
|
1495
|
+
const computeBalances = ({ expenses, settlements }) => {
|
|
1496
|
+
const balances = /* @__PURE__ */ new Map();
|
|
1497
|
+
for (const expense2 of expenses) {
|
|
1498
|
+
add(balances, expense2.paidBy, expense2.amount);
|
|
1499
|
+
for (const share2 of expense2.shares) add(balances, share2.member, -share2.amount);
|
|
1500
|
+
}
|
|
1501
|
+
for (const s of settlements) {
|
|
1502
|
+
if (s.status !== SETTLEMENT_STATUS.CONFIRMED) continue;
|
|
1503
|
+
add(balances, s.from, s.amount);
|
|
1504
|
+
add(balances, s.to, -s.amount);
|
|
1505
|
+
}
|
|
1506
|
+
return balances;
|
|
1507
|
+
};
|
|
1508
|
+
const bySize = (a, b) => b.amount - a.amount || String(a.member).localeCompare(String(b.member));
|
|
1509
|
+
const suggestPayments = (balances) => {
|
|
1510
|
+
const creditors = [];
|
|
1511
|
+
const debtors = [];
|
|
1512
|
+
for (const [member2, balance] of balances) {
|
|
1513
|
+
if (balance > 0) creditors.push({ member: member2, amount: balance });
|
|
1514
|
+
if (balance < 0) debtors.push({ member: member2, amount: -balance });
|
|
1515
|
+
}
|
|
1516
|
+
creditors.sort(bySize);
|
|
1517
|
+
debtors.sort(bySize);
|
|
1518
|
+
const payments = [];
|
|
1519
|
+
let c = 0;
|
|
1520
|
+
let d = 0;
|
|
1521
|
+
while (c < creditors.length && d < debtors.length) {
|
|
1522
|
+
const amount = Math.min(creditors[c].amount, debtors[d].amount);
|
|
1523
|
+
payments.push({ from: debtors[d].member, to: creditors[c].member, amount });
|
|
1524
|
+
creditors[c].amount -= amount;
|
|
1525
|
+
debtors[d].amount -= amount;
|
|
1526
|
+
if (creditors[c].amount === 0) c += 1;
|
|
1527
|
+
if (debtors[d].amount === 0) d += 1;
|
|
1528
|
+
}
|
|
1529
|
+
return payments;
|
|
1530
|
+
};
|
|
1531
|
+
const headroom = ({ balances, settlements, from, to }) => {
|
|
1532
|
+
const owes = Math.max(0, -(balances.get(from) ?? 0));
|
|
1533
|
+
const owed = Math.max(0, balances.get(to) ?? 0);
|
|
1534
|
+
const pendingOut = settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.from === from).reduce((sum, s) => sum + s.amount, 0);
|
|
1535
|
+
const pendingIn = settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.to === to).reduce((sum, s) => sum + s.amount, 0);
|
|
1536
|
+
return Math.max(0, Math.min(owes - pendingOut, owed - pendingIn));
|
|
1537
|
+
};
|
|
1538
|
+
const LIVE_STATUSES = [SETTLEMENT_STATUS.PENDING, SETTLEMENT_STATUS.CONFIRMED];
|
|
1539
|
+
const ledger = ({ strapi }) => ({
|
|
1540
|
+
/** Every seat of a group, people populated, in the order they joined. */
|
|
1541
|
+
async seats(group2) {
|
|
1542
|
+
return strapi.db.query(UID.MEMBER).findMany({
|
|
1543
|
+
where: { group: group2.id },
|
|
1544
|
+
populate: { person: true },
|
|
1545
|
+
orderBy: { id: "asc" }
|
|
1546
|
+
});
|
|
1547
|
+
},
|
|
1548
|
+
/** Expenses that count, flattened to ids. */
|
|
1549
|
+
async expenses(group2) {
|
|
1550
|
+
const rows = await strapi.db.query(UID.EXPENSE).findMany({
|
|
1551
|
+
where: { group: group2.id, deletedAt: { $null: true } },
|
|
1552
|
+
select: ["id", "amount"],
|
|
1553
|
+
populate: {
|
|
1554
|
+
paidBy: { select: ["id"] },
|
|
1555
|
+
shares: { select: ["amount"], populate: { member: { select: ["id"] } } }
|
|
1556
|
+
}
|
|
1557
|
+
});
|
|
1558
|
+
return rows.map((e) => ({
|
|
1559
|
+
paidBy: idOf(e.paidBy),
|
|
1560
|
+
amount: e.amount,
|
|
1561
|
+
shares: (e.shares ?? []).map((s) => ({ member: idOf(s.member), amount: s.amount }))
|
|
1562
|
+
}));
|
|
1563
|
+
},
|
|
1564
|
+
/** Settlements that count or reserve room, flattened to ids. */
|
|
1565
|
+
async settlements(group2) {
|
|
1566
|
+
const rows = await strapi.db.query(UID.SETTLEMENT).findMany({
|
|
1567
|
+
where: { group: group2.id, status: { $in: LIVE_STATUSES } },
|
|
1568
|
+
select: ["id", "amount", "status"],
|
|
1569
|
+
populate: { from: { select: ["id"] }, to: { select: ["id"] } }
|
|
1570
|
+
});
|
|
1571
|
+
return rows.map((s) => ({
|
|
1572
|
+
from: idOf(s.from),
|
|
1573
|
+
to: idOf(s.to),
|
|
1574
|
+
amount: s.amount,
|
|
1575
|
+
status: s.status
|
|
1576
|
+
}));
|
|
1577
|
+
},
|
|
1578
|
+
/**
|
|
1579
|
+
* @param {Object} group
|
|
1580
|
+
* @returns {Promise<{ seats: Object[], active: Object[], seatById: Map, balances: Map, payments: Array,
|
|
1581
|
+
* settlements: Array, expenseCount: number, total: number, room: Function, balanceOf: Function }>}
|
|
1582
|
+
*/
|
|
1583
|
+
async of(group2) {
|
|
1584
|
+
const [seats, expenses, settlements] = await Promise.all([
|
|
1585
|
+
this.seats(group2),
|
|
1586
|
+
this.expenses(group2),
|
|
1587
|
+
this.settlements(group2)
|
|
1588
|
+
]);
|
|
1589
|
+
const balances = computeBalances({ expenses, settlements });
|
|
1590
|
+
return {
|
|
1591
|
+
seats,
|
|
1592
|
+
active: seats.filter((s) => !s.leftAt),
|
|
1593
|
+
seatById: new Map(seats.map((s) => [s.id, s])),
|
|
1594
|
+
balances,
|
|
1595
|
+
payments: suggestPayments(balances),
|
|
1596
|
+
settlements,
|
|
1597
|
+
expenseCount: expenses.length,
|
|
1598
|
+
total: expenses.reduce((sum, e) => sum + e.amount, 0),
|
|
1599
|
+
/** The most seat `from` may still settle towards seat `to`. */
|
|
1600
|
+
room: (from, to) => headroom({ balances, settlements, from, to }),
|
|
1601
|
+
balanceOf: (seatId) => balances.get(seatId) ?? 0
|
|
1602
|
+
};
|
|
1603
|
+
},
|
|
1604
|
+
/** What is declared and awaiting confirmation from one seat to another. */
|
|
1605
|
+
pendingBetween(books, from, to) {
|
|
1606
|
+
return books.settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.from === from && s.to === to).reduce((sum, s) => sum + s.amount, 0);
|
|
1607
|
+
}
|
|
1608
|
+
});
|
|
1609
|
+
const cleanName = (raw) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, NAME_MAX);
|
|
1610
|
+
const group = ({ strapi }) => {
|
|
1611
|
+
const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
|
|
1612
|
+
const groups = () => strapi.db.query(UID.GROUP);
|
|
1613
|
+
const members = () => strapi.db.query(UID.MEMBER);
|
|
1614
|
+
return {
|
|
1615
|
+
cleanName,
|
|
1616
|
+
async generateInviteCode() {
|
|
1617
|
+
const prefix = svc("settings").inviteCodePrefix();
|
|
1618
|
+
for (let i = 0; i < MAX_CODE_ATTEMPTS; i += 1) {
|
|
1619
|
+
const inviteCode = `${prefix}-${randomCode(INVITE_CODE_LENGTH)}`;
|
|
1620
|
+
const taken = await groups().findOne({ where: { inviteCode }, select: ["id"] });
|
|
1621
|
+
if (!taken) return inviteCode;
|
|
1622
|
+
}
|
|
1623
|
+
throw conflict(ERROR_CODES.VALIDATION, "Impossible de générer un code d'invitation unique.");
|
|
1624
|
+
},
|
|
1625
|
+
/**
|
|
1626
|
+
* The group and the caller's seat in it.
|
|
1627
|
+
* @param {Object} person
|
|
1628
|
+
* @param {string} documentId
|
|
1629
|
+
* @param {{ writable?: boolean }} [options] `writable` refuses an archived group
|
|
1630
|
+
* @returns {Promise<{ group: Object, me: Object }>}
|
|
1631
|
+
*/
|
|
1632
|
+
async seat(person2, documentId, { writable = false } = {}) {
|
|
1633
|
+
const group2 = await groups().findOne({ where: { documentId: String(documentId) } });
|
|
1634
|
+
const me = group2 && await members().findOne({
|
|
1635
|
+
where: { group: group2.id, person: person2.id, leftAt: { $null: true } },
|
|
1636
|
+
populate: { person: true }
|
|
1637
|
+
});
|
|
1638
|
+
if (!me) throw notFound(ERROR_CODES.GROUP_NOT_FOUND, "Groupe introuvable.");
|
|
1639
|
+
if (writable && group2.archivedAt)
|
|
1640
|
+
throw conflict(ERROR_CODES.GROUP_ARCHIVED, "Ce groupe est archivé.");
|
|
1641
|
+
return { group: group2, me };
|
|
1642
|
+
},
|
|
1643
|
+
/** Only the owner. */
|
|
1644
|
+
assertOwner(me) {
|
|
1645
|
+
if (me.role !== ROLE.OWNER)
|
|
1646
|
+
throw forbidden(ERROR_CODES.NOT_ALLOWED, "Seul le créateur du groupe peut faire ça.");
|
|
1647
|
+
},
|
|
1648
|
+
/** The seats a person holds, groups populated; archived groups only on request. */
|
|
1649
|
+
async seatsOf(person2, { archived = false } = {}) {
|
|
1650
|
+
const rows = await members().findMany({
|
|
1651
|
+
where: { person: person2.id, leftAt: { $null: true } },
|
|
1652
|
+
populate: { group: true, person: true }
|
|
1653
|
+
});
|
|
1654
|
+
return rows.filter((m) => m.group && Boolean(m.group.archivedAt) === archived);
|
|
1655
|
+
},
|
|
1656
|
+
/** A write that every other write of the group waits behind: taken first in a transaction. */
|
|
1657
|
+
async lock(group2) {
|
|
1658
|
+
await groups().update({ where: { id: group2.id }, data: { lastActivityAt: /* @__PURE__ */ new Date() } });
|
|
1659
|
+
},
|
|
1660
|
+
/**
|
|
1661
|
+
* @param {Object} person the creator, who becomes the owner
|
|
1662
|
+
* @param {{ name: string, members?: Array<{ name: string, phone?: string }> }} input
|
|
1663
|
+
*/
|
|
1664
|
+
async create(person2, input) {
|
|
1665
|
+
const name = cleanName(input.name);
|
|
1666
|
+
if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
|
|
1667
|
+
const limits = svc("settings").limits();
|
|
1668
|
+
const held = await members().count({ where: { person: person2.id, leftAt: { $null: true } } });
|
|
1669
|
+
if (held >= limits.maxGroupsPerPerson)
|
|
1670
|
+
throw unprocessable(
|
|
1671
|
+
ERROR_CODES.GROUP_LIMIT,
|
|
1672
|
+
`Maximum ${limits.maxGroupsPerPerson} groupes.`
|
|
1673
|
+
);
|
|
1674
|
+
const others = svc("member").parseMany(input.members ?? [], person2);
|
|
1675
|
+
if (others.length + 1 > limits.maxMembersPerGroup)
|
|
1676
|
+
throw unprocessable(
|
|
1677
|
+
ERROR_CODES.MEMBER_LIMIT,
|
|
1678
|
+
`Maximum ${limits.maxMembersPerGroup} membres.`
|
|
1679
|
+
);
|
|
1680
|
+
const inviteCode = await this.generateInviteCode();
|
|
1681
|
+
const now = /* @__PURE__ */ new Date();
|
|
1682
|
+
const group2 = await strapi.db.transaction(async () => {
|
|
1683
|
+
const g = await groups().create({
|
|
1684
|
+
data: { name, inviteCode, founder: person2.id, lastActivityAt: now }
|
|
1685
|
+
});
|
|
1686
|
+
await members().create({
|
|
1687
|
+
data: {
|
|
1688
|
+
group: g.id,
|
|
1689
|
+
person: person2.id,
|
|
1690
|
+
displayName: person2.displayName || "Moi",
|
|
1691
|
+
phone: person2.phone ?? null,
|
|
1692
|
+
role: ROLE.OWNER,
|
|
1693
|
+
joinedAt: now
|
|
1694
|
+
}
|
|
1695
|
+
});
|
|
1696
|
+
for (const other of others) await svc("member").seatFor(g, other);
|
|
1697
|
+
return g;
|
|
1698
|
+
});
|
|
1699
|
+
await svc("audit").log({
|
|
1700
|
+
group: group2,
|
|
1701
|
+
actor: person2,
|
|
1702
|
+
action: EVENT.GROUP_CREATED,
|
|
1703
|
+
data: { members: others.length + 1 }
|
|
1704
|
+
});
|
|
1705
|
+
return group2;
|
|
1706
|
+
},
|
|
1707
|
+
async rename({ group: group2, me }, rawName) {
|
|
1708
|
+
this.assertOwner(me);
|
|
1709
|
+
const name = cleanName(rawName);
|
|
1710
|
+
if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
|
|
1711
|
+
const updated = await groups().update({ where: { id: group2.id }, data: { name } });
|
|
1712
|
+
await svc("audit").log({
|
|
1713
|
+
group: group2,
|
|
1714
|
+
actor: me.person,
|
|
1715
|
+
action: EVENT.GROUP_RENAMED,
|
|
1716
|
+
data: { from: group2.name, to: name }
|
|
1717
|
+
});
|
|
1718
|
+
return updated;
|
|
1719
|
+
},
|
|
1720
|
+
/** @param {Object} group @param {Object|null} actor a person, or null for an administrator */
|
|
1721
|
+
async archive(group2, actor) {
|
|
1722
|
+
if (group2.archivedAt) return group2;
|
|
1723
|
+
const updated = await groups().update({
|
|
1724
|
+
where: { id: group2.id },
|
|
1725
|
+
data: { archivedAt: /* @__PURE__ */ new Date() }
|
|
1726
|
+
});
|
|
1727
|
+
await svc("audit").log({ group: group2, actor, action: EVENT.GROUP_ARCHIVED });
|
|
1728
|
+
return updated;
|
|
1729
|
+
},
|
|
1730
|
+
/**
|
|
1731
|
+
* Take a seat with an invite code. A seat that was waiting for this person's phone is theirs
|
|
1732
|
+
* already; joining twice is not an error.
|
|
1733
|
+
*/
|
|
1734
|
+
async join(person2, rawCode) {
|
|
1735
|
+
const inviteCode = String(rawCode ?? "").trim().toUpperCase();
|
|
1736
|
+
const group2 = inviteCode && await groups().findOne({ where: { inviteCode } });
|
|
1737
|
+
if (!group2 || group2.archivedAt)
|
|
1738
|
+
throw notFound(ERROR_CODES.INVITE_INVALID, "Ce code d'invitation n'existe pas.");
|
|
1739
|
+
const existing = await members().findOne({
|
|
1740
|
+
where: { group: group2.id, person: person2.id, leftAt: { $null: true } }
|
|
1741
|
+
});
|
|
1742
|
+
if (existing) return group2;
|
|
1743
|
+
const limits = svc("settings").limits();
|
|
1744
|
+
const count = await members().count({ where: { group: group2.id, leftAt: { $null: true } } });
|
|
1745
|
+
if (count >= limits.maxMembersPerGroup)
|
|
1746
|
+
throw unprocessable(ERROR_CODES.MEMBER_LIMIT, "Ce groupe est complet.");
|
|
1747
|
+
await members().create({
|
|
1748
|
+
data: {
|
|
1749
|
+
group: group2.id,
|
|
1750
|
+
person: person2.id,
|
|
1751
|
+
displayName: person2.displayName || "Membre",
|
|
1752
|
+
phone: person2.phone ?? null,
|
|
1753
|
+
role: ROLE.MEMBER,
|
|
1754
|
+
joinedAt: /* @__PURE__ */ new Date()
|
|
1755
|
+
}
|
|
1756
|
+
});
|
|
1757
|
+
await svc("audit").log({ group: group2, actor: person2, action: EVENT.MEMBER_JOINED });
|
|
1758
|
+
return group2;
|
|
1759
|
+
},
|
|
1760
|
+
async byDocumentId(documentId) {
|
|
1761
|
+
const group2 = await groups().findOne({ where: { documentId: String(documentId) } });
|
|
1762
|
+
if (!group2) throw notFound(ERROR_CODES.GROUP_NOT_FOUND, "Groupe introuvable.");
|
|
1763
|
+
return group2;
|
|
1764
|
+
},
|
|
1765
|
+
/**
|
|
1766
|
+
* Admin search by name or invite code.
|
|
1767
|
+
* @param {{ q?: string, archived?: boolean }} filters
|
|
1768
|
+
* @param {{ offset: number, limit: number }} page
|
|
1769
|
+
*/
|
|
1770
|
+
async search(filters, page) {
|
|
1771
|
+
const where = {};
|
|
1772
|
+
if (filters.q) {
|
|
1773
|
+
const q = String(filters.q).trim();
|
|
1774
|
+
where.$or = [{ name: { $containsi: q } }, { inviteCode: { $containsi: q } }];
|
|
1775
|
+
}
|
|
1776
|
+
if (typeof filters.archived === "boolean")
|
|
1777
|
+
where.archivedAt = filters.archived ? { $notNull: true } : { $null: true };
|
|
1778
|
+
const [items, total] = await Promise.all([
|
|
1779
|
+
groups().findMany({
|
|
1780
|
+
where,
|
|
1781
|
+
orderBy: { lastActivityAt: "desc" },
|
|
1782
|
+
offset: page.offset,
|
|
1783
|
+
limit: page.limit
|
|
1784
|
+
}),
|
|
1785
|
+
groups().count({ where })
|
|
1786
|
+
]);
|
|
1787
|
+
return { items, total };
|
|
1788
|
+
}
|
|
1789
|
+
};
|
|
1790
|
+
};
|
|
1791
|
+
const member = ({ strapi }) => {
|
|
1792
|
+
const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
|
|
1793
|
+
const members = () => strapi.db.query(UID.MEMBER);
|
|
1794
|
+
return {
|
|
1795
|
+
/** One `{ name, phone }` as sent, checked. */
|
|
1796
|
+
parse(raw) {
|
|
1797
|
+
const displayName = String(raw?.name ?? "").trim().replace(/\s+/g, " ").slice(0, NAME_MAX);
|
|
1798
|
+
if (!displayName) throw badRequest(ERROR_CODES.VALIDATION, "Chaque membre a un nom.");
|
|
1799
|
+
const sent = String(raw?.phone ?? "").trim();
|
|
1800
|
+
const phone = sent ? normalizePhone(sent, svc("settings").countryCode()) : null;
|
|
1801
|
+
if (sent && !phone) throw badRequest(ERROR_CODES.VALIDATION, "Numéro de téléphone invalide.");
|
|
1802
|
+
return { displayName, phone };
|
|
1803
|
+
},
|
|
1804
|
+
/** Several at once (a new group): nobody twice, and not the creator. */
|
|
1805
|
+
parseMany(list, creator) {
|
|
1806
|
+
if (!Array.isArray(list))
|
|
1807
|
+
throw badRequest(ERROR_CODES.VALIDATION, "Liste de membres invalide.");
|
|
1808
|
+
const parsed = list.map((raw) => this.parse(raw));
|
|
1809
|
+
const phones = parsed.map((m) => m.phone).filter(Boolean);
|
|
1810
|
+
if (new Set(phones).size !== phones.length || phones.includes(creator.phone))
|
|
1811
|
+
throw conflict(ERROR_CODES.MEMBER_EXISTS, "Un numéro apparaît deux fois.");
|
|
1812
|
+
return parsed;
|
|
1813
|
+
},
|
|
1814
|
+
/** Create the seat; it is the person's at once when that phone already uses the app. */
|
|
1815
|
+
async seatFor(group2, { displayName, phone }) {
|
|
1816
|
+
const person2 = await svc("person").byPhone(phone);
|
|
1817
|
+
return members().create({
|
|
1818
|
+
data: {
|
|
1819
|
+
group: group2.id,
|
|
1820
|
+
person: person2?.id ?? null,
|
|
1821
|
+
displayName,
|
|
1822
|
+
phone,
|
|
1823
|
+
role: ROLE.MEMBER,
|
|
1824
|
+
joinedAt: person2 ? /* @__PURE__ */ new Date() : null
|
|
1825
|
+
}
|
|
1826
|
+
});
|
|
1827
|
+
},
|
|
1828
|
+
/**
|
|
1829
|
+
* @param {{ group: Object, me: Object }} seat the caller's
|
|
1830
|
+
* @param {{ name: string, phone?: string }} raw
|
|
1831
|
+
* @returns {Promise<Object>} the new seat, person populated
|
|
1832
|
+
*/
|
|
1833
|
+
async add({ group: group2, me }, raw) {
|
|
1834
|
+
const input = this.parse(raw);
|
|
1835
|
+
const limits = svc("settings").limits();
|
|
1836
|
+
const seats = await members().findMany({
|
|
1837
|
+
where: { group: group2.id, leftAt: { $null: true } },
|
|
1838
|
+
populate: { person: true }
|
|
1839
|
+
});
|
|
1840
|
+
if (seats.length >= limits.maxMembersPerGroup)
|
|
1841
|
+
throw unprocessable(
|
|
1842
|
+
ERROR_CODES.MEMBER_LIMIT,
|
|
1843
|
+
`Maximum ${limits.maxMembersPerGroup} membres.`
|
|
1844
|
+
);
|
|
1845
|
+
const format2 = svc("format");
|
|
1846
|
+
if (input.phone && seats.some((s) => format2.phoneOf(s) === input.phone))
|
|
1847
|
+
throw conflict(ERROR_CODES.MEMBER_EXISTS, "Ce numéro est déjà dans le groupe.");
|
|
1848
|
+
const created = await this.seatFor(group2, input);
|
|
1849
|
+
await svc("audit").log({
|
|
1850
|
+
group: group2,
|
|
1851
|
+
actor: me.person,
|
|
1852
|
+
action: EVENT.MEMBER_ADDED,
|
|
1853
|
+
targetId: created.documentId
|
|
1854
|
+
});
|
|
1855
|
+
return members().findOne({ where: { id: created.id }, populate: { person: true } });
|
|
1856
|
+
},
|
|
1857
|
+
/** A seat of this group by its document id. */
|
|
1858
|
+
async find(group2, documentId) {
|
|
1859
|
+
const seat = await members().findOne({
|
|
1860
|
+
where: { group: group2.id, documentId: String(documentId), leftAt: { $null: true } },
|
|
1861
|
+
populate: { person: true }
|
|
1862
|
+
});
|
|
1863
|
+
if (!seat) throw notFound(ERROR_CODES.MEMBER_NOT_FOUND, "Membre introuvable.");
|
|
1864
|
+
return seat;
|
|
1865
|
+
},
|
|
1866
|
+
/** A seat is only vacated once it is even and nothing awaits confirmation on it. */
|
|
1867
|
+
async assertSettled(group2, seat) {
|
|
1868
|
+
const books = await svc("ledger").of(group2);
|
|
1869
|
+
const busy = books.settlements.some(
|
|
1870
|
+
(s) => s.status === SETTLEMENT_STATUS.PENDING && [s.from, s.to].includes(seat.id)
|
|
1871
|
+
);
|
|
1872
|
+
if (books.balanceOf(seat.id) !== 0 || busy)
|
|
1873
|
+
throw unprocessable(
|
|
1874
|
+
ERROR_CODES.MEMBER_NOT_SETTLED,
|
|
1875
|
+
"Les comptes de ce membre ne sont pas à zéro.",
|
|
1876
|
+
{ balance: books.balanceOf(seat.id) }
|
|
1877
|
+
);
|
|
1878
|
+
},
|
|
1879
|
+
/** The owner removes someone else. */
|
|
1880
|
+
async remove({ group: group2, me }, documentId) {
|
|
1881
|
+
svc("group").assertOwner(me);
|
|
1882
|
+
const seat = await this.find(group2, documentId);
|
|
1883
|
+
if (seat.id === me.id)
|
|
1884
|
+
throw forbidden(ERROR_CODES.NOT_ALLOWED, "Le créateur ne peut pas se retirer.");
|
|
1885
|
+
await this.assertSettled(group2, seat);
|
|
1886
|
+
await members().update({ where: { id: seat.id }, data: { leftAt: /* @__PURE__ */ new Date() } });
|
|
1887
|
+
await svc("audit").log({
|
|
1888
|
+
group: group2,
|
|
1889
|
+
actor: me.person,
|
|
1890
|
+
action: EVENT.MEMBER_REMOVED,
|
|
1891
|
+
targetId: seat.documentId
|
|
1892
|
+
});
|
|
1893
|
+
},
|
|
1894
|
+
/** Someone leaves by themselves. The owner cannot: the group would have nobody to run it. */
|
|
1895
|
+
async leave({ group: group2, me }) {
|
|
1896
|
+
if (me.role === ROLE.OWNER)
|
|
1897
|
+
throw forbidden(ERROR_CODES.NOT_ALLOWED, "Le créateur ne peut pas quitter le groupe.");
|
|
1898
|
+
await this.assertSettled(group2, me);
|
|
1899
|
+
await members().update({ where: { id: me.id }, data: { leftAt: /* @__PURE__ */ new Date() } });
|
|
1900
|
+
await svc("audit").log({
|
|
1901
|
+
group: group2,
|
|
1902
|
+
actor: me.person,
|
|
1903
|
+
action: EVENT.MEMBER_LEFT,
|
|
1904
|
+
targetId: me.documentId
|
|
1905
|
+
});
|
|
1906
|
+
},
|
|
1907
|
+
/** Is this seat held by this person? */
|
|
1908
|
+
isHeldBy(seat, person2) {
|
|
1909
|
+
return idOf(seat.person) === person2.id;
|
|
1910
|
+
}
|
|
1911
|
+
};
|
|
1912
|
+
};
|
|
1913
|
+
const invalid = (message, details) => unprocessable(ERROR_CODES.SPLIT_INVALID, message, details);
|
|
1914
|
+
const sharesByWeight = (amount, weights) => {
|
|
1915
|
+
const total = weights.reduce((sum, w) => sum + w, 0);
|
|
1916
|
+
if (total === 0) return weights.map(() => 0);
|
|
1917
|
+
const shares = weights.map((w) => Math.floor(amount * w / total));
|
|
1918
|
+
let leftover = amount - shares.reduce((sum, s) => sum + s, 0);
|
|
1919
|
+
return shares.map((share2, i) => {
|
|
1920
|
+
const extra = weights[i] > 0 && leftover > 0 ? 1 : 0;
|
|
1921
|
+
leftover -= extra;
|
|
1922
|
+
return share2 + extra;
|
|
1923
|
+
});
|
|
1924
|
+
};
|
|
1925
|
+
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
|
1926
|
+
const weightOf = (part, mode) => {
|
|
1927
|
+
if (mode === SPLIT_MODE.EQUAL) return 1;
|
|
1928
|
+
if (!isCount(part.weight) || part.weight > MAX_WEIGHT)
|
|
1929
|
+
throw invalid(`Chaque part est un entier entre 0 et ${MAX_WEIGHT}.`);
|
|
1930
|
+
return part.weight;
|
|
1931
|
+
};
|
|
1932
|
+
const freeShares = (amount, parts) => {
|
|
1933
|
+
if (!parts.every((p) => isCount(p.amount)))
|
|
1934
|
+
throw invalid("Chaque montant est un entier positif.");
|
|
1935
|
+
const sum = parts.reduce((total, p) => total + p.amount, 0);
|
|
1936
|
+
if (sum !== amount)
|
|
1937
|
+
throw invalid("La somme des parts ne correspond pas au montant.", { amount, sum });
|
|
1938
|
+
return parts.map((p) => p.amount);
|
|
1939
|
+
};
|
|
1940
|
+
const resolveShares = ({ amount, mode, parts }) => {
|
|
1941
|
+
if (!Object.values(SPLIT_MODE).includes(mode)) throw invalid("Mode de partage inconnu.");
|
|
1942
|
+
if (!Array.isArray(parts) || parts.length === 0) throw invalid("Personne ne participe.");
|
|
1943
|
+
if (new Set(parts.map((p) => String(p.member))).size !== parts.length)
|
|
1944
|
+
throw invalid("Un membre apparaît deux fois.");
|
|
1945
|
+
const weights = mode === SPLIT_MODE.FREE ? null : parts.map((p) => weightOf(p, mode));
|
|
1946
|
+
const amounts = weights ? sharesByWeight(amount, weights) : freeShares(amount, parts);
|
|
1947
|
+
const shares = parts.map((p, i) => ({ member: p.member, amount: amounts[i], weight: weights ? weights[i] : 0 })).filter((s) => s.amount > 0);
|
|
1948
|
+
if (shares.length === 0) throw invalid("Personne ne participe.");
|
|
1949
|
+
return shares;
|
|
1950
|
+
};
|
|
1951
|
+
const POPULATE$1 = {
|
|
1952
|
+
paidBy: { populate: { person: true } },
|
|
1953
|
+
addedBy: { select: ["id"] },
|
|
1954
|
+
shares: { populate: { member: { populate: { person: true } } } }
|
|
1955
|
+
};
|
|
1956
|
+
const isDuplicate$1 = (err) => /unique|duplicate/i.test(String(err?.message));
|
|
1957
|
+
const expense = ({ strapi }) => {
|
|
1958
|
+
const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
|
|
1959
|
+
const expenses = () => strapi.db.query(UID.EXPENSE);
|
|
1960
|
+
const shares = () => strapi.db.query(UID.SHARE);
|
|
1961
|
+
return {
|
|
1962
|
+
/** When the expense happened: the caller's date when it is a real one and not in the future. */
|
|
1963
|
+
spentAt(raw) {
|
|
1964
|
+
const date = raw ? new Date(raw) : /* @__PURE__ */ new Date();
|
|
1965
|
+
return Number.isNaN(date.getTime()) || date > /* @__PURE__ */ new Date() ? /* @__PURE__ */ new Date() : date;
|
|
1966
|
+
},
|
|
1967
|
+
/**
|
|
1968
|
+
* What the caller sent, checked against the group's active seats.
|
|
1969
|
+
* @returns {{ label: string, category: string|null, amount: number, mode: string, spentAt: Date,
|
|
1970
|
+
* paidBy: number, shares: Array<{ member: number, amount: number, weight: number }> }}
|
|
1971
|
+
*/
|
|
1972
|
+
parse(input, active) {
|
|
1973
|
+
const label = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
|
|
1974
|
+
if (!label) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
|
|
1975
|
+
const { maxAmount } = svc("settings").limits();
|
|
1976
|
+
const amount = input?.amount;
|
|
1977
|
+
if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
|
|
1978
|
+
throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
|
|
1979
|
+
const seatByDoc = new Map(active.map((s) => [s.documentId, s]));
|
|
1980
|
+
const seat = (documentId) => {
|
|
1981
|
+
const found = seatByDoc.get(String(documentId));
|
|
1982
|
+
if (!found)
|
|
1983
|
+
throw badRequest(ERROR_CODES.MEMBER_NOT_FOUND, "Membre introuvable dans ce groupe.");
|
|
1984
|
+
return found.id;
|
|
1985
|
+
};
|
|
1986
|
+
const mode = input?.mode ?? SPLIT_MODE.EQUAL;
|
|
1987
|
+
const parts = (Array.isArray(input?.shares) ? input.shares : []).map((p) => ({
|
|
1988
|
+
member: seat(p?.member),
|
|
1989
|
+
weight: p?.weight,
|
|
1990
|
+
amount: p?.amount
|
|
1991
|
+
}));
|
|
1992
|
+
return {
|
|
1993
|
+
label,
|
|
1994
|
+
category: input?.category ? String(input.category).slice(0, 40) : null,
|
|
1995
|
+
amount,
|
|
1996
|
+
mode,
|
|
1997
|
+
spentAt: this.spentAt(input?.spentAt),
|
|
1998
|
+
paidBy: seat(input?.paidBy),
|
|
1999
|
+
shares: resolveShares({ amount, mode, parts })
|
|
2000
|
+
};
|
|
2001
|
+
},
|
|
2002
|
+
async one(id) {
|
|
2003
|
+
return expenses().findOne({ where: { id }, populate: POPULATE$1 });
|
|
2004
|
+
},
|
|
2005
|
+
/** An expense already written under this reference, in this group. */
|
|
2006
|
+
async replayed(group2, clientRef) {
|
|
2007
|
+
if (!clientRef) return null;
|
|
2008
|
+
const found = await expenses().findOne({
|
|
2009
|
+
where: { clientRef, group: group2.id },
|
|
2010
|
+
populate: POPULATE$1
|
|
2011
|
+
});
|
|
2012
|
+
return found ?? null;
|
|
2013
|
+
},
|
|
2014
|
+
async writeShares(expenseId, list) {
|
|
2015
|
+
for (const s of list) {
|
|
2016
|
+
await shares().create({
|
|
2017
|
+
data: { expense: expenseId, member: s.member, amount: s.amount, weight: s.weight }
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
},
|
|
2021
|
+
/**
|
|
2022
|
+
* @param {{ group: Object, me: Object }} seat the caller's
|
|
2023
|
+
* @param {Object} input `{ label, amount, mode, paidBy, shares, category?, spentAt?, clientRef? }`
|
|
2024
|
+
* @returns {Promise<{ expense: Object, replayed: boolean }>}
|
|
2025
|
+
*/
|
|
2026
|
+
async create({ group: group2, me }, input) {
|
|
2027
|
+
const clientRef = input?.clientRef ? String(input.clientRef).slice(0, REF_MAX) : null;
|
|
2028
|
+
const earlier = await this.replayed(group2, clientRef);
|
|
2029
|
+
if (earlier) return { expense: earlier, replayed: true };
|
|
2030
|
+
const { active } = await svc("ledger").of(group2);
|
|
2031
|
+
const { shares: list, ...data } = this.parse(input, active);
|
|
2032
|
+
try {
|
|
2033
|
+
const created = await strapi.db.transaction(async () => {
|
|
2034
|
+
await svc("group").lock(group2);
|
|
2035
|
+
const e = await expenses().create({
|
|
2036
|
+
data: { ...data, group: group2.id, addedBy: me.id, clientRef }
|
|
2037
|
+
});
|
|
2038
|
+
await this.writeShares(e.id, list);
|
|
2039
|
+
return e;
|
|
2040
|
+
});
|
|
2041
|
+
await svc("audit").log({
|
|
2042
|
+
group: group2,
|
|
2043
|
+
actor: me.person,
|
|
2044
|
+
action: EVENT.EXPENSE_CREATED,
|
|
2045
|
+
targetId: created.documentId,
|
|
2046
|
+
data: { amount: data.amount }
|
|
2047
|
+
});
|
|
2048
|
+
return { expense: await this.one(created.id), replayed: false };
|
|
2049
|
+
} catch (err) {
|
|
2050
|
+
const twin = isDuplicate$1(err) ? await this.replayed(group2, clientRef) : null;
|
|
2051
|
+
if (!twin) throw err;
|
|
2052
|
+
return { expense: twin, replayed: true };
|
|
2053
|
+
}
|
|
2054
|
+
},
|
|
2055
|
+
/** An expense of this group the caller may change. */
|
|
2056
|
+
async editable({ group: group2, me }, documentId) {
|
|
2057
|
+
const expense2 = await expenses().findOne({
|
|
2058
|
+
where: { group: group2.id, documentId: String(documentId), deletedAt: { $null: true } },
|
|
2059
|
+
populate: POPULATE$1
|
|
2060
|
+
});
|
|
2061
|
+
if (!expense2) throw notFound(ERROR_CODES.EXPENSE_NOT_FOUND, "Dépense introuvable.");
|
|
2062
|
+
const mine = [idOf(expense2.paidBy), idOf(expense2.addedBy)].includes(me.id);
|
|
2063
|
+
if (!mine && me.role !== ROLE.OWNER)
|
|
2064
|
+
throw forbidden(
|
|
2065
|
+
ERROR_CODES.NOT_ALLOWED,
|
|
2066
|
+
"Seul celui qui a payé ou noté la dépense peut la modifier."
|
|
2067
|
+
);
|
|
2068
|
+
return expense2;
|
|
2069
|
+
},
|
|
2070
|
+
async update(seat, documentId, input) {
|
|
2071
|
+
const { group: group2, me } = seat;
|
|
2072
|
+
const expense2 = await this.editable(seat, documentId);
|
|
2073
|
+
const { active } = await svc("ledger").of(group2);
|
|
2074
|
+
const { shares: list, ...data } = this.parse(input, active);
|
|
2075
|
+
await strapi.db.transaction(async () => {
|
|
2076
|
+
await svc("group").lock(group2);
|
|
2077
|
+
await expenses().update({ where: { id: expense2.id }, data });
|
|
2078
|
+
await shares().deleteMany({ where: { expense: expense2.id } });
|
|
2079
|
+
await this.writeShares(expense2.id, list);
|
|
2080
|
+
});
|
|
2081
|
+
await svc("audit").log({
|
|
2082
|
+
group: group2,
|
|
2083
|
+
actor: me.person,
|
|
2084
|
+
action: EVENT.EXPENSE_UPDATED,
|
|
2085
|
+
targetId: expense2.documentId,
|
|
2086
|
+
data: { from: expense2.amount, to: data.amount }
|
|
2087
|
+
});
|
|
2088
|
+
return this.one(expense2.id);
|
|
2089
|
+
},
|
|
2090
|
+
async remove(seat, documentId) {
|
|
2091
|
+
const { group: group2, me } = seat;
|
|
2092
|
+
const expense2 = await this.editable(seat, documentId);
|
|
2093
|
+
await strapi.db.transaction(async () => {
|
|
2094
|
+
await svc("group").lock(group2);
|
|
2095
|
+
await expenses().update({ where: { id: expense2.id }, data: { deletedAt: /* @__PURE__ */ new Date() } });
|
|
2096
|
+
});
|
|
2097
|
+
await svc("audit").log({
|
|
2098
|
+
group: group2,
|
|
2099
|
+
actor: me.person,
|
|
2100
|
+
action: EVENT.EXPENSE_DELETED,
|
|
2101
|
+
targetId: expense2.documentId,
|
|
2102
|
+
data: { amount: expense2.amount }
|
|
2103
|
+
});
|
|
2104
|
+
},
|
|
2105
|
+
/**
|
|
2106
|
+
* @param {Object} group
|
|
2107
|
+
* @param {{ offset: number, limit: number }} page
|
|
2108
|
+
*/
|
|
2109
|
+
async list(group2, page) {
|
|
2110
|
+
const where = { group: group2.id, deletedAt: { $null: true } };
|
|
2111
|
+
const [items, total] = await Promise.all([
|
|
2112
|
+
expenses().findMany({
|
|
2113
|
+
where,
|
|
2114
|
+
populate: POPULATE$1,
|
|
2115
|
+
orderBy: [{ spentAt: "desc" }, { id: "desc" }],
|
|
2116
|
+
offset: page.offset,
|
|
2117
|
+
limit: page.limit
|
|
2118
|
+
}),
|
|
2119
|
+
expenses().count({ where })
|
|
2120
|
+
]);
|
|
2121
|
+
return { items, total };
|
|
2122
|
+
}
|
|
2123
|
+
};
|
|
2124
|
+
};
|
|
2125
|
+
const POPULATE = { from: { populate: { person: true } }, to: { populate: { person: true } } };
|
|
2126
|
+
const isDuplicate = (err) => /unique|duplicate/i.test(String(err?.message));
|
|
2127
|
+
const text = (raw, max) => raw ? String(raw).trim().slice(0, max) || null : null;
|
|
2128
|
+
const settlement = ({ strapi }) => {
|
|
2129
|
+
const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
|
|
2130
|
+
const settlements = () => strapi.db.query(UID.SETTLEMENT);
|
|
2131
|
+
return {
|
|
2132
|
+
/** What the caller sent, checked. The receiving seat is looked up in the group. */
|
|
2133
|
+
async parse({ group: group2, me }, input) {
|
|
2134
|
+
const { maxAmount } = svc("settings").limits();
|
|
2135
|
+
const amount = input?.amount;
|
|
2136
|
+
if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
|
|
2137
|
+
throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
|
|
2138
|
+
const method = svc("settings").methods()[String(input?.method)];
|
|
2139
|
+
if (!method) throw badRequest(ERROR_CODES.METHOD_UNKNOWN, "Moyen de paiement inconnu.");
|
|
2140
|
+
const to = await svc("member").find(group2, input?.to);
|
|
2141
|
+
if (to.id === me.id)
|
|
2142
|
+
throw badRequest(ERROR_CODES.VALIDATION, "Tu ne peux pas te régler à toi-même.");
|
|
2143
|
+
return {
|
|
2144
|
+
amount,
|
|
2145
|
+
to,
|
|
2146
|
+
method: String(input.method),
|
|
2147
|
+
instant: method.instant || !to.person,
|
|
2148
|
+
reference: text(input?.reference, REF_MAX),
|
|
2149
|
+
note: text(input?.note, NOTE_MAX),
|
|
2150
|
+
clientRef: text(input?.clientRef, REF_MAX)
|
|
2151
|
+
};
|
|
2152
|
+
},
|
|
2153
|
+
/** A settlement already written under one of these references, in this group. */
|
|
2154
|
+
async replayed(group2, { clientRef, reference }) {
|
|
2155
|
+
const keys = [clientRef && { clientRef }, reference && { reference }].filter(Boolean);
|
|
2156
|
+
if (keys.length === 0) return null;
|
|
2157
|
+
const found = await settlements().findOne({
|
|
2158
|
+
where: { group: group2.id, $or: keys },
|
|
2159
|
+
populate: POPULATE
|
|
2160
|
+
});
|
|
2161
|
+
return found ?? null;
|
|
2162
|
+
},
|
|
2163
|
+
async one(id) {
|
|
2164
|
+
return settlements().findOne({ where: { id }, populate: POPULATE });
|
|
2165
|
+
},
|
|
2166
|
+
/** Inside the transaction: read the books behind the lock, refuse what exceeds them, write. */
|
|
2167
|
+
async write({ group: group2, me }, data) {
|
|
2168
|
+
await svc("group").lock(group2);
|
|
2169
|
+
const books = await svc("ledger").of(group2);
|
|
2170
|
+
const outstanding = books.room(me.id, data.to.id);
|
|
2171
|
+
if (data.amount > outstanding)
|
|
2172
|
+
throw unprocessable(
|
|
2173
|
+
ERROR_CODES.SETTLEMENT_EXCEEDS_DEBT,
|
|
2174
|
+
outstanding > 0 ? "Le montant dépasse ce qui est dû." : "Rien à régler envers ce membre.",
|
|
2175
|
+
{ outstanding }
|
|
2176
|
+
);
|
|
2177
|
+
const now = /* @__PURE__ */ new Date();
|
|
2178
|
+
return settlements().create({
|
|
2179
|
+
data: {
|
|
2180
|
+
group: group2.id,
|
|
2181
|
+
from: me.id,
|
|
2182
|
+
to: data.to.id,
|
|
2183
|
+
amount: data.amount,
|
|
2184
|
+
method: data.method,
|
|
2185
|
+
status: data.instant ? SETTLEMENT_STATUS.CONFIRMED : SETTLEMENT_STATUS.PENDING,
|
|
2186
|
+
reference: data.reference,
|
|
2187
|
+
note: data.note,
|
|
2188
|
+
clientRef: data.clientRef,
|
|
2189
|
+
declaredAt: now,
|
|
2190
|
+
resolvedAt: data.instant ? now : null,
|
|
2191
|
+
resolvedBy: data.instant ? idOf(me.person) : null
|
|
2192
|
+
}
|
|
2193
|
+
});
|
|
2194
|
+
},
|
|
2195
|
+
/**
|
|
2196
|
+
* @param {{ group: Object, me: Object }} seat the payer's
|
|
2197
|
+
* @param {Object} input `{ to, amount, method, reference?, note?, clientRef? }`
|
|
2198
|
+
* @returns {Promise<{ settlement: Object, replayed: boolean }>}
|
|
2199
|
+
*/
|
|
2200
|
+
async create(seat, input) {
|
|
2201
|
+
const data = await this.parse(seat, input);
|
|
2202
|
+
const earlier = await this.replayed(seat.group, data);
|
|
2203
|
+
if (earlier) return { settlement: earlier, replayed: true };
|
|
2204
|
+
try {
|
|
2205
|
+
const created = await strapi.db.transaction(() => this.write(seat, data));
|
|
2206
|
+
await svc("audit").log({
|
|
2207
|
+
group: seat.group,
|
|
2208
|
+
actor: seat.me.person,
|
|
2209
|
+
action: EVENT.SETTLEMENT_CREATED,
|
|
2210
|
+
targetId: created.documentId,
|
|
2211
|
+
data: {
|
|
2212
|
+
amount: data.amount,
|
|
2213
|
+
method: data.method,
|
|
2214
|
+
status: created.status,
|
|
2215
|
+
reference: data.reference
|
|
2216
|
+
}
|
|
2217
|
+
});
|
|
2218
|
+
return { settlement: await this.one(created.id), replayed: false };
|
|
2219
|
+
} catch (err) {
|
|
2220
|
+
const twin = isDuplicate(err) ? await this.replayed(seat.group, data) : null;
|
|
2221
|
+
if (!twin) throw err;
|
|
2222
|
+
return { settlement: twin, replayed: true };
|
|
2223
|
+
}
|
|
2224
|
+
},
|
|
2225
|
+
/** A pending settlement of this group. */
|
|
2226
|
+
async pending(group2, documentId) {
|
|
2227
|
+
const s = await settlements().findOne({
|
|
2228
|
+
where: { group: group2.id, documentId: String(documentId) },
|
|
2229
|
+
populate: POPULATE
|
|
2230
|
+
});
|
|
2231
|
+
if (!s) throw notFound(ERROR_CODES.SETTLEMENT_NOT_FOUND, "Règlement introuvable.");
|
|
2232
|
+
if (s.status !== SETTLEMENT_STATUS.PENDING)
|
|
2233
|
+
throw unprocessable(
|
|
2234
|
+
ERROR_CODES.SETTLEMENT_NOT_PENDING,
|
|
2235
|
+
`Ce règlement est déjà ${s.status}.`,
|
|
2236
|
+
{ status: s.status }
|
|
2237
|
+
);
|
|
2238
|
+
return s;
|
|
2239
|
+
},
|
|
2240
|
+
/**
|
|
2241
|
+
* Close a pending settlement. Only the seat named by `side` may: the receiver confirms or
|
|
2242
|
+
* rejects, the payer cancels.
|
|
2243
|
+
*/
|
|
2244
|
+
async resolve({ group: group2, me }, documentId, { status, side, action }) {
|
|
2245
|
+
const s = await this.pending(group2, documentId);
|
|
2246
|
+
if (idOf(s[side]) !== me.id)
|
|
2247
|
+
throw forbidden(ERROR_CODES.NOT_ALLOWED, "Ce n'est pas à toi de faire ça.");
|
|
2248
|
+
await strapi.db.transaction(async () => {
|
|
2249
|
+
await svc("group").lock(group2);
|
|
2250
|
+
const fresh = await settlements().findOne({ where: { id: s.id }, select: ["status"] });
|
|
2251
|
+
if (fresh.status !== SETTLEMENT_STATUS.PENDING)
|
|
2252
|
+
throw unprocessable(ERROR_CODES.SETTLEMENT_NOT_PENDING, "Règlement déjà traité.");
|
|
2253
|
+
await settlements().update({
|
|
2254
|
+
where: { id: s.id },
|
|
2255
|
+
data: { status, resolvedAt: /* @__PURE__ */ new Date(), resolvedBy: idOf(me.person) }
|
|
2256
|
+
});
|
|
2257
|
+
});
|
|
2258
|
+
await svc("audit").log({
|
|
2259
|
+
group: group2,
|
|
2260
|
+
actor: me.person,
|
|
2261
|
+
action,
|
|
2262
|
+
targetId: s.documentId,
|
|
2263
|
+
data: { amount: s.amount }
|
|
2264
|
+
});
|
|
2265
|
+
return this.one(s.id);
|
|
2266
|
+
},
|
|
2267
|
+
confirm(seat, documentId) {
|
|
2268
|
+
return this.resolve(seat, documentId, {
|
|
2269
|
+
status: SETTLEMENT_STATUS.CONFIRMED,
|
|
2270
|
+
side: "to",
|
|
2271
|
+
action: EVENT.SETTLEMENT_CONFIRMED
|
|
2272
|
+
});
|
|
2273
|
+
},
|
|
2274
|
+
reject(seat, documentId) {
|
|
2275
|
+
return this.resolve(seat, documentId, {
|
|
2276
|
+
status: SETTLEMENT_STATUS.REJECTED,
|
|
2277
|
+
side: "to",
|
|
2278
|
+
action: EVENT.SETTLEMENT_REJECTED
|
|
2279
|
+
});
|
|
2280
|
+
},
|
|
2281
|
+
cancel(seat, documentId) {
|
|
2282
|
+
return this.resolve(seat, documentId, {
|
|
2283
|
+
status: SETTLEMENT_STATUS.CANCELLED,
|
|
2284
|
+
side: "from",
|
|
2285
|
+
action: EVENT.SETTLEMENT_CANCELLED
|
|
2286
|
+
});
|
|
2287
|
+
},
|
|
2288
|
+
/**
|
|
2289
|
+
* @param {{ group?: number, status?: string, method?: string, reference?: string }} filters
|
|
2290
|
+
* @param {{ offset: number, limit: number }} page
|
|
2291
|
+
*/
|
|
2292
|
+
async list(filters, page) {
|
|
2293
|
+
const where = {};
|
|
2294
|
+
if (filters.group) where.group = filters.group;
|
|
2295
|
+
if (filters.status) where.status = filters.status;
|
|
2296
|
+
if (filters.method) where.method = filters.method;
|
|
2297
|
+
if (filters.reference) where.reference = { $containsi: String(filters.reference).trim() };
|
|
2298
|
+
const [items, total] = await Promise.all([
|
|
2299
|
+
settlements().findMany({
|
|
2300
|
+
where,
|
|
2301
|
+
populate: { ...POPULATE, group: { select: ["documentId", "name"] } },
|
|
2302
|
+
orderBy: [{ declaredAt: "desc" }, { id: "desc" }],
|
|
2303
|
+
offset: page.offset,
|
|
2304
|
+
limit: page.limit
|
|
2305
|
+
}),
|
|
2306
|
+
settlements().count({ where })
|
|
2307
|
+
]);
|
|
2308
|
+
return { items, total };
|
|
2309
|
+
}
|
|
2310
|
+
};
|
|
2311
|
+
};
|
|
2312
|
+
const ADMIN_RECENT = 50;
|
|
2313
|
+
const stats = ({ strapi }) => {
|
|
2314
|
+
const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
|
|
2315
|
+
const count = (uid, where = {}) => strapi.db.query(uid).count({ where });
|
|
2316
|
+
const table = (uid) => strapi.db.metadata.get(uid).tableName;
|
|
2317
|
+
const tally = async (uid, narrow) => {
|
|
2318
|
+
const row = await narrow(strapi.db.connection(table(uid))).count({ count: "*" }).sum({ total: "amount" }).first();
|
|
2319
|
+
return { count: Number(row?.count ?? 0), total: Number(row?.total ?? 0) };
|
|
2320
|
+
};
|
|
2321
|
+
return {
|
|
2322
|
+
async dashboard() {
|
|
2323
|
+
const since = new Date(Date.now() - DASHBOARD_DAYS * DAY_MS);
|
|
2324
|
+
const recent = { createdAt: { $gte: since } };
|
|
2325
|
+
const [
|
|
2326
|
+
people,
|
|
2327
|
+
activePeople,
|
|
2328
|
+
newPeople,
|
|
2329
|
+
groups,
|
|
2330
|
+
archived,
|
|
2331
|
+
newGroups,
|
|
2332
|
+
expenses,
|
|
2333
|
+
weekExpenses,
|
|
2334
|
+
confirmed,
|
|
2335
|
+
pending,
|
|
2336
|
+
byMethod
|
|
2337
|
+
] = await Promise.all([
|
|
2338
|
+
count(UID.PERSON),
|
|
2339
|
+
count(UID.PERSON, { lastActiveAt: { $gte: since } }),
|
|
2340
|
+
count(UID.PERSON, recent),
|
|
2341
|
+
count(UID.GROUP),
|
|
2342
|
+
count(UID.GROUP, { archivedAt: { $notNull: true } }),
|
|
2343
|
+
count(UID.GROUP, recent),
|
|
2344
|
+
tally(UID.EXPENSE, (q) => q.whereNull("deleted_at")),
|
|
2345
|
+
tally(UID.EXPENSE, (q) => q.whereNull("deleted_at").where("spent_at", ">=", since)),
|
|
2346
|
+
tally(UID.SETTLEMENT, (q) => q.where({ status: SETTLEMENT_STATUS.CONFIRMED })),
|
|
2347
|
+
tally(UID.SETTLEMENT, (q) => q.where({ status: SETTLEMENT_STATUS.PENDING })),
|
|
2348
|
+
strapi.db.connection(table(UID.SETTLEMENT)).where({ status: SETTLEMENT_STATUS.CONFIRMED }).groupBy("method").select("method").count({ count: "*" }).sum({ total: "amount" })
|
|
2349
|
+
]);
|
|
2350
|
+
return {
|
|
2351
|
+
days: DASHBOARD_DAYS,
|
|
2352
|
+
people: { total: people, active: activePeople, new: newPeople },
|
|
2353
|
+
groups: { total: groups, archived, new: newGroups },
|
|
2354
|
+
expenses: { ...expenses, recent: weekExpenses },
|
|
2355
|
+
settlements: {
|
|
2356
|
+
confirmed,
|
|
2357
|
+
pending,
|
|
2358
|
+
byMethod: byMethod.map((m) => ({
|
|
2359
|
+
method: m.method,
|
|
2360
|
+
count: Number(m.count),
|
|
2361
|
+
total: Number(m.total ?? 0)
|
|
2362
|
+
}))
|
|
2363
|
+
}
|
|
2364
|
+
};
|
|
2365
|
+
},
|
|
2366
|
+
/** One group with its books, for support: phones masked. */
|
|
2367
|
+
async group(documentId) {
|
|
2368
|
+
const format2 = svc("format");
|
|
2369
|
+
const group2 = await svc("group").byDocumentId(documentId);
|
|
2370
|
+
const page = { offset: 0, limit: ADMIN_RECENT };
|
|
2371
|
+
const [books, expenses, settlements] = await Promise.all([
|
|
2372
|
+
svc("ledger").of(group2),
|
|
2373
|
+
svc("expense").list(group2, page),
|
|
2374
|
+
svc("settlement").list({ group: group2.id }, page)
|
|
2375
|
+
]);
|
|
2376
|
+
return {
|
|
2377
|
+
...format2.group(group2),
|
|
2378
|
+
createdAt: group2.createdAt,
|
|
2379
|
+
memberCount: books.active.length,
|
|
2380
|
+
expenseCount: books.expenseCount,
|
|
2381
|
+
total: books.total,
|
|
2382
|
+
members: books.seats.map((s) => ({
|
|
2383
|
+
...format2.adminMember(s),
|
|
2384
|
+
balance: books.balanceOf(s.id)
|
|
2385
|
+
})),
|
|
2386
|
+
payments: books.payments.map((p) => ({
|
|
2387
|
+
from: format2.member(books.seatById.get(p.from)),
|
|
2388
|
+
to: format2.member(books.seatById.get(p.to)),
|
|
2389
|
+
amount: p.amount
|
|
2390
|
+
})),
|
|
2391
|
+
expenses: expenses.items.map((e) => format2.expense(e, NOBODY, null)),
|
|
2392
|
+
settlements: settlements.items.map((s) => format2.settlement(s, NOBODY, null))
|
|
2393
|
+
};
|
|
2394
|
+
},
|
|
2395
|
+
/** The groups a person sits in. */
|
|
2396
|
+
async groupsOf(person2) {
|
|
2397
|
+
const seats = await strapi.db.query(UID.MEMBER).findMany({
|
|
2398
|
+
where: { person: person2.id },
|
|
2399
|
+
populate: { group: true },
|
|
2400
|
+
orderBy: { id: "desc" }
|
|
2401
|
+
});
|
|
2402
|
+
return seats.filter((s) => s.group).map((s) => ({
|
|
2403
|
+
...svc("format").group(s.group),
|
|
2404
|
+
role: s.role,
|
|
2405
|
+
hasLeft: Boolean(s.leftAt)
|
|
2406
|
+
}));
|
|
2407
|
+
}
|
|
2408
|
+
};
|
|
2409
|
+
};
|
|
2410
|
+
const services = {
|
|
2411
|
+
settings,
|
|
2412
|
+
audit,
|
|
2413
|
+
format,
|
|
2414
|
+
person,
|
|
2415
|
+
ledger,
|
|
2416
|
+
group,
|
|
2417
|
+
member,
|
|
2418
|
+
expense,
|
|
2419
|
+
settlement,
|
|
2420
|
+
view,
|
|
2421
|
+
stats
|
|
2422
|
+
};
|
|
2423
|
+
const index = {
|
|
2424
|
+
register,
|
|
2425
|
+
bootstrap,
|
|
2426
|
+
config,
|
|
2427
|
+
controllers,
|
|
2428
|
+
contentTypes,
|
|
2429
|
+
middlewares,
|
|
2430
|
+
policies,
|
|
2431
|
+
routes,
|
|
2432
|
+
services
|
|
2433
|
+
};
|
|
2434
|
+
module.exports = index;
|