@sonatel-os/strapi-plugin-split 0.2.0 → 0.4.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.
@@ -10,7 +10,10 @@ const UID = Object.freeze({
10
10
  EXPENSE: "plugin::split.expense",
11
11
  SHARE: "plugin::split.share",
12
12
  SETTLEMENT: "plugin::split.settlement",
13
- EVENT: "plugin::split.event"
13
+ EVENT: "plugin::split.event",
14
+ ORDER: "plugin::split.order",
15
+ ORDER_ITEM: "plugin::split.order-item",
16
+ ORDER_LINE: "plugin::split.order-line"
14
17
  });
15
18
  const RBAC = Object.freeze({
16
19
  ACCESS: "access",
@@ -26,6 +29,12 @@ const RBAC = Object.freeze({
26
29
  });
27
30
  const SPLIT_MODE = Object.freeze({ EQUAL: "equal", WEIGHTED: "weighted", FREE: "free" });
28
31
  const ROLE = Object.freeze({ OWNER: "owner", MEMBER: "member" });
32
+ const INVITE = Object.freeze({
33
+ /** Added by a member; the person has not said yes or no. */
34
+ PENDING: "pending",
35
+ /** The person said no, and the seat stays as a name because it is on the books. */
36
+ DECLINED: "declined"
37
+ });
29
38
  const SETTLEMENT_STATUS = Object.freeze({
30
39
  /** Declared; the receiver has not confirmed yet. Does not move balances. */
31
40
  PENDING: "pending",
@@ -47,6 +56,7 @@ const EVENT = Object.freeze({
47
56
  GROUP_ARCHIVED: "group.archived",
48
57
  MEMBER_ADDED: "member.added",
49
58
  MEMBER_JOINED: "member.joined",
59
+ MEMBER_DECLINED: "member.declined",
50
60
  MEMBER_LEFT: "member.left",
51
61
  MEMBER_REMOVED: "member.removed",
52
62
  EXPENSE_CREATED: "expense.created",
@@ -55,8 +65,22 @@ const EVENT = Object.freeze({
55
65
  SETTLEMENT_CREATED: "settlement.created",
56
66
  SETTLEMENT_CONFIRMED: "settlement.confirmed",
57
67
  SETTLEMENT_REJECTED: "settlement.rejected",
58
- SETTLEMENT_CANCELLED: "settlement.cancelled"
68
+ SETTLEMENT_CANCELLED: "settlement.cancelled",
69
+ ORDER_OPENED: "order.opened",
70
+ ORDER_CLOSED: "order.closed",
71
+ ORDER_CANCELLED: "order.cancelled"
72
+ });
73
+ const ORDER_STATUS = Object.freeze({
74
+ /** Members add and change what they take, until the closing time if there is one. */
75
+ OPEN: "open",
76
+ /** The organiser closed it: it became one expense. */
77
+ CLOSED: "closed",
78
+ /** The organiser dropped it; nothing was written. */
79
+ CANCELLED: "cancelled"
59
80
  });
81
+ const ORDER_MAX_ITEMS = 30;
82
+ const ORDER_MAX_QUANTITY = 99;
83
+ const ORDER_LIST_SIZE = 20;
60
84
  const DEFAULT_LIMITS = Object.freeze({
61
85
  maxGroupsPerPerson: 50,
62
86
  maxMembersPerGroup: 50,
@@ -89,6 +113,7 @@ const ERROR_CODES = Object.freeze({
89
113
  NOT_A_MEMBER: "NOT_A_MEMBER",
90
114
  NOT_ALLOWED: "NOT_ALLOWED",
91
115
  INVITE_INVALID: "INVITE_INVALID",
116
+ INVITATION_NOT_FOUND: "INVITATION_NOT_FOUND",
92
117
  MEMBER_NOT_FOUND: "MEMBER_NOT_FOUND",
93
118
  MEMBER_EXISTS: "MEMBER_EXISTS",
94
119
  MEMBER_LIMIT: "MEMBER_LIMIT",
@@ -98,7 +123,10 @@ const ERROR_CODES = Object.freeze({
98
123
  SETTLEMENT_NOT_FOUND: "SETTLEMENT_NOT_FOUND",
99
124
  SETTLEMENT_EXCEEDS_DEBT: "SETTLEMENT_EXCEEDS_DEBT",
100
125
  SETTLEMENT_NOT_PENDING: "SETTLEMENT_NOT_PENDING",
101
- METHOD_UNKNOWN: "METHOD_UNKNOWN"
126
+ METHOD_UNKNOWN: "METHOD_UNKNOWN",
127
+ ORDER_NOT_FOUND: "ORDER_NOT_FOUND",
128
+ ORDER_CLOSED: "ORDER_CLOSED",
129
+ ORDER_EMPTY: "ORDER_EMPTY"
102
130
  });
103
131
  const ACTIONS = [
104
132
  { section: "plugins", uid: RBAC.ACCESS, displayName: `Access the ${PLUGIN_DISPLAY_NAME} module` },
@@ -211,18 +239,18 @@ const config = {
211
239
  }
212
240
  }
213
241
  };
214
- const kind$6 = "collectionType";
215
- const collectionName$6 = "split_people";
216
- const info$6 = {
242
+ const kind$9 = "collectionType";
243
+ const collectionName$9 = "split_people";
244
+ const info$9 = {
217
245
  singularName: "person",
218
246
  pluralName: "people",
219
247
  displayName: "Split Person",
220
248
  description: "Someone using the ledger, identified by the external id the host sends in the person header."
221
249
  };
222
- const options$6 = {
250
+ const options$9 = {
223
251
  draftAndPublish: false
224
252
  };
225
- const pluginOptions$6 = {
253
+ const pluginOptions$9 = {
226
254
  "content-manager": {
227
255
  visible: false
228
256
  },
@@ -230,7 +258,7 @@ const pluginOptions$6 = {
230
258
  visible: false
231
259
  }
232
260
  };
233
- const attributes$6 = {
261
+ const attributes$9 = {
234
262
  externalId: {
235
263
  type: "string",
236
264
  maxLength: 190,
@@ -254,6 +282,10 @@ const attributes$6 = {
254
282
  lastActiveAt: {
255
283
  type: "datetime"
256
284
  },
285
+ autoAcceptInvites: {
286
+ type: "boolean",
287
+ "default": false
288
+ },
257
289
  memberships: {
258
290
  type: "relation",
259
291
  relation: "oneToMany",
@@ -261,27 +293,27 @@ const attributes$6 = {
261
293
  mappedBy: "person"
262
294
  }
263
295
  };
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 = {
296
+ const schema$9 = {
297
+ kind: kind$9,
298
+ collectionName: collectionName$9,
299
+ info: info$9,
300
+ options: options$9,
301
+ pluginOptions: pluginOptions$9,
302
+ attributes: attributes$9
303
+ };
304
+ const person$2 = { schema: schema$9 };
305
+ const kind$8 = "collectionType";
306
+ const collectionName$8 = "split_groups";
307
+ const info$8 = {
276
308
  singularName: "group",
277
309
  pluralName: "groups",
278
310
  displayName: "Split Group",
279
311
  description: "People sharing expenses."
280
312
  };
281
- const options$5 = {
313
+ const options$8 = {
282
314
  draftAndPublish: false
283
315
  };
284
- const pluginOptions$5 = {
316
+ const pluginOptions$8 = {
285
317
  "content-manager": {
286
318
  visible: false
287
319
  },
@@ -289,7 +321,7 @@ const pluginOptions$5 = {
289
321
  visible: false
290
322
  }
291
323
  };
292
- const attributes$5 = {
324
+ const attributes$8 = {
293
325
  name: {
294
326
  type: "string",
295
327
  maxLength: 80,
@@ -319,27 +351,27 @@ const attributes$5 = {
319
351
  mappedBy: "group"
320
352
  }
321
353
  };
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 = {
354
+ const schema$8 = {
355
+ kind: kind$8,
356
+ collectionName: collectionName$8,
357
+ info: info$8,
358
+ options: options$8,
359
+ pluginOptions: pluginOptions$8,
360
+ attributes: attributes$8
361
+ };
362
+ const group$1 = { schema: schema$8 };
363
+ const kind$7 = "collectionType";
364
+ const collectionName$7 = "split_members";
365
+ const info$7 = {
334
366
  singularName: "member",
335
367
  pluralName: "members",
336
368
  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."
369
+ description: "A seat in a group: a registered person who joined or was invited and has not answered yet, or someone a member added by name (and maybe phone) who has not opened the app yet."
338
370
  };
339
- const options$4 = {
371
+ const options$7 = {
340
372
  draftAndPublish: false
341
373
  };
342
- const pluginOptions$4 = {
374
+ const pluginOptions$7 = {
343
375
  "content-manager": {
344
376
  visible: false
345
377
  },
@@ -347,7 +379,7 @@ const pluginOptions$4 = {
347
379
  visible: false
348
380
  }
349
381
  };
350
- const attributes$4 = {
382
+ const attributes$7 = {
351
383
  group: {
352
384
  type: "relation",
353
385
  relation: "manyToOne",
@@ -384,29 +416,37 @@ const attributes$4 = {
384
416
  },
385
417
  leftAt: {
386
418
  type: "datetime"
419
+ },
420
+ invitedBy: {
421
+ type: "relation",
422
+ relation: "manyToOne",
423
+ target: "plugin::split.person"
424
+ },
425
+ declinedAt: {
426
+ type: "datetime"
387
427
  }
388
428
  };
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
429
+ const schema$7 = {
430
+ kind: kind$7,
431
+ collectionName: collectionName$7,
432
+ info: info$7,
433
+ options: options$7,
434
+ pluginOptions: pluginOptions$7,
435
+ attributes: attributes$7
396
436
  };
397
- const member$1 = { schema: schema$4 };
398
- const kind$3 = "collectionType";
399
- const collectionName$3 = "split_expenses";
400
- const info$3 = {
437
+ const member$1 = { schema: schema$7 };
438
+ const kind$6 = "collectionType";
439
+ const collectionName$6 = "split_expenses";
440
+ const info$6 = {
401
441
  singularName: "expense",
402
442
  pluralName: "expenses",
403
443
  displayName: "Split Expense",
404
444
  description: "Something one member paid for the others."
405
445
  };
406
- const options$3 = {
446
+ const options$6 = {
407
447
  draftAndPublish: false
408
448
  };
409
- const pluginOptions$3 = {
449
+ const pluginOptions$6 = {
410
450
  "content-manager": {
411
451
  visible: false
412
452
  },
@@ -414,7 +454,7 @@ const pluginOptions$3 = {
414
454
  visible: false
415
455
  }
416
456
  };
417
- const attributes$3 = {
457
+ const attributes$6 = {
418
458
  group: {
419
459
  type: "relation",
420
460
  relation: "manyToOne",
@@ -473,27 +513,27 @@ const attributes$3 = {
473
513
  mappedBy: "expense"
474
514
  }
475
515
  };
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
516
+ const schema$6 = {
517
+ kind: kind$6,
518
+ collectionName: collectionName$6,
519
+ info: info$6,
520
+ options: options$6,
521
+ pluginOptions: pluginOptions$6,
522
+ attributes: attributes$6
483
523
  };
484
- const expense$1 = { schema: schema$3 };
485
- const kind$2 = "collectionType";
486
- const collectionName$2 = "split_shares";
487
- const info$2 = {
524
+ const expense$1 = { schema: schema$6 };
525
+ const kind$5 = "collectionType";
526
+ const collectionName$5 = "split_shares";
527
+ const info$5 = {
488
528
  singularName: "share",
489
529
  pluralName: "shares",
490
530
  displayName: "Split Share",
491
531
  description: "What one member owes of one expense."
492
532
  };
493
- const options$2 = {
533
+ const options$5 = {
494
534
  draftAndPublish: false
495
535
  };
496
- const pluginOptions$2 = {
536
+ const pluginOptions$5 = {
497
537
  "content-manager": {
498
538
  visible: false
499
539
  },
@@ -501,7 +541,7 @@ const pluginOptions$2 = {
501
541
  visible: false
502
542
  }
503
543
  };
504
- const attributes$2 = {
544
+ const attributes$5 = {
505
545
  expense: {
506
546
  type: "relation",
507
547
  relation: "manyToOne",
@@ -523,27 +563,27 @@ const attributes$2 = {
523
563
  "default": 0
524
564
  }
525
565
  };
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
566
+ const schema$5 = {
567
+ kind: kind$5,
568
+ collectionName: collectionName$5,
569
+ info: info$5,
570
+ options: options$5,
571
+ pluginOptions: pluginOptions$5,
572
+ attributes: attributes$5
533
573
  };
534
- const share = { schema: schema$2 };
535
- const kind$1 = "collectionType";
536
- const collectionName$1 = "split_settlements";
537
- const info$1 = {
574
+ const share = { schema: schema$5 };
575
+ const kind$4 = "collectionType";
576
+ const collectionName$4 = "split_settlements";
577
+ const info$4 = {
538
578
  singularName: "settlement",
539
579
  pluralName: "settlements",
540
580
  displayName: "Split Settlement",
541
581
  description: "A payment from one member to another that reduces what is owed."
542
582
  };
543
- const options$1 = {
583
+ const options$4 = {
544
584
  draftAndPublish: false
545
585
  };
546
- const pluginOptions$1 = {
586
+ const pluginOptions$4 = {
547
587
  "content-manager": {
548
588
  visible: false
549
589
  },
@@ -551,7 +591,7 @@ const pluginOptions$1 = {
551
591
  visible: false
552
592
  }
553
593
  };
554
- const attributes$1 = {
594
+ const attributes$4 = {
555
595
  group: {
556
596
  type: "relation",
557
597
  relation: "manyToOne",
@@ -614,27 +654,27 @@ const attributes$1 = {
614
654
  target: "plugin::split.person"
615
655
  }
616
656
  };
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
657
+ const schema$4 = {
658
+ kind: kind$4,
659
+ collectionName: collectionName$4,
660
+ info: info$4,
661
+ options: options$4,
662
+ pluginOptions: pluginOptions$4,
663
+ attributes: attributes$4
624
664
  };
625
- const settlement$1 = { schema: schema$1 };
626
- const kind = "collectionType";
627
- const collectionName = "split_events";
628
- const info = {
665
+ const settlement$1 = { schema: schema$4 };
666
+ const kind$3 = "collectionType";
667
+ const collectionName$3 = "split_events";
668
+ const info$3 = {
629
669
  singularName: "event",
630
670
  pluralName: "events",
631
671
  displayName: "Split Event",
632
672
  description: "Audit trail: who did what in which group."
633
673
  };
634
- const options = {
674
+ const options$3 = {
635
675
  draftAndPublish: false
636
676
  };
637
- const pluginOptions = {
677
+ const pluginOptions$3 = {
638
678
  "content-manager": {
639
679
  visible: false
640
680
  },
@@ -642,7 +682,7 @@ const pluginOptions = {
642
682
  visible: false
643
683
  }
644
684
  };
645
- const attributes = {
685
+ const attributes$3 = {
646
686
  group: {
647
687
  type: "relation",
648
688
  relation: "manyToOne",
@@ -670,6 +710,175 @@ const attributes = {
670
710
  required: true
671
711
  }
672
712
  };
713
+ const schema$3 = {
714
+ kind: kind$3,
715
+ collectionName: collectionName$3,
716
+ info: info$3,
717
+ options: options$3,
718
+ pluginOptions: pluginOptions$3,
719
+ attributes: attributes$3
720
+ };
721
+ const event = { schema: schema$3 };
722
+ const kind$2 = "collectionType";
723
+ const collectionName$2 = "split_orders";
724
+ const info$2 = {
725
+ singularName: "order",
726
+ pluralName: "orders",
727
+ displayName: "Split Order",
728
+ description: "A list of priced items the members of a group order from until it closes; closing it writes one expense."
729
+ };
730
+ const options$2 = {
731
+ draftAndPublish: false
732
+ };
733
+ const pluginOptions$2 = {
734
+ "content-manager": {
735
+ visible: false
736
+ },
737
+ "content-type-builder": {
738
+ visible: false
739
+ }
740
+ };
741
+ const attributes$2 = {
742
+ group: {
743
+ type: "relation",
744
+ relation: "manyToOne",
745
+ target: "plugin::split.group"
746
+ },
747
+ organizer: {
748
+ type: "relation",
749
+ relation: "manyToOne",
750
+ target: "plugin::split.member"
751
+ },
752
+ title: {
753
+ type: "string",
754
+ maxLength: 120,
755
+ required: true
756
+ },
757
+ closesAt: {
758
+ type: "datetime"
759
+ },
760
+ status: {
761
+ type: "enumeration",
762
+ "enum": [
763
+ "open",
764
+ "closed",
765
+ "cancelled"
766
+ ],
767
+ "default": "open",
768
+ required: true
769
+ },
770
+ deliveryFee: {
771
+ type: "integer",
772
+ "default": 0,
773
+ min: 0
774
+ },
775
+ expenseRef: {
776
+ type: "string",
777
+ maxLength: 64
778
+ },
779
+ closedAt: {
780
+ type: "datetime"
781
+ }
782
+ };
783
+ const schema$2 = {
784
+ kind: kind$2,
785
+ collectionName: collectionName$2,
786
+ info: info$2,
787
+ options: options$2,
788
+ pluginOptions: pluginOptions$2,
789
+ attributes: attributes$2
790
+ };
791
+ const order$1 = { schema: schema$2 };
792
+ const kind$1 = "collectionType";
793
+ const collectionName$1 = "split_order_items";
794
+ const info$1 = {
795
+ singularName: "order-item",
796
+ pluralName: "order-items",
797
+ displayName: "Split Order Item",
798
+ description: "One thing that can be ordered, at a unit price."
799
+ };
800
+ const options$1 = {
801
+ draftAndPublish: false
802
+ };
803
+ const pluginOptions$1 = {
804
+ "content-manager": {
805
+ visible: false
806
+ },
807
+ "content-type-builder": {
808
+ visible: false
809
+ }
810
+ };
811
+ const attributes$1 = {
812
+ order: {
813
+ type: "relation",
814
+ relation: "manyToOne",
815
+ target: "plugin::split.order"
816
+ },
817
+ label: {
818
+ type: "string",
819
+ maxLength: 120,
820
+ required: true
821
+ },
822
+ price: {
823
+ type: "integer",
824
+ required: true,
825
+ min: 1
826
+ },
827
+ position: {
828
+ type: "integer",
829
+ "default": 0
830
+ }
831
+ };
832
+ const schema$1 = {
833
+ kind: kind$1,
834
+ collectionName: collectionName$1,
835
+ info: info$1,
836
+ options: options$1,
837
+ pluginOptions: pluginOptions$1,
838
+ attributes: attributes$1
839
+ };
840
+ const orderItem = { schema: schema$1 };
841
+ const kind = "collectionType";
842
+ const collectionName = "split_order_lines";
843
+ const info = {
844
+ singularName: "order-line",
845
+ pluralName: "order-lines",
846
+ displayName: "Split Order Line",
847
+ description: "How many of one item one member takes."
848
+ };
849
+ const options = {
850
+ draftAndPublish: false
851
+ };
852
+ const pluginOptions = {
853
+ "content-manager": {
854
+ visible: false
855
+ },
856
+ "content-type-builder": {
857
+ visible: false
858
+ }
859
+ };
860
+ const attributes = {
861
+ order: {
862
+ type: "relation",
863
+ relation: "manyToOne",
864
+ target: "plugin::split.order"
865
+ },
866
+ item: {
867
+ type: "relation",
868
+ relation: "manyToOne",
869
+ target: "plugin::split.order-item"
870
+ },
871
+ member: {
872
+ type: "relation",
873
+ relation: "manyToOne",
874
+ target: "plugin::split.member"
875
+ },
876
+ quantity: {
877
+ type: "integer",
878
+ required: true,
879
+ min: 1
880
+ }
881
+ };
673
882
  const schema = {
674
883
  kind,
675
884
  collectionName,
@@ -678,8 +887,19 @@ const schema = {
678
887
  pluginOptions,
679
888
  attributes
680
889
  };
681
- const event = { schema };
682
- const contentTypes = { person: person$2, group: group$1, member: member$1, expense: expense$1, share, settlement: settlement$1, event };
890
+ const orderLine = { schema };
891
+ const contentTypes = {
892
+ person: person$2,
893
+ group: group$1,
894
+ member: member$1,
895
+ expense: expense$1,
896
+ share,
897
+ settlement: settlement$1,
898
+ event,
899
+ order: order$1,
900
+ "order-item": orderItem,
901
+ "order-line": orderLine
902
+ };
683
903
  class SplitError extends Error {
684
904
  /**
685
905
  * @param {number} status HTTP status
@@ -751,17 +971,39 @@ const app = ({ strapi }) => {
751
971
  const viewer = (ctx) => ctx.state.splitPerson;
752
972
  const seat = (ctx, options2) => svc("group").seat(viewer(ctx), ctx.params.group, options2);
753
973
  const writable = (ctx) => seat(ctx, { writable: true });
974
+ const orderView = (ctx, mine, order2) => svc("order").view(order2, mine, viewer(ctx), { detailed: true });
754
975
  return {
755
976
  // ── Person ───────────────────────────────────────────────────────────
756
977
  me: handle(strapi, async (ctx) => {
757
978
  ok(ctx, svc("format").person(viewer(ctx), Boolean(ctx.state.splitPersonIsNew)));
758
979
  }),
980
+ updateMe: handle(strapi, async (ctx) => {
981
+ const person2 = await svc("person").setPreferences(viewer(ctx), body(ctx));
982
+ ok(ctx, svc("format").person(person2));
983
+ }),
759
984
  overview: handle(strapi, async (ctx) => ok(ctx, await svc("view").overview(viewer(ctx)))),
760
985
  activity: handle(strapi, async (ctx) => {
761
986
  const page = parsePagination(ctx.query);
762
987
  const { items, total } = await svc("view").activity(viewer(ctx), page);
763
988
  ctx.body = paged(items, total, page);
764
989
  }),
990
+ // ── Invitations ──────────────────────────────────────────────────────
991
+ invitations: handle(strapi, async (ctx) => {
992
+ const seats = await svc("member").invitations(viewer(ctx));
993
+ ok(
994
+ ctx,
995
+ seats.map((s) => svc("format").invitation(s))
996
+ );
997
+ }),
998
+ acceptInvitation: handle(strapi, async (ctx) => {
999
+ const group2 = await svc("member").accept(viewer(ctx), ctx.params.invitation);
1000
+ const mine = await svc("group").seat(viewer(ctx), group2.documentId);
1001
+ ok(ctx, await svc("view").group(mine, viewer(ctx)));
1002
+ }),
1003
+ declineInvitation: handle(strapi, async (ctx) => {
1004
+ await svc("member").decline(viewer(ctx), ctx.params.invitation);
1005
+ noContent(ctx);
1006
+ }),
765
1007
  // ── Groups ───────────────────────────────────────────────────────────
766
1008
  createGroup: handle(strapi, async (ctx) => {
767
1009
  const group2 = await svc("group").create(viewer(ctx), body(ctx));
@@ -850,6 +1092,36 @@ const app = ({ strapi }) => {
850
1092
  const mine = await seat(ctx);
851
1093
  const settlement2 = await svc("settlement").cancel(mine, ctx.params.settlement);
852
1094
  ok(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)));
1095
+ }),
1096
+ // ── Orders ───────────────────────────────────────────────────────────
1097
+ orders: handle(
1098
+ strapi,
1099
+ async (ctx) => ok(ctx, await svc("order").list(await seat(ctx), viewer(ctx)))
1100
+ ),
1101
+ createOrder: handle(strapi, async (ctx) => {
1102
+ const mine = await writable(ctx);
1103
+ const order2 = await svc("order").create(mine, body(ctx));
1104
+ written(ctx, await orderView(ctx, mine, order2), false);
1105
+ }),
1106
+ order: handle(strapi, async (ctx) => {
1107
+ const mine = await seat(ctx);
1108
+ const order2 = await svc("order").find(mine.group, ctx.params.order);
1109
+ ok(ctx, await orderView(ctx, mine, order2));
1110
+ }),
1111
+ setOrderLines: handle(strapi, async (ctx) => {
1112
+ const mine = await writable(ctx);
1113
+ const order2 = await svc("order").setLines(mine, ctx.params.order, body(ctx));
1114
+ ok(ctx, await orderView(ctx, mine, order2));
1115
+ }),
1116
+ closeOrder: handle(strapi, async (ctx) => {
1117
+ const mine = await writable(ctx);
1118
+ const order2 = await svc("order").close(mine, ctx.params.order, body(ctx));
1119
+ ok(ctx, await orderView(ctx, mine, order2));
1120
+ }),
1121
+ cancelOrder: handle(strapi, async (ctx) => {
1122
+ const mine = await writable(ctx);
1123
+ const order2 = await svc("order").cancel(mine, ctx.params.order);
1124
+ ok(ctx, await orderView(ctx, mine, order2));
853
1125
  })
854
1126
  };
855
1127
  };
@@ -963,11 +1235,13 @@ const view = ({ strapi }) => {
963
1235
  const debts = perGroup.flatMap((g) => g.debts).sort((a, b) => b.amount - a.amount);
964
1236
  const credits = perGroup.flatMap((g) => g.credits).sort((a, b) => b.amount - a.amount);
965
1237
  const sum = (list) => list.reduce((total, item) => total + item.amount, 0);
1238
+ const invitations = await svc("member").invitations(viewer);
966
1239
  return {
967
1240
  owe: sum(debts),
968
1241
  owed: sum(credits),
969
1242
  debts,
970
1243
  credits,
1244
+ invitations: invitations.map((seat) => format2.invitation(seat)),
971
1245
  groups: perGroup.map((g) => g.summary).sort((a, b) => new Date(b.lastActivityAt ?? 0) - new Date(a.lastActivityAt ?? 0))
972
1246
  };
973
1247
  },
@@ -1174,8 +1448,14 @@ const route$1 = (method, path, handler) => ({
1174
1448
  const contentApi = [
1175
1449
  // person
1176
1450
  route$1("GET", "/me", "me"),
1451
+ // PUT, not PATCH: some app runtimes (mini-programs) cannot send PATCH.
1452
+ route$1("PUT", "/me", "updateMe"),
1177
1453
  route$1("GET", "/overview", "overview"),
1178
1454
  route$1("GET", "/activity", "activity"),
1455
+ // invitations: being added to a group is an offer, answered by the person
1456
+ route$1("GET", "/invitations", "invitations"),
1457
+ route$1("POST", "/invitations/:invitation/accept", "acceptInvitation"),
1458
+ route$1("POST", "/invitations/:invitation/decline", "declineInvitation"),
1179
1459
  // groups
1180
1460
  route$1("POST", "/groups", "createGroup"),
1181
1461
  route$1("POST", "/groups/join", "joinGroup"),
@@ -1198,7 +1478,14 @@ const contentApi = [
1198
1478
  route$1("POST", "/groups/:group/settlements", "createSettlement"),
1199
1479
  route$1("POST", "/groups/:group/settlements/:settlement/confirm", "confirmSettlement"),
1200
1480
  route$1("POST", "/groups/:group/settlements/:settlement/reject", "rejectSettlement"),
1201
- route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement")
1481
+ route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement"),
1482
+ // orders: priced items the members order from; closing one writes an expense
1483
+ route$1("GET", "/groups/:group/orders", "orders"),
1484
+ route$1("POST", "/groups/:group/orders", "createOrder"),
1485
+ route$1("GET", "/groups/:group/orders/:order", "order"),
1486
+ route$1("PUT", "/groups/:group/orders/:order/lines", "setOrderLines"),
1487
+ route$1("POST", "/groups/:group/orders/:order/close", "closeOrder"),
1488
+ route$1("POST", "/groups/:group/orders/:order/cancel", "cancelOrder")
1202
1489
  ];
1203
1490
  const can = (...actions) => ({
1204
1491
  policies: [
@@ -1300,10 +1587,16 @@ const audit = ({ strapi }) => ({
1300
1587
  return { items, total };
1301
1588
  }
1302
1589
  });
1303
- const iso = (date) => date ? new Date(date).toISOString() : null;
1590
+ const iso$1 = (date) => date ? new Date(date).toISOString() : null;
1304
1591
  const format = () => ({
1305
1592
  person(p, isNew = false) {
1306
- return { id: p.documentId, displayName: p.displayName ?? null, phone: p.phone ?? null, isNew };
1593
+ return {
1594
+ id: p.documentId,
1595
+ displayName: p.displayName ?? null,
1596
+ phone: p.phone ?? null,
1597
+ autoAcceptInvites: Boolean(p.autoAcceptInvites),
1598
+ isNew
1599
+ };
1307
1600
  },
1308
1601
  /** The name a seat goes by: the person's own once they have one, the name it was added under otherwise. */
1309
1602
  nameOf(member2) {
@@ -1323,13 +1616,32 @@ const format = () => ({
1323
1616
  displayName: this.nameOf(m),
1324
1617
  isYou: Boolean(viewer) && idOf(m.person) === viewer.id,
1325
1618
  isRegistered: Boolean(m.person),
1619
+ invite: this.inviteOf(m),
1326
1620
  role: m.role,
1327
1621
  hasLeft: Boolean(m.leftAt)
1328
1622
  };
1329
1623
  },
1624
+ /** `pending` while an invited person has not answered, `declined` once they said no, else null. */
1625
+ inviteOf(m) {
1626
+ if (m.declinedAt) return INVITE.DECLINED;
1627
+ return m.person && !m.joinedAt ? INVITE.PENDING : null;
1628
+ },
1629
+ /**
1630
+ * An invitation as the invited person sees it: enough to decide, nothing of the books.
1631
+ * @param {Object} seat member row, `group` and `invitedBy` populated, with a `memberCount`
1632
+ */
1633
+ invitation(seat) {
1634
+ return {
1635
+ id: seat.documentId,
1636
+ group: { id: seat.group.documentId, name: seat.group.name },
1637
+ invitedBy: seat.invitedBy ? { displayName: seat.invitedBy.displayName ?? null } : null,
1638
+ memberCount: seat.memberCount,
1639
+ invitedAt: iso$1(seat.createdAt)
1640
+ };
1641
+ },
1330
1642
  /** A seat as an administrator sees it: the phone masked. */
1331
1643
  adminMember(m) {
1332
- return { ...this.member(m), phone: maskPhone(this.phoneOf(m)), joinedAt: iso(m.joinedAt) };
1644
+ return { ...this.member(m), phone: maskPhone(this.phoneOf(m)), joinedAt: iso$1(m.joinedAt) };
1333
1645
  },
1334
1646
  group(g) {
1335
1647
  return {
@@ -1337,7 +1649,7 @@ const format = () => ({
1337
1649
  name: g.name,
1338
1650
  inviteCode: g.inviteCode,
1339
1651
  isArchived: Boolean(g.archivedAt),
1340
- lastActivityAt: iso(g.lastActivityAt)
1652
+ lastActivityAt: iso$1(g.lastActivityAt)
1341
1653
  };
1342
1654
  },
1343
1655
  /**
@@ -1359,7 +1671,7 @@ const format = () => ({
1359
1671
  category: e.category ?? null,
1360
1672
  amount: e.amount,
1361
1673
  mode: e.mode,
1362
- spentAt: iso(e.spentAt),
1674
+ spentAt: iso$1(e.spentAt),
1363
1675
  paidBy: this.member(e.paidBy, viewer),
1364
1676
  yourShare: mine ? mine.amount : 0,
1365
1677
  shares,
@@ -1382,8 +1694,8 @@ const format = () => ({
1382
1694
  status: s.status,
1383
1695
  reference: s.reference ?? null,
1384
1696
  note: s.note ?? null,
1385
- declaredAt: iso(s.declaredAt),
1386
- resolvedAt: iso(s.resolvedAt),
1697
+ declaredAt: iso$1(s.declaredAt),
1698
+ resolvedAt: iso$1(s.resolvedAt),
1387
1699
  canConfirm: pending && idOf(s.to) === me.id,
1388
1700
  canCancel: pending && idOf(s.from) === me.id
1389
1701
  };
@@ -1440,7 +1752,8 @@ const person = ({ strapi }) => ({
1440
1752
  }
1441
1753
  },
1442
1754
  /**
1443
- * Seats added by phone before this person existed become theirs.
1755
+ * Seats added by phone before this person existed become invitations to them: theirs to accept
1756
+ * or decline, like any other.
1444
1757
  * @param {Object} person
1445
1758
  * @returns {Promise<number>} seats claimed
1446
1759
  */
@@ -1451,10 +1764,24 @@ const person = ({ strapi }) => ({
1451
1764
  select: ["id"]
1452
1765
  });
1453
1766
  for (const seat of seats) {
1454
- await strapi.db.query(UID.MEMBER).update({ where: { id: seat.id }, data: { person: person2.id, joinedAt: /* @__PURE__ */ new Date() } });
1767
+ await strapi.db.query(UID.MEMBER).update({ where: { id: seat.id }, data: { person: person2.id } });
1455
1768
  }
1456
1769
  return seats.length;
1457
1770
  },
1771
+ /**
1772
+ * What a person chose for themselves.
1773
+ * @param {Object} person
1774
+ * @param {{ autoAcceptInvites?: boolean }} input
1775
+ * @returns {Promise<Object>} the person, updated
1776
+ */
1777
+ async setPreferences(person2, input) {
1778
+ if (typeof input?.autoAcceptInvites !== "boolean")
1779
+ throw badRequest(ERROR_CODES.VALIDATION, "Préférence invalide.");
1780
+ return strapi.db.query(UID.PERSON).update({
1781
+ where: { id: person2.id },
1782
+ data: { autoAcceptInvites: input.autoAcceptInvites }
1783
+ });
1784
+ },
1458
1785
  /** The registered person with this phone, if any. */
1459
1786
  async byPhone(phone) {
1460
1787
  return phone ? strapi.db.query(UID.PERSON).findOne({ where: { phone } }) : null;
@@ -1609,6 +1936,7 @@ const ledger = ({ strapi }) => ({
1609
1936
  return books.settlements.filter((s) => s.status === SETTLEMENT_STATUS.PENDING && s.from === from && s.to === to).reduce((sum, s) => sum + s.amount, 0);
1610
1937
  }
1611
1938
  });
1939
+ const HELD = Object.freeze({ leftAt: { $null: true }, joinedAt: { $notNull: true } });
1612
1940
  const cleanName = (raw) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, NAME_MAX);
1613
1941
  const group = ({ strapi }) => {
1614
1942
  const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
@@ -1635,7 +1963,7 @@ const group = ({ strapi }) => {
1635
1963
  async seat(person2, documentId, { writable = false } = {}) {
1636
1964
  const group2 = await groups().findOne({ where: { documentId: String(documentId) } });
1637
1965
  const me = group2 && await members().findOne({
1638
- where: { group: group2.id, person: person2.id, leftAt: { $null: true } },
1966
+ where: { group: group2.id, person: person2.id, ...HELD },
1639
1967
  populate: { person: true }
1640
1968
  });
1641
1969
  if (!me) throw notFound(ERROR_CODES.GROUP_NOT_FOUND, "Groupe introuvable.");
@@ -1651,7 +1979,7 @@ const group = ({ strapi }) => {
1651
1979
  /** The seats a person holds, groups populated; archived groups only on request. */
1652
1980
  async seatsOf(person2, { archived = false } = {}) {
1653
1981
  const rows = await members().findMany({
1654
- where: { person: person2.id, leftAt: { $null: true } },
1982
+ where: { person: person2.id, ...HELD },
1655
1983
  populate: { group: true, person: true }
1656
1984
  });
1657
1985
  return rows.filter((m) => m.group && Boolean(m.group.archivedAt) === archived);
@@ -1668,7 +1996,7 @@ const group = ({ strapi }) => {
1668
1996
  const name = cleanName(input.name);
1669
1997
  if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
1670
1998
  const limits = svc("settings").limits();
1671
- const held = await members().count({ where: { person: person2.id, leftAt: { $null: true } } });
1999
+ const held = await members().count({ where: { person: person2.id, ...HELD } });
1672
2000
  if (held >= limits.maxGroupsPerPerson)
1673
2001
  throw unprocessable(
1674
2002
  ERROR_CODES.GROUP_LIMIT,
@@ -1696,7 +2024,7 @@ const group = ({ strapi }) => {
1696
2024
  joinedAt: now
1697
2025
  }
1698
2026
  });
1699
- for (const other of others) await svc("member").seatFor(g, other);
2027
+ for (const other of others) await svc("member").seatFor(g, other, person2);
1700
2028
  return g;
1701
2029
  });
1702
2030
  await svc("audit").log({
@@ -1731,8 +2059,8 @@ const group = ({ strapi }) => {
1731
2059
  return updated;
1732
2060
  },
1733
2061
  /**
1734
- * Take a seat with an invite code. A seat that was waiting for this person's phone is theirs
1735
- * already; joining twice is not an error.
2062
+ * Take a seat with an invite code. Entering the code of a group one was invited to accepts the
2063
+ * invitation; joining twice is not an error.
1736
2064
  */
1737
2065
  async join(person2, rawCode) {
1738
2066
  const inviteCode = String(rawCode ?? "").trim().toUpperCase();
@@ -1742,6 +2070,7 @@ const group = ({ strapi }) => {
1742
2070
  const existing = await members().findOne({
1743
2071
  where: { group: group2.id, person: person2.id, leftAt: { $null: true } }
1744
2072
  });
2073
+ if (existing && !existing.joinedAt) await svc("member").take({ ...existing, group: group2 }, person2);
1745
2074
  if (existing) return group2;
1746
2075
  const limits = svc("settings").limits();
1747
2076
  const count = await members().count({ where: { group: group2.id, leftAt: { $null: true } } });
@@ -1814,8 +2143,14 @@ const member = ({ strapi }) => {
1814
2143
  throw conflict(ERROR_CODES.MEMBER_EXISTS, "Un numéro apparaît deux fois.");
1815
2144
  return parsed;
1816
2145
  },
1817
- /** Create the seat; it is the person's at once when that phone already uses the app. */
1818
- async seatFor(group2, { displayName, phone }) {
2146
+ /**
2147
+ * Create the seat. When that phone already uses the app it is an invitation to them, taken at
2148
+ * once only for someone who accepts every invitation.
2149
+ * @param {Object} group
2150
+ * @param {{ displayName: string, phone: string|null }} input
2151
+ * @param {Object} inviter the person adding them
2152
+ */
2153
+ async seatFor(group2, { displayName, phone }, inviter) {
1819
2154
  const person2 = await svc("person").byPhone(phone);
1820
2155
  return members().create({
1821
2156
  data: {
@@ -1824,10 +2159,20 @@ const member = ({ strapi }) => {
1824
2159
  displayName,
1825
2160
  phone,
1826
2161
  role: ROLE.MEMBER,
1827
- joinedAt: person2 ? /* @__PURE__ */ new Date() : null
2162
+ invitedBy: inviter?.id ?? null,
2163
+ joinedAt: person2?.autoAcceptInvites ? /* @__PURE__ */ new Date() : null
1828
2164
  }
1829
2165
  });
1830
2166
  },
2167
+ /** Is someone sitting here: a person who is in the group, not a name or an open invitation? */
2168
+ isHeld(seat) {
2169
+ return Boolean(seat.person) && Boolean(seat.joinedAt);
2170
+ },
2171
+ /** Where an invitation stands, or null for a seat that is held or was never anyone's. */
2172
+ inviteOf(seat) {
2173
+ if (seat.declinedAt) return INVITE.DECLINED;
2174
+ return seat.person && !seat.joinedAt ? INVITE.PENDING : null;
2175
+ },
1831
2176
  /**
1832
2177
  * @param {{ group: Object, me: Object }} seat the caller's
1833
2178
  * @param {{ name: string, phone?: string }} raw
@@ -1848,7 +2193,7 @@ const member = ({ strapi }) => {
1848
2193
  const format2 = svc("format");
1849
2194
  if (input.phone && seats.some((s) => format2.phoneOf(s) === input.phone))
1850
2195
  throw conflict(ERROR_CODES.MEMBER_EXISTS, "Ce numéro est déjà dans le groupe.");
1851
- const created = await this.seatFor(group2, input);
2196
+ const created = await this.seatFor(group2, input, me.person);
1852
2197
  await svc("audit").log({
1853
2198
  group: group2,
1854
2199
  actor: me.person,
@@ -1866,17 +2211,23 @@ const member = ({ strapi }) => {
1866
2211
  if (!seat) throw notFound(ERROR_CODES.MEMBER_NOT_FOUND, "Membre introuvable.");
1867
2212
  return seat;
1868
2213
  },
1869
- /** A seat is only vacated once it is even and nothing awaits confirmation on it. */
1870
- async assertSettled(group2, seat) {
2214
+ /** What a seat still has on the books: its balance, and whether a payment awaits an answer. */
2215
+ async standing(group2, seat) {
1871
2216
  const books = await svc("ledger").of(group2);
1872
2217
  const busy = books.settlements.some(
1873
2218
  (s) => s.status === SETTLEMENT_STATUS.PENDING && [s.from, s.to].includes(seat.id)
1874
2219
  );
1875
- if (books.balanceOf(seat.id) !== 0 || busy)
2220
+ const balance = books.balanceOf(seat.id);
2221
+ return { balance, settled: balance === 0 && !busy };
2222
+ },
2223
+ /** A seat is only vacated once it is even and nothing awaits confirmation on it. */
2224
+ async assertSettled(group2, seat) {
2225
+ const { balance, settled } = await this.standing(group2, seat);
2226
+ if (!settled)
1876
2227
  throw unprocessable(
1877
2228
  ERROR_CODES.MEMBER_NOT_SETTLED,
1878
2229
  "Les comptes de ce membre ne sont pas à zéro.",
1879
- { balance: books.balanceOf(seat.id) }
2230
+ { balance }
1880
2231
  );
1881
2232
  },
1882
2233
  /** The owner removes someone else. */
@@ -1910,10 +2261,82 @@ const member = ({ strapi }) => {
1910
2261
  /** Is this seat held by this person? */
1911
2262
  isHeldBy(seat, person2) {
1912
2263
  return idOf(seat.person) === person2.id;
2264
+ },
2265
+ /** The invitations a person has not answered, newest first; archived groups are not offered. */
2266
+ async invitations(person2) {
2267
+ const rows = await members().findMany({
2268
+ where: { person: person2.id, joinedAt: { $null: true }, leftAt: { $null: true } },
2269
+ populate: { group: true, invitedBy: true },
2270
+ orderBy: { id: "desc" }
2271
+ });
2272
+ const open = rows.filter((seat) => seat.group && !seat.group.archivedAt);
2273
+ return Promise.all(
2274
+ open.map(async (seat) => ({
2275
+ ...seat,
2276
+ memberCount: await members().count({
2277
+ where: { group: seat.group.id, leftAt: { $null: true } }
2278
+ })
2279
+ }))
2280
+ );
2281
+ },
2282
+ /** One open invitation of this person, by the seat's document id. */
2283
+ async invitation(person2, documentId) {
2284
+ const seat = await members().findOne({
2285
+ where: {
2286
+ documentId: String(documentId),
2287
+ person: person2.id,
2288
+ joinedAt: { $null: true },
2289
+ leftAt: { $null: true }
2290
+ },
2291
+ populate: { group: true, person: true }
2292
+ });
2293
+ if (!seat?.group)
2294
+ throw notFound(ERROR_CODES.INVITATION_NOT_FOUND, "Cette invitation n'existe plus.");
2295
+ return seat;
2296
+ },
2297
+ /** The person takes the seat they were offered. */
2298
+ async take(seat, person2) {
2299
+ await members().update({ where: { id: seat.id }, data: { joinedAt: /* @__PURE__ */ new Date() } });
2300
+ await svc("audit").log({
2301
+ group: seat.group,
2302
+ actor: person2,
2303
+ action: EVENT.MEMBER_JOINED,
2304
+ targetId: seat.documentId
2305
+ });
2306
+ },
2307
+ /**
2308
+ * @param {Object} person
2309
+ * @param {string} documentId the invitation's
2310
+ * @returns {Promise<Object>} the group they are now in
2311
+ */
2312
+ async accept(person2, documentId) {
2313
+ const seat = await this.invitation(person2, documentId);
2314
+ await this.take(seat, person2);
2315
+ return seat.group;
2316
+ },
2317
+ /**
2318
+ * The person says no. A seat with nothing on the books goes; one the group already counted in
2319
+ * its expenses stays as a name nobody holds, so the books still add up.
2320
+ * @param {Object} person
2321
+ * @param {string} documentId the invitation's
2322
+ */
2323
+ async decline(person2, documentId) {
2324
+ const seat = await this.invitation(person2, documentId);
2325
+ const now = /* @__PURE__ */ new Date();
2326
+ const { settled } = await this.standing(seat.group, seat);
2327
+ const data = settled ? { leftAt: now, declinedAt: now } : { person: null, declinedAt: now };
2328
+ await members().update({ where: { id: seat.id }, data });
2329
+ await svc("audit").log({
2330
+ group: seat.group,
2331
+ actor: person2,
2332
+ action: EVENT.MEMBER_DECLINED,
2333
+ targetId: seat.documentId,
2334
+ data: { kept: !settled }
2335
+ });
1913
2336
  }
1914
2337
  };
1915
2338
  };
1916
- const invalid = (message, details) => unprocessable(ERROR_CODES.SPLIT_INVALID, message, details);
2339
+ const invalid$1 = (message, details) => unprocessable(ERROR_CODES.SPLIT_INVALID, message, details);
1917
2340
  const sharesByWeight = (amount, weights) => {
1918
2341
  const total = weights.reduce((sum, w) => sum + w, 0);
1919
2342
  if (total === 0) return weights.map(() => 0);
@@ -1929,26 +2352,26 @@ const isCount = (n) => Number.isInteger(n) && n >= 0;
1929
2352
  const weightOf = (part, mode) => {
1930
2353
  if (mode === SPLIT_MODE.EQUAL) return 1;
1931
2354
  if (!isCount(part.weight) || part.weight > MAX_WEIGHT)
1932
- throw invalid(`Chaque part est un entier entre 0 et ${MAX_WEIGHT}.`);
2355
+ throw invalid$1(`Chaque part est un entier entre 0 et ${MAX_WEIGHT}.`);
1933
2356
  return part.weight;
1934
2357
  };
1935
2358
  const freeShares = (amount, parts) => {
1936
2359
  if (!parts.every((p) => isCount(p.amount)))
1937
- throw invalid("Chaque montant est un entier positif.");
2360
+ throw invalid$1("Chaque montant est un entier positif.");
1938
2361
  const sum = parts.reduce((total, p) => total + p.amount, 0);
1939
2362
  if (sum !== amount)
1940
- throw invalid("La somme des parts ne correspond pas au montant.", { amount, sum });
2363
+ throw invalid$1("La somme des parts ne correspond pas au montant.", { amount, sum });
1941
2364
  return parts.map((p) => p.amount);
1942
2365
  };
1943
2366
  const resolveShares = ({ amount, mode, parts }) => {
1944
- if (!Object.values(SPLIT_MODE).includes(mode)) throw invalid("Mode de partage inconnu.");
1945
- if (!Array.isArray(parts) || parts.length === 0) throw invalid("Personne ne participe.");
2367
+ if (!Object.values(SPLIT_MODE).includes(mode)) throw invalid$1("Mode de partage inconnu.");
2368
+ if (!Array.isArray(parts) || parts.length === 0) throw invalid$1("Personne ne participe.");
1946
2369
  if (new Set(parts.map((p) => String(p.member))).size !== parts.length)
1947
- throw invalid("Un membre apparaît deux fois.");
2370
+ throw invalid$1("Un membre apparaît deux fois.");
1948
2371
  const weights = mode === SPLIT_MODE.FREE ? null : parts.map((p) => weightOf(p, mode));
1949
2372
  const amounts = weights ? sharesByWeight(amount, weights) : freeShares(amount, parts);
1950
2373
  const shares = parts.map((p, i) => ({ member: p.member, amount: amounts[i], weight: weights ? weights[i] : 0 })).filter((s) => s.amount > 0);
1951
- if (shares.length === 0) throw invalid("Personne ne participe.");
2374
+ if (shares.length === 0) throw invalid$1("Personne ne participe.");
1952
2375
  return shares;
1953
2376
  };
1954
2377
  const POPULATE$1 = {
@@ -1973,8 +2396,8 @@ const expense = ({ strapi }) => {
1973
2396
  * paidBy: number, shares: Array<{ member: number, amount: number, weight: number }> }}
1974
2397
  */
1975
2398
  parse(input, active) {
1976
- const label = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
1977
- if (!label) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
2399
+ const label2 = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
2400
+ if (!label2) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
1978
2401
  const { maxAmount } = svc("settings").limits();
1979
2402
  const amount = input?.amount;
1980
2403
  if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
@@ -1993,7 +2416,7 @@ const expense = ({ strapi }) => {
1993
2416
  amount: p?.amount
1994
2417
  }));
1995
2418
  return {
1996
- label,
2419
+ label: label2,
1997
2420
  category: input?.category ? String(input.category).slice(0, 40) : null,
1998
2421
  amount,
1999
2422
  mode,
@@ -2156,7 +2579,7 @@ const settlement = ({ strapi }) => {
2156
2579
  to,
2157
2580
  received,
2158
2581
  method: String(input.method),
2159
- instant: received || method.instant || !to.person,
2582
+ instant: received || method.instant || !svc("member").isHeld(to),
2160
2583
  reference: text(input?.reference, REF_MAX),
2161
2584
  note: text(input?.note, NOTE_MAX),
2162
2585
  clientRef: text(input?.clientRef, REF_MAX)
@@ -2322,6 +2745,327 @@ const settlement = ({ strapi }) => {
2322
2745
  }
2323
2746
  };
2324
2747
  };
2748
+ const orderTotals = ({ items, lines, deliveryFee = 0 }) => {
2749
+ const priceOf = new Map(items.map((item) => [item.id, item.price]));
2750
+ const taken = /* @__PURE__ */ new Map();
2751
+ for (const { item, member: member2, quantity } of lines) {
2752
+ if (!priceOf.has(item) || quantity <= 0) continue;
2753
+ const sofar = taken.get(member2) ?? { quantity: 0, subtotal: 0 };
2754
+ taken.set(member2, {
2755
+ quantity: sofar.quantity + quantity,
2756
+ subtotal: sofar.subtotal + quantity * priceOf.get(item)
2757
+ });
2758
+ }
2759
+ const members = [...taken.keys()].sort((a, b) => a - b);
2760
+ const fees = sharesByWeight(
2761
+ deliveryFee,
2762
+ members.map(() => 1)
2763
+ );
2764
+ const people = members.map((member2, i) => ({
2765
+ member: member2,
2766
+ ...taken.get(member2),
2767
+ delivery: fees[i],
2768
+ total: taken.get(member2).subtotal + fees[i]
2769
+ }));
2770
+ const subtotal = people.reduce((sum, p) => sum + p.subtotal, 0);
2771
+ return { people, subtotal, total: subtotal + (people.length ? deliveryFee : 0) };
2772
+ };
2773
+ const LINE_POPULATE = { item: { select: ["id"] }, member: { select: ["id"] } };
2774
+ const ORDER_POPULATE = { organizer: { select: ["id"] } };
2775
+ const iso = (date) => date ? new Date(date).toISOString() : null;
2776
+ const label = (raw) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, LABEL_MAX);
2777
+ const invalid = (message, details) => badRequest(ERROR_CODES.VALIDATION, message, details);
2778
+ const expenseRefOf = (order2) => `order:${order2.documentId}`;
2779
+ const order = ({ strapi }) => {
2780
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
2781
+ const orders = () => strapi.db.query(UID.ORDER);
2782
+ const items = () => strapi.db.query(UID.ORDER_ITEM);
2783
+ const lines = () => strapi.db.query(UID.ORDER_LINE);
2784
+ return {
2785
+ /** Members can still say what they take. */
2786
+ accepts(order2, now = /* @__PURE__ */ new Date()) {
2787
+ return order2.status === ORDER_STATUS.OPEN && (!order2.closesAt || now < new Date(order2.closesAt));
2788
+ },
2789
+ /** When ordering stops: nothing, or a real date still ahead. */
2790
+ closesAt(raw) {
2791
+ if (raw == null || raw === "") return null;
2792
+ const date = new Date(raw);
2793
+ if (Number.isNaN(date.getTime()) || date <= /* @__PURE__ */ new Date())
2794
+ throw invalid("L'heure de clôture doit être à venir.");
2795
+ return date;
2796
+ },
2797
+ /** What the organiser sent, checked. */
2798
+ parse(input) {
2799
+ const title = label(input?.title);
2800
+ if (!title) throw invalid("Donne un nom à la commande.");
2801
+ const { maxAmount } = svc("settings").limits();
2802
+ const list = Array.isArray(input?.items) ? input.items : [];
2803
+ if (list.length === 0 || list.length > ORDER_MAX_ITEMS)
2804
+ throw invalid(`Entre 1 et ${ORDER_MAX_ITEMS} articles.`, { max: ORDER_MAX_ITEMS });
2805
+ const parsed = list.map((raw) => ({ label: label(raw?.label), price: raw?.price }));
2806
+ if (parsed.some((item) => !item.label)) throw invalid("Chaque article a un nom.");
2807
+ if (parsed.some((i) => !Number.isInteger(i.price) || i.price <= 0 || i.price > maxAmount))
2808
+ throw invalid("Chaque article a un prix.", { maxAmount });
2809
+ return { title, closesAt: this.closesAt(input?.closesAt), items: parsed };
2810
+ },
2811
+ /**
2812
+ * @param {{ group: Object, me: Object }} seat the organiser's
2813
+ * @param {{ title: string, closesAt?: string, items: Array<{ label: string, price: number }> }} input
2814
+ */
2815
+ async create({ group: group2, me }, input) {
2816
+ const data = this.parse(input);
2817
+ const order2 = await strapi.db.transaction(async () => {
2818
+ const created = await orders().create({
2819
+ data: {
2820
+ group: group2.id,
2821
+ organizer: me.id,
2822
+ title: data.title,
2823
+ closesAt: data.closesAt,
2824
+ status: ORDER_STATUS.OPEN,
2825
+ deliveryFee: 0
2826
+ }
2827
+ });
2828
+ for (const [position, item] of data.items.entries())
2829
+ await items().create({ data: { order: created.id, ...item, position } });
2830
+ return created;
2831
+ });
2832
+ await svc("audit").log({
2833
+ group: group2,
2834
+ actor: me.person,
2835
+ action: EVENT.ORDER_OPENED,
2836
+ targetId: order2.documentId,
2837
+ data: { items: data.items.length }
2838
+ });
2839
+ return this.find(group2, order2.documentId);
2840
+ },
2841
+ /** An order of this group. */
2842
+ async find(group2, documentId) {
2843
+ const order2 = await orders().findOne({
2844
+ where: { group: group2.id, documentId: String(documentId) },
2845
+ populate: ORDER_POPULATE
2846
+ });
2847
+ if (!order2) throw notFound(ERROR_CODES.ORDER_NOT_FOUND, "Commande introuvable.");
2848
+ return order2;
2849
+ },
2850
+ /** An order with what it offers and what was taken, relations as ids. */
2851
+ async load(order2) {
2852
+ const [offered, taken] = await Promise.all([
2853
+ items().findMany({ where: { order: order2.id }, orderBy: [{ position: "asc" }] }),
2854
+ lines().findMany({ where: { order: order2.id }, populate: LINE_POPULATE })
2855
+ ]);
2856
+ return {
2857
+ order: order2,
2858
+ items: offered,
2859
+ lines: taken.map((l) => ({
2860
+ item: idOf(l.item),
2861
+ member: idOf(l.member),
2862
+ quantity: l.quantity
2863
+ }))
2864
+ };
2865
+ },
2866
+ assertOrganizer(order2, me) {
2867
+ if (idOf(order2.organizer) !== me.id)
2868
+ throw forbidden(
2869
+ ERROR_CODES.NOT_ALLOWED,
2870
+ "Seul l'organisateur de la commande peut faire ça."
2871
+ );
2872
+ },
2873
+ assertOpen(order2) {
2874
+ if (order2.status !== ORDER_STATUS.OPEN)
2875
+ throw unprocessable(ERROR_CODES.ORDER_CLOSED, "Cette commande est close.", {
2876
+ status: order2.status
2877
+ });
2878
+ },
2879
+ /** The quantities sent, by item row id; unknown items and odd quantities are refused. */
2880
+ quantities(input, offered) {
2881
+ const byDoc = new Map(offered.map((item) => [item.documentId, item.id]));
2882
+ const list = Array.isArray(input?.lines) ? input.lines : null;
2883
+ if (!list) throw invalid("Liste de quantités invalide.");
2884
+ const wanted = /* @__PURE__ */ new Map();
2885
+ for (const raw of list) {
2886
+ const item = byDoc.get(String(raw?.item));
2887
+ if (!item) throw invalid("Cet article n'est pas dans la commande.");
2888
+ const quantity = raw?.quantity;
2889
+ if (!Number.isInteger(quantity) || quantity < 0 || quantity > ORDER_MAX_QUANTITY)
2890
+ throw invalid(`Une quantité va de 0 à ${ORDER_MAX_QUANTITY}.`, {
2891
+ max: ORDER_MAX_QUANTITY
2892
+ });
2893
+ wanted.set(item, quantity);
2894
+ }
2895
+ return wanted;
2896
+ },
2897
+ /**
2898
+ * What one member takes, replaced whole. A member sets their own; the organiser sets anyone's
2899
+ * (someone who told them, someone without the app), and still can after the closing time.
2900
+ * @param {{ group: Object, me: Object }} seat the caller's
2901
+ * @param {string} documentId the order
2902
+ * @param {{ member?: string, lines: Array<{ item: string, quantity: number }> }} input
2903
+ */
2904
+ async setLines({ group: group2, me }, documentId, input) {
2905
+ const order2 = await this.find(group2, documentId);
2906
+ this.assertOpen(order2);
2907
+ const organizes = idOf(order2.organizer) === me.id;
2908
+ const target = input?.member ? await svc("member").find(group2, input.member) : me;
2909
+ if (target.id !== me.id && !organizes)
2910
+ throw forbidden(ERROR_CODES.NOT_ALLOWED, "Tu ne peux commander que pour toi.");
2911
+ if (!organizes && !this.accepts(order2))
2912
+ throw unprocessable(ERROR_CODES.ORDER_CLOSED, "Les commandes sont closes.", {
2913
+ status: order2.status
2914
+ });
2915
+ const { items: offered } = await this.load(order2);
2916
+ const wanted = this.quantities(input, offered);
2917
+ await strapi.db.transaction(async () => {
2918
+ await lines().deleteMany({ where: { order: order2.id, member: target.id } });
2919
+ for (const [item, quantity] of wanted)
2920
+ if (quantity > 0)
2921
+ await lines().create({
2922
+ data: { order: order2.id, item, member: target.id, quantity }
2923
+ });
2924
+ });
2925
+ return order2;
2926
+ },
2927
+ /**
2928
+ * Close the order: one expense, paid by the organiser, each member owing what they took and
2929
+ * an equal part of the delivery. Closing an order already closed answers it as it is.
2930
+ * @param {{ group: Object, me: Object }} seat the organiser's
2931
+ * @param {string} documentId
2932
+ * @param {{ deliveryFee?: number, category?: string }} [input]
2933
+ */
2934
+ async close(seat, documentId, input = {}) {
2935
+ const { group: group2, me } = seat;
2936
+ const order2 = await this.find(group2, documentId);
2937
+ this.assertOrganizer(order2, me);
2938
+ if (order2.status === ORDER_STATUS.CLOSED) return order2;
2939
+ this.assertOpen(order2);
2940
+ const { maxAmount } = svc("settings").limits();
2941
+ const deliveryFee = input?.deliveryFee ?? 0;
2942
+ if (!Number.isInteger(deliveryFee) || deliveryFee < 0 || deliveryFee > maxAmount)
2943
+ throw invalid("Frais de livraison invalides.", { maxAmount });
2944
+ const [{ items: offered, lines: taken }, books] = await Promise.all([
2945
+ this.load(order2),
2946
+ svc("ledger").of(group2)
2947
+ ]);
2948
+ const here = new Set(books.active.map((s) => s.id));
2949
+ const totals = orderTotals({
2950
+ items: offered,
2951
+ lines: taken.filter((l) => here.has(l.member)),
2952
+ deliveryFee
2953
+ });
2954
+ if (totals.people.length === 0)
2955
+ throw unprocessable(ERROR_CODES.ORDER_EMPTY, "Personne n'a rien commandé.");
2956
+ const { expense: expense2 } = await svc("expense").create(seat, {
2957
+ label: order2.title,
2958
+ amount: totals.total,
2959
+ category: input?.category ?? null,
2960
+ mode: SPLIT_MODE.FREE,
2961
+ paidBy: me.documentId,
2962
+ clientRef: expenseRefOf(order2),
2963
+ shares: totals.people.map((p) => ({
2964
+ member: books.seatById.get(p.member).documentId,
2965
+ amount: p.total
2966
+ }))
2967
+ });
2968
+ await orders().update({
2969
+ where: { id: order2.id },
2970
+ data: {
2971
+ status: ORDER_STATUS.CLOSED,
2972
+ deliveryFee,
2973
+ expenseRef: expense2.documentId,
2974
+ closedAt: /* @__PURE__ */ new Date()
2975
+ }
2976
+ });
2977
+ await svc("audit").log({
2978
+ group: group2,
2979
+ actor: me.person,
2980
+ action: EVENT.ORDER_CLOSED,
2981
+ targetId: order2.documentId,
2982
+ data: { amount: totals.total, deliveryFee, people: totals.people.length }
2983
+ });
2984
+ return this.find(group2, documentId);
2985
+ },
2986
+ /** Drop an open order: nothing was written, nothing is owed. */
2987
+ async cancel({ group: group2, me }, documentId) {
2988
+ const order2 = await this.find(group2, documentId);
2989
+ this.assertOrganizer(order2, me);
2990
+ this.assertOpen(order2);
2991
+ await orders().update({
2992
+ where: { id: order2.id },
2993
+ data: { status: ORDER_STATUS.CANCELLED, closedAt: /* @__PURE__ */ new Date() }
2994
+ });
2995
+ await svc("audit").log({
2996
+ group: group2,
2997
+ actor: me.person,
2998
+ action: EVENT.ORDER_CANCELLED,
2999
+ targetId: order2.documentId
3000
+ });
3001
+ return this.find(group2, documentId);
3002
+ },
3003
+ /**
3004
+ * An order as a member reads it.
3005
+ * @param {Object} order
3006
+ * @param {{ group: Object, me: Object }} seat the viewer's
3007
+ * @param {Object} viewer the person asking
3008
+ * @param {{ detailed?: boolean }} [options] `detailed` adds the items and who took what
3009
+ */
3010
+ async view(order2, { group: group2, me }, viewer, { detailed = false } = {}) {
3011
+ const [{ items: offered, lines: taken }, books] = await Promise.all([
3012
+ this.load(order2),
3013
+ svc("ledger").of(group2)
3014
+ ]);
3015
+ const format2 = svc("format");
3016
+ const totals = orderTotals({ items: offered, lines: taken, deliveryFee: order2.deliveryFee });
3017
+ const docOf = new Map(offered.map((item) => [item.id, item.documentId]));
3018
+ const none = { quantity: 0, subtotal: 0, delivery: 0, total: 0 };
3019
+ const { member: _mine, ...yours } = totals.people.find((p) => p.member === me.id) ?? none;
3020
+ const summary = {
3021
+ id: order2.documentId,
3022
+ title: order2.title,
3023
+ status: order2.status,
3024
+ closesAt: iso(order2.closesAt),
3025
+ closedAt: iso(order2.closedAt),
3026
+ acceptsOrders: this.accepts(order2),
3027
+ isOrganizer: idOf(order2.organizer) === me.id,
3028
+ organizer: format2.member(books.seatById.get(idOf(order2.organizer)), viewer),
3029
+ deliveryFee: order2.deliveryFee ?? 0,
3030
+ expenseId: order2.expenseRef ?? null,
3031
+ participantCount: totals.people.length,
3032
+ subtotal: totals.subtotal,
3033
+ total: totals.total,
3034
+ yours
3035
+ };
3036
+ 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 }));
3038
+ const quantityOf = (item, member2) => taken.filter((l) => l.item === item && (member2 == null || l.member === member2)).reduce((sum, l) => sum + l.quantity, 0);
3039
+ return {
3040
+ ...summary,
3041
+ items: offered.map((item) => ({
3042
+ id: item.documentId,
3043
+ label: item.label,
3044
+ price: item.price,
3045
+ quantity: quantityOf(item.id),
3046
+ yours: quantityOf(item.id, me.id)
3047
+ })),
3048
+ people: totals.people.map(({ member: member2, ...sums }) => ({
3049
+ member: format2.member(books.seatById.get(member2), viewer),
3050
+ ...sums,
3051
+ lines: takenBy(member2)
3052
+ }))
3053
+ };
3054
+ },
3055
+ /** The group's orders as a member reads them: the open ones first, then the latest. */
3056
+ async list(seat, viewer) {
3057
+ const rows = await orders().findMany({
3058
+ where: { group: seat.group.id, status: { $in: [ORDER_STATUS.OPEN, ORDER_STATUS.CLOSED] } },
3059
+ populate: ORDER_POPULATE,
3060
+ orderBy: [{ id: "desc" }],
3061
+ limit: ORDER_LIST_SIZE
3062
+ });
3063
+ const open = (order2) => Number(order2.status === ORDER_STATUS.OPEN);
3064
+ const sorted = [...rows].sort((a, b) => open(b) - open(a));
3065
+ return Promise.all(sorted.map((order2) => this.view(order2, seat, viewer)));
3066
+ }
3067
+ };
3068
+ };
2325
3069
  const ADMIN_RECENT = 50;
2326
3070
  const stats = ({ strapi }) => {
2327
3071
  const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
@@ -2430,6 +3174,7 @@ const services = {
2430
3174
  member,
2431
3175
  expense,
2432
3176
  settlement,
3177
+ order,
2433
3178
  view,
2434
3179
  stats
2435
3180
  };