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