@sonatel-os/strapi-plugin-split 0.4.0 → 0.6.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.
@@ -25,7 +25,8 @@ const RBAC = Object.freeze({
25
25
  PEOPLE_WRITE: "people.write",
26
26
  SETTLEMENTS_READ: "settlements.read",
27
27
  AUDIT_READ: "audit.read",
28
- SETTINGS_READ: "settings.read"
28
+ SETTINGS_READ: "settings.read",
29
+ SETTINGS_WRITE: "settings.write"
29
30
  });
30
31
  const SPLIT_MODE = Object.freeze({ EQUAL: "equal", WEIGHTED: "weighted", FREE: "free" });
31
32
  const ROLE = Object.freeze({ OWNER: "owner", MEMBER: "member" });
@@ -81,12 +82,20 @@ const ORDER_STATUS = Object.freeze({
81
82
  const ORDER_MAX_ITEMS = 30;
82
83
  const ORDER_MAX_QUANTITY = 99;
83
84
  const ORDER_LIST_SIZE = 20;
85
+ const ORDER_NOTE_MAX = 80;
86
+ const ORDER_RECENT_MS = 24 * 60 * 60 * 1e3;
84
87
  const DEFAULT_LIMITS = Object.freeze({
85
- maxGroupsPerPerson: 50,
86
- maxMembersPerGroup: 50,
88
+ maxGroupsPerPerson: 150,
89
+ maxMembersPerGroup: 150,
87
90
  /** Largest single expense or settlement, in the currency's smallest unit. */
88
- maxAmount: 5e7
91
+ maxAmount: 15e7
89
92
  });
93
+ const LIMIT_CEILINGS = Object.freeze({
94
+ maxGroupsPerPerson: 1e3,
95
+ maxMembersPerGroup: 500,
96
+ maxAmount: 2e9
97
+ });
98
+ const LIMITS_STORE_KEY = "limits";
90
99
  const DEFAULT_INVITE_PREFIX = "SPL";
91
100
  const DEFAULT_COUNTRY_CODE = "";
92
101
  const CODE_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
@@ -143,6 +152,12 @@ const ACTIONS = [
143
152
  category: PLUGIN_DISPLAY_NAME,
144
153
  uid: RBAC.SETTINGS_READ,
145
154
  displayName: "Read settings"
155
+ },
156
+ {
157
+ section: "settings",
158
+ category: PLUGIN_DISPLAY_NAME,
159
+ uid: RBAC.SETTINGS_WRITE,
160
+ displayName: "Change the limits"
146
161
  }
147
162
  ].map((a) => ({ ...a, pluginName: PLUGIN_ID }));
148
163
  const UNIQUE_COLUMNS = [
@@ -844,7 +859,7 @@ const info = {
844
859
  singularName: "order-line",
845
860
  pluralName: "order-lines",
846
861
  displayName: "Split Order Line",
847
- description: "How many of one item one member takes."
862
+ description: "How many of one item one member takes, and what they ask about it."
848
863
  };
849
864
  const options = {
850
865
  draftAndPublish: false
@@ -877,6 +892,10 @@ const attributes = {
877
892
  type: "integer",
878
893
  required: true,
879
894
  min: 1
895
+ },
896
+ note: {
897
+ type: "string",
898
+ maxLength: 80
880
899
  }
881
900
  };
882
901
  const schema = {
@@ -1094,6 +1113,7 @@ const app = ({ strapi }) => {
1094
1113
  ok(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)));
1095
1114
  }),
1096
1115
  // ── Orders ───────────────────────────────────────────────────────────
1116
+ currentOrders: handle(strapi, async (ctx) => ok(ctx, await svc("order").current(viewer(ctx)))),
1097
1117
  orders: handle(
1098
1118
  strapi,
1099
1119
  async (ctx) => ok(ctx, await svc("order").list(await seat(ctx), viewer(ctx)))
@@ -1235,13 +1255,17 @@ const view = ({ strapi }) => {
1235
1255
  const debts = perGroup.flatMap((g) => g.debts).sort((a, b) => b.amount - a.amount);
1236
1256
  const credits = perGroup.flatMap((g) => g.credits).sort((a, b) => b.amount - a.amount);
1237
1257
  const sum = (list) => list.reduce((total, item) => total + item.amount, 0);
1238
- const invitations = await svc("member").invitations(viewer);
1258
+ const [invitations, orders] = await Promise.all([
1259
+ svc("member").invitations(viewer),
1260
+ svc("order").current(viewer)
1261
+ ]);
1239
1262
  return {
1240
1263
  owe: sum(debts),
1241
1264
  owed: sum(credits),
1242
1265
  debts,
1243
1266
  credits,
1244
1267
  invitations: invitations.map((seat) => format2.invitation(seat)),
1268
+ orders,
1245
1269
  groups: perGroup.map((g) => g.summary).sort((a, b) => new Date(b.lastActivityAt ?? 0) - new Date(a.lastActivityAt ?? 0))
1246
1270
  };
1247
1271
  },
@@ -1395,8 +1419,16 @@ const admin$1 = ({ strapi }) => {
1395
1419
  countryCode: settings2.countryCode(),
1396
1420
  people: settings2.people(),
1397
1421
  methods: settings2.methods(),
1398
- limits: settings2.limits()
1422
+ limits: await settings2.limits(),
1423
+ limitCeilings: LIMIT_CEILINGS
1399
1424
  });
1425
+ }),
1426
+ setLimits: handle(strapi, async (ctx) => {
1427
+ const limits = await svc("settings").setLimits(body(ctx));
1428
+ strapi.log.info(
1429
+ `${LOG_PREFIX} limits set to ${JSON.stringify(limits)} by admin ${ctx.state.user?.id}`
1430
+ );
1431
+ ok(ctx, limits);
1400
1432
  })
1401
1433
  };
1402
1434
  };
@@ -1480,6 +1512,7 @@ const contentApi = [
1480
1512
  route$1("POST", "/groups/:group/settlements/:settlement/reject", "rejectSettlement"),
1481
1513
  route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement"),
1482
1514
  // orders: priced items the members order from; closing one writes an expense
1515
+ route$1("GET", "/orders", "currentOrders"),
1483
1516
  route$1("GET", "/groups/:group/orders", "orders"),
1484
1517
  route$1("POST", "/groups/:group/orders", "createOrder"),
1485
1518
  route$1("GET", "/groups/:group/orders/:order", "order"),
@@ -1512,14 +1545,23 @@ const admin = [
1512
1545
  route("PUT", "/people/:id/active", "setPersonActive", RBAC.PEOPLE_WRITE),
1513
1546
  route("GET", "/settlements", "settlements", RBAC.SETTLEMENTS_READ),
1514
1547
  route("GET", "/events", "events", RBAC.AUDIT_READ),
1515
- route("GET", "/settings", "settings", RBAC.SETTINGS_READ)
1548
+ route("GET", "/settings", "settings", RBAC.SETTINGS_READ),
1549
+ route("PUT", "/settings/limits", "setLimits", RBAC.SETTINGS_WRITE)
1516
1550
  ];
1517
1551
  const routes = {
1518
1552
  "content-api": { type: "content-api", routes: contentApi },
1519
1553
  admin: { type: "admin", routes: admin }
1520
1554
  };
1521
1555
  const DEFAULT_PEOPLE = Object.freeze({ idHeader: "x-person-id", nameHeader: "x-person-name" });
1556
+ const LIMIT_KEYS = Object.keys(DEFAULT_LIMITS);
1557
+ const withinCeiling = (key, value) => Number.isInteger(value) && value > 0 && value <= LIMIT_CEILINGS[key];
1558
+ const usable = (limits) => Object.fromEntries(
1559
+ LIMIT_KEYS.filter((key) => withinCeiling(key, limits?.[key])).map((key) => [key, limits[key]])
1560
+ );
1522
1561
  const settings = ({ strapi }) => ({
1562
+ store() {
1563
+ return strapi.store({ type: "plugin", name: PLUGIN_ID });
1564
+ },
1523
1565
  /** @returns {Object} the full plugin config */
1524
1566
  all() {
1525
1567
  return strapi.config.get(`plugin::${PLUGIN_ID}`) ?? {};
@@ -1546,8 +1588,34 @@ const settings = ({ strapi }) => ({
1546
1588
  Object.entries(methods).map(([name, m]) => [name, { instant: Boolean(m?.instant) }])
1547
1589
  );
1548
1590
  },
1549
- limits() {
1591
+ /** The limits from the configuration file, before anything set in the back office. */
1592
+ configuredLimits() {
1550
1593
  return { ...DEFAULT_LIMITS, ...this.all().limits ?? {} };
1594
+ },
1595
+ /**
1596
+ * The limits in force: what an administrator set, else the configuration file, else the defaults.
1597
+ * @returns {Promise<{ maxGroupsPerPerson: number, maxMembersPerGroup: number, maxAmount: number }>}
1598
+ */
1599
+ async limits() {
1600
+ const saved = await this.store().get({ key: LIMITS_STORE_KEY });
1601
+ return { ...this.configuredLimits(), ...usable(saved) };
1602
+ },
1603
+ /**
1604
+ * Sets the limits from the back office. Every limit is given, each a whole number from 1 to its
1605
+ * ceiling. Lowering one never touches what already exists: it only refuses what comes next.
1606
+ * @param {Object} input
1607
+ * @returns {Promise<Object>} the limits now in force
1608
+ */
1609
+ async setLimits(input) {
1610
+ const refused = LIMIT_KEYS.filter((key) => !withinCeiling(key, input?.[key]));
1611
+ if (refused.length > 0)
1612
+ throw badRequest(
1613
+ ERROR_CODES.VALIDATION,
1614
+ "Chaque limite est un entier entre 1 et son plafond.",
1615
+ { fields: refused, ceilings: LIMIT_CEILINGS }
1616
+ );
1617
+ await this.store().set({ key: LIMITS_STORE_KEY, value: usable(input) });
1618
+ return this.limits();
1551
1619
  }
1552
1620
  });
1553
1621
  const audit = ({ strapi }) => ({
@@ -1995,7 +2063,7 @@ const group = ({ strapi }) => {
1995
2063
  async create(person2, input) {
1996
2064
  const name = cleanName(input.name);
1997
2065
  if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
1998
- const limits = svc("settings").limits();
2066
+ const limits = await svc("settings").limits();
1999
2067
  const held = await members().count({ where: { person: person2.id, ...HELD } });
2000
2068
  if (held >= limits.maxGroupsPerPerson)
2001
2069
  throw unprocessable(
@@ -2072,7 +2140,7 @@ const group = ({ strapi }) => {
2072
2140
  });
2073
2141
  if (existing && !existing.joinedAt) await svc("member").take({ ...existing, group: group2 }, person2);
2074
2142
  if (existing) return group2;
2075
- const limits = svc("settings").limits();
2143
+ const limits = await svc("settings").limits();
2076
2144
  const count = await members().count({ where: { group: group2.id, leftAt: { $null: true } } });
2077
2145
  if (count >= limits.maxMembersPerGroup)
2078
2146
  throw unprocessable(ERROR_CODES.MEMBER_LIMIT, "Ce groupe est complet.");
@@ -2180,7 +2248,7 @@ const member = ({ strapi }) => {
2180
2248
  */
2181
2249
  async add({ group: group2, me }, raw) {
2182
2250
  const input = this.parse(raw);
2183
- const limits = svc("settings").limits();
2251
+ const limits = await svc("settings").limits();
2184
2252
  const seats = await members().findMany({
2185
2253
  where: { group: group2.id, leftAt: { $null: true } },
2186
2254
  populate: { person: true }
@@ -2395,10 +2463,10 @@ const expense = ({ strapi }) => {
2395
2463
  * @returns {{ label: string, category: string|null, amount: number, mode: string, spentAt: Date,
2396
2464
  * paidBy: number, shares: Array<{ member: number, amount: number, weight: number }> }}
2397
2465
  */
2398
- parse(input, active) {
2466
+ async parse(input, active) {
2399
2467
  const label2 = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
2400
2468
  if (!label2) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
2401
- const { maxAmount } = svc("settings").limits();
2469
+ const { maxAmount } = await svc("settings").limits();
2402
2470
  const amount = input?.amount;
2403
2471
  if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
2404
2472
  throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
@@ -2454,7 +2522,7 @@ const expense = ({ strapi }) => {
2454
2522
  const earlier = await this.replayed(group2, clientRef);
2455
2523
  if (earlier) return { expense: earlier, replayed: true };
2456
2524
  const { active } = await svc("ledger").of(group2);
2457
- const { shares: list, ...data } = this.parse(input, active);
2525
+ const { shares: list, ...data } = await this.parse(input, active);
2458
2526
  try {
2459
2527
  const created = await strapi.db.transaction(async () => {
2460
2528
  await svc("group").lock(group2);
@@ -2497,7 +2565,7 @@ const expense = ({ strapi }) => {
2497
2565
  const { group: group2, me } = seat;
2498
2566
  const expense2 = await this.editable(seat, documentId);
2499
2567
  const { active } = await svc("ledger").of(group2);
2500
- const { shares: list, ...data } = this.parse(input, active);
2568
+ const { shares: list, ...data } = await this.parse(input, active);
2501
2569
  await strapi.db.transaction(async () => {
2502
2570
  await svc("group").lock(group2);
2503
2571
  await expenses().update({ where: { id: expense2.id }, data });
@@ -2560,7 +2628,7 @@ const settlement = ({ strapi }) => {
2560
2628
  * (`to`) when the caller pays, the one who paid (`from`) when the caller received.
2561
2629
  */
2562
2630
  async parse({ group: group2, me }, input) {
2563
- const { maxAmount } = svc("settings").limits();
2631
+ const { maxAmount } = await svc("settings").limits();
2564
2632
  const amount = input?.amount;
2565
2633
  if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
2566
2634
  throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
@@ -2772,8 +2840,10 @@ const orderTotals = ({ items, lines, deliveryFee = 0 }) => {
2772
2840
  };
2773
2841
  const LINE_POPULATE = { item: { select: ["id"] }, member: { select: ["id"] } };
2774
2842
  const ORDER_POPULATE = { organizer: { select: ["id"] } };
2843
+ const CURRENT_POPULATE = { group: { select: ["id"] }, organizer: { populate: { person: true } } };
2775
2844
  const iso = (date) => date ? new Date(date).toISOString() : null;
2776
- const label = (raw) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, LABEL_MAX);
2845
+ const tidy = (raw, max) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, max);
2846
+ const label = (raw) => tidy(raw, LABEL_MAX);
2777
2847
  const invalid = (message, details) => badRequest(ERROR_CODES.VALIDATION, message, details);
2778
2848
  const expenseRefOf = (order2) => `order:${order2.documentId}`;
2779
2849
  const order = ({ strapi }) => {
@@ -2795,10 +2865,10 @@ const order = ({ strapi }) => {
2795
2865
  return date;
2796
2866
  },
2797
2867
  /** What the organiser sent, checked. */
2798
- parse(input) {
2868
+ async parse(input) {
2799
2869
  const title = label(input?.title);
2800
2870
  if (!title) throw invalid("Donne un nom à la commande.");
2801
- const { maxAmount } = svc("settings").limits();
2871
+ const { maxAmount } = await svc("settings").limits();
2802
2872
  const list = Array.isArray(input?.items) ? input.items : [];
2803
2873
  if (list.length === 0 || list.length > ORDER_MAX_ITEMS)
2804
2874
  throw invalid(`Entre 1 et ${ORDER_MAX_ITEMS} articles.`, { max: ORDER_MAX_ITEMS });
@@ -2813,7 +2883,7 @@ const order = ({ strapi }) => {
2813
2883
  * @param {{ title: string, closesAt?: string, items: Array<{ label: string, price: number }> }} input
2814
2884
  */
2815
2885
  async create({ group: group2, me }, input) {
2816
- const data = this.parse(input);
2886
+ const data = await this.parse(input);
2817
2887
  const order2 = await strapi.db.transaction(async () => {
2818
2888
  const created = await orders().create({
2819
2889
  data: {
@@ -2859,7 +2929,8 @@ const order = ({ strapi }) => {
2859
2929
  lines: taken.map((l) => ({
2860
2930
  item: idOf(l.item),
2861
2931
  member: idOf(l.member),
2862
- quantity: l.quantity
2932
+ quantity: l.quantity,
2933
+ note: l.note || null
2863
2934
  }))
2864
2935
  };
2865
2936
  },
@@ -2876,7 +2947,11 @@ const order = ({ strapi }) => {
2876
2947
  status: order2.status
2877
2948
  });
2878
2949
  },
2879
- /** The quantities sent, by item row id; unknown items and odd quantities are refused. */
2950
+ /**
2951
+ * What was sent, by item row id: how many, and the precision given with it if any. Unknown
2952
+ * items and odd quantities are refused.
2953
+ * @returns {Map<number, { quantity: number, note: string|null }>}
2954
+ */
2880
2955
  quantities(input, offered) {
2881
2956
  const byDoc = new Map(offered.map((item) => [item.documentId, item.id]));
2882
2957
  const list = Array.isArray(input?.lines) ? input.lines : null;
@@ -2890,7 +2965,7 @@ const order = ({ strapi }) => {
2890
2965
  throw invalid(`Une quantité va de 0 à ${ORDER_MAX_QUANTITY}.`, {
2891
2966
  max: ORDER_MAX_QUANTITY
2892
2967
  });
2893
- wanted.set(item, quantity);
2968
+ wanted.set(item, { quantity, note: tidy(raw?.note, ORDER_NOTE_MAX) || null });
2894
2969
  }
2895
2970
  return wanted;
2896
2971
  },
@@ -2899,7 +2974,7 @@ const order = ({ strapi }) => {
2899
2974
  * (someone who told them, someone without the app), and still can after the closing time.
2900
2975
  * @param {{ group: Object, me: Object }} seat the caller's
2901
2976
  * @param {string} documentId the order
2902
- * @param {{ member?: string, lines: Array<{ item: string, quantity: number }> }} input
2977
+ * @param {{ member?: string, lines: Array<{ item: string, quantity: number, note?: string }> }} input
2903
2978
  */
2904
2979
  async setLines({ group: group2, me }, documentId, input) {
2905
2980
  const order2 = await this.find(group2, documentId);
@@ -2916,10 +2991,10 @@ const order = ({ strapi }) => {
2916
2991
  const wanted = this.quantities(input, offered);
2917
2992
  await strapi.db.transaction(async () => {
2918
2993
  await lines().deleteMany({ where: { order: order2.id, member: target.id } });
2919
- for (const [item, quantity] of wanted)
2994
+ for (const [item, { quantity, note }] of wanted)
2920
2995
  if (quantity > 0)
2921
2996
  await lines().create({
2922
- data: { order: order2.id, item, member: target.id, quantity }
2997
+ data: { order: order2.id, item, member: target.id, quantity, note }
2923
2998
  });
2924
2999
  });
2925
3000
  return order2;
@@ -2937,7 +3012,7 @@ const order = ({ strapi }) => {
2937
3012
  this.assertOrganizer(order2, me);
2938
3013
  if (order2.status === ORDER_STATUS.CLOSED) return order2;
2939
3014
  this.assertOpen(order2);
2940
- const { maxAmount } = svc("settings").limits();
3015
+ const { maxAmount } = await svc("settings").limits();
2941
3016
  const deliveryFee = input?.deliveryFee ?? 0;
2942
3017
  if (!Number.isInteger(deliveryFee) || deliveryFee < 0 || deliveryFee > maxAmount)
2943
3018
  throw invalid("Frais de livraison invalides.", { maxAmount });
@@ -3034,7 +3109,7 @@ const order = ({ strapi }) => {
3034
3109
  yours
3035
3110
  };
3036
3111
  if (!detailed) return summary;
3037
- const takenBy = (member2) => taken.filter((l) => l.member === member2 && docOf.has(l.item)).map((l) => ({ item: docOf.get(l.item), quantity: l.quantity }));
3112
+ const takenBy = (member2) => taken.filter((l) => l.member === member2 && docOf.has(l.item)).map((l) => ({ item: docOf.get(l.item), quantity: l.quantity, note: l.note }));
3038
3113
  const quantityOf = (item, member2) => taken.filter((l) => l.item === item && (member2 == null || l.member === member2)).reduce((sum, l) => sum + l.quantity, 0);
3039
3114
  return {
3040
3115
  ...summary,
@@ -3052,6 +3127,60 @@ const order = ({ strapi }) => {
3052
3127
  }))
3053
3128
  };
3054
3129
  },
3130
+ /**
3131
+ * The orders a person should know about, across their groups: the open ones, and those that
3132
+ * closed or were dropped within the last day. Light enough to be asked often: no books read.
3133
+ * @param {Object} viewer the person asking
3134
+ * @param {Date} [now]
3135
+ * @returns {Promise<Object[]>} the latest first
3136
+ */
3137
+ async current(viewer, now = /* @__PURE__ */ new Date()) {
3138
+ const seats = await svc("group").seatsOf(viewer);
3139
+ if (seats.length === 0) return [];
3140
+ const seatByGroup = new Map(seats.map((s) => [s.group.id, s]));
3141
+ const rows = await orders().findMany({
3142
+ where: {
3143
+ group: { id: { $in: [...seatByGroup.keys()] } },
3144
+ $or: [
3145
+ { status: ORDER_STATUS.OPEN },
3146
+ { closedAt: { $gte: new Date(now.getTime() - ORDER_RECENT_MS) } }
3147
+ ]
3148
+ },
3149
+ populate: CURRENT_POPULATE,
3150
+ orderBy: [{ id: "desc" }]
3151
+ });
3152
+ return Promise.all(
3153
+ rows.map((order2) => this.brief(order2, seatByGroup.get(idOf(order2.group)), viewer))
3154
+ );
3155
+ },
3156
+ /**
3157
+ * An order in a few facts, for someone who is not looking at it: where, whose, where it
3158
+ * stands and what the viewer took.
3159
+ * @param {Object} order `organizer.person` populated
3160
+ * @param {Object} me the viewer's seat, `group` populated
3161
+ * @param {Object} viewer the person asking
3162
+ */
3163
+ async brief(order2, me, viewer) {
3164
+ const { items: offered, lines: taken } = await this.load(order2);
3165
+ const totals = orderTotals({ items: offered, lines: taken, deliveryFee: order2.deliveryFee });
3166
+ const none = { quantity: 0, subtotal: 0, delivery: 0, total: 0 };
3167
+ const { member: _mine, ...yours } = totals.people.find((p) => p.member === me.id) ?? none;
3168
+ return {
3169
+ id: order2.documentId,
3170
+ group: { id: me.group.documentId, name: me.group.name },
3171
+ title: order2.title,
3172
+ status: order2.status,
3173
+ openedAt: iso(order2.createdAt),
3174
+ closesAt: iso(order2.closesAt),
3175
+ closedAt: iso(order2.closedAt),
3176
+ acceptsOrders: this.accepts(order2),
3177
+ isOrganizer: idOf(order2.organizer) === me.id,
3178
+ organizer: order2.organizer ? svc("format").member(order2.organizer, viewer) : null,
3179
+ participantCount: totals.people.length,
3180
+ total: totals.total,
3181
+ yours
3182
+ };
3183
+ },
3055
3184
  /** The group's orders as a member reads them: the open ones first, then the latest. */
3056
3185
  async list(seat, viewer) {
3057
3186
  const rows = await orders().findMany({