@sonatel-os/strapi-plugin-split 0.1.0 → 0.3.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",
@@ -55,8 +58,22 @@ const EVENT = Object.freeze({
55
58
  SETTLEMENT_CREATED: "settlement.created",
56
59
  SETTLEMENT_CONFIRMED: "settlement.confirmed",
57
60
  SETTLEMENT_REJECTED: "settlement.rejected",
58
- SETTLEMENT_CANCELLED: "settlement.cancelled"
61
+ SETTLEMENT_CANCELLED: "settlement.cancelled",
62
+ ORDER_OPENED: "order.opened",
63
+ ORDER_CLOSED: "order.closed",
64
+ ORDER_CANCELLED: "order.cancelled"
59
65
  });
66
+ const ORDER_STATUS = Object.freeze({
67
+ /** Members add and change what they take, until the closing time if there is one. */
68
+ OPEN: "open",
69
+ /** The organiser closed it: it became one expense. */
70
+ CLOSED: "closed",
71
+ /** The organiser dropped it; nothing was written. */
72
+ CANCELLED: "cancelled"
73
+ });
74
+ const ORDER_MAX_ITEMS = 30;
75
+ const ORDER_MAX_QUANTITY = 99;
76
+ const ORDER_LIST_SIZE = 20;
60
77
  const DEFAULT_LIMITS = Object.freeze({
61
78
  maxGroupsPerPerson: 50,
62
79
  maxMembersPerGroup: 50,
@@ -98,7 +115,10 @@ const ERROR_CODES = Object.freeze({
98
115
  SETTLEMENT_NOT_FOUND: "SETTLEMENT_NOT_FOUND",
99
116
  SETTLEMENT_EXCEEDS_DEBT: "SETTLEMENT_EXCEEDS_DEBT",
100
117
  SETTLEMENT_NOT_PENDING: "SETTLEMENT_NOT_PENDING",
101
- METHOD_UNKNOWN: "METHOD_UNKNOWN"
118
+ METHOD_UNKNOWN: "METHOD_UNKNOWN",
119
+ ORDER_NOT_FOUND: "ORDER_NOT_FOUND",
120
+ ORDER_CLOSED: "ORDER_CLOSED",
121
+ ORDER_EMPTY: "ORDER_EMPTY"
102
122
  });
103
123
  const ACTIONS = [
104
124
  { section: "plugins", uid: RBAC.ACCESS, displayName: `Access the ${PLUGIN_DISPLAY_NAME} module` },
@@ -211,18 +231,18 @@ const config = {
211
231
  }
212
232
  }
213
233
  };
214
- const kind$6 = "collectionType";
215
- const collectionName$6 = "split_people";
216
- const info$6 = {
234
+ const kind$9 = "collectionType";
235
+ const collectionName$9 = "split_people";
236
+ const info$9 = {
217
237
  singularName: "person",
218
238
  pluralName: "people",
219
239
  displayName: "Split Person",
220
240
  description: "Someone using the ledger, identified by the external id the host sends in the person header."
221
241
  };
222
- const options$6 = {
242
+ const options$9 = {
223
243
  draftAndPublish: false
224
244
  };
225
- const pluginOptions$6 = {
245
+ const pluginOptions$9 = {
226
246
  "content-manager": {
227
247
  visible: false
228
248
  },
@@ -230,7 +250,7 @@ const pluginOptions$6 = {
230
250
  visible: false
231
251
  }
232
252
  };
233
- const attributes$6 = {
253
+ const attributes$9 = {
234
254
  externalId: {
235
255
  type: "string",
236
256
  maxLength: 190,
@@ -261,27 +281,27 @@ const attributes$6 = {
261
281
  mappedBy: "person"
262
282
  }
263
283
  };
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 = {
284
+ const schema$9 = {
285
+ kind: kind$9,
286
+ collectionName: collectionName$9,
287
+ info: info$9,
288
+ options: options$9,
289
+ pluginOptions: pluginOptions$9,
290
+ attributes: attributes$9
291
+ };
292
+ const person$2 = { schema: schema$9 };
293
+ const kind$8 = "collectionType";
294
+ const collectionName$8 = "split_groups";
295
+ const info$8 = {
276
296
  singularName: "group",
277
297
  pluralName: "groups",
278
298
  displayName: "Split Group",
279
299
  description: "People sharing expenses."
280
300
  };
281
- const options$5 = {
301
+ const options$8 = {
282
302
  draftAndPublish: false
283
303
  };
284
- const pluginOptions$5 = {
304
+ const pluginOptions$8 = {
285
305
  "content-manager": {
286
306
  visible: false
287
307
  },
@@ -289,7 +309,7 @@ const pluginOptions$5 = {
289
309
  visible: false
290
310
  }
291
311
  };
292
- const attributes$5 = {
312
+ const attributes$8 = {
293
313
  name: {
294
314
  type: "string",
295
315
  maxLength: 80,
@@ -319,27 +339,27 @@ const attributes$5 = {
319
339
  mappedBy: "group"
320
340
  }
321
341
  };
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 = {
342
+ const schema$8 = {
343
+ kind: kind$8,
344
+ collectionName: collectionName$8,
345
+ info: info$8,
346
+ options: options$8,
347
+ pluginOptions: pluginOptions$8,
348
+ attributes: attributes$8
349
+ };
350
+ const group$1 = { schema: schema$8 };
351
+ const kind$7 = "collectionType";
352
+ const collectionName$7 = "split_members";
353
+ const info$7 = {
334
354
  singularName: "member",
335
355
  pluralName: "members",
336
356
  displayName: "Split Member",
337
357
  description: "A seat in a group: a registered person, or someone a member added by name (and maybe phone) who has not opened the app yet."
338
358
  };
339
- const options$4 = {
359
+ const options$7 = {
340
360
  draftAndPublish: false
341
361
  };
342
- const pluginOptions$4 = {
362
+ const pluginOptions$7 = {
343
363
  "content-manager": {
344
364
  visible: false
345
365
  },
@@ -347,7 +367,7 @@ const pluginOptions$4 = {
347
367
  visible: false
348
368
  }
349
369
  };
350
- const attributes$4 = {
370
+ const attributes$7 = {
351
371
  group: {
352
372
  type: "relation",
353
373
  relation: "manyToOne",
@@ -386,27 +406,27 @@ const attributes$4 = {
386
406
  type: "datetime"
387
407
  }
388
408
  };
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
409
+ const schema$7 = {
410
+ kind: kind$7,
411
+ collectionName: collectionName$7,
412
+ info: info$7,
413
+ options: options$7,
414
+ pluginOptions: pluginOptions$7,
415
+ attributes: attributes$7
396
416
  };
397
- const member$1 = { schema: schema$4 };
398
- const kind$3 = "collectionType";
399
- const collectionName$3 = "split_expenses";
400
- const info$3 = {
417
+ const member$1 = { schema: schema$7 };
418
+ const kind$6 = "collectionType";
419
+ const collectionName$6 = "split_expenses";
420
+ const info$6 = {
401
421
  singularName: "expense",
402
422
  pluralName: "expenses",
403
423
  displayName: "Split Expense",
404
424
  description: "Something one member paid for the others."
405
425
  };
406
- const options$3 = {
426
+ const options$6 = {
407
427
  draftAndPublish: false
408
428
  };
409
- const pluginOptions$3 = {
429
+ const pluginOptions$6 = {
410
430
  "content-manager": {
411
431
  visible: false
412
432
  },
@@ -414,7 +434,7 @@ const pluginOptions$3 = {
414
434
  visible: false
415
435
  }
416
436
  };
417
- const attributes$3 = {
437
+ const attributes$6 = {
418
438
  group: {
419
439
  type: "relation",
420
440
  relation: "manyToOne",
@@ -473,27 +493,27 @@ const attributes$3 = {
473
493
  mappedBy: "expense"
474
494
  }
475
495
  };
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
496
+ const schema$6 = {
497
+ kind: kind$6,
498
+ collectionName: collectionName$6,
499
+ info: info$6,
500
+ options: options$6,
501
+ pluginOptions: pluginOptions$6,
502
+ attributes: attributes$6
483
503
  };
484
- const expense$1 = { schema: schema$3 };
485
- const kind$2 = "collectionType";
486
- const collectionName$2 = "split_shares";
487
- const info$2 = {
504
+ const expense$1 = { schema: schema$6 };
505
+ const kind$5 = "collectionType";
506
+ const collectionName$5 = "split_shares";
507
+ const info$5 = {
488
508
  singularName: "share",
489
509
  pluralName: "shares",
490
510
  displayName: "Split Share",
491
511
  description: "What one member owes of one expense."
492
512
  };
493
- const options$2 = {
513
+ const options$5 = {
494
514
  draftAndPublish: false
495
515
  };
496
- const pluginOptions$2 = {
516
+ const pluginOptions$5 = {
497
517
  "content-manager": {
498
518
  visible: false
499
519
  },
@@ -501,7 +521,7 @@ const pluginOptions$2 = {
501
521
  visible: false
502
522
  }
503
523
  };
504
- const attributes$2 = {
524
+ const attributes$5 = {
505
525
  expense: {
506
526
  type: "relation",
507
527
  relation: "manyToOne",
@@ -523,27 +543,27 @@ const attributes$2 = {
523
543
  "default": 0
524
544
  }
525
545
  };
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
546
+ const schema$5 = {
547
+ kind: kind$5,
548
+ collectionName: collectionName$5,
549
+ info: info$5,
550
+ options: options$5,
551
+ pluginOptions: pluginOptions$5,
552
+ attributes: attributes$5
533
553
  };
534
- const share = { schema: schema$2 };
535
- const kind$1 = "collectionType";
536
- const collectionName$1 = "split_settlements";
537
- const info$1 = {
554
+ const share = { schema: schema$5 };
555
+ const kind$4 = "collectionType";
556
+ const collectionName$4 = "split_settlements";
557
+ const info$4 = {
538
558
  singularName: "settlement",
539
559
  pluralName: "settlements",
540
560
  displayName: "Split Settlement",
541
561
  description: "A payment from one member to another that reduces what is owed."
542
562
  };
543
- const options$1 = {
563
+ const options$4 = {
544
564
  draftAndPublish: false
545
565
  };
546
- const pluginOptions$1 = {
566
+ const pluginOptions$4 = {
547
567
  "content-manager": {
548
568
  visible: false
549
569
  },
@@ -551,7 +571,7 @@ const pluginOptions$1 = {
551
571
  visible: false
552
572
  }
553
573
  };
554
- const attributes$1 = {
574
+ const attributes$4 = {
555
575
  group: {
556
576
  type: "relation",
557
577
  relation: "manyToOne",
@@ -614,27 +634,27 @@ const attributes$1 = {
614
634
  target: "plugin::split.person"
615
635
  }
616
636
  };
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
637
+ const schema$4 = {
638
+ kind: kind$4,
639
+ collectionName: collectionName$4,
640
+ info: info$4,
641
+ options: options$4,
642
+ pluginOptions: pluginOptions$4,
643
+ attributes: attributes$4
624
644
  };
625
- const settlement$1 = { schema: schema$1 };
626
- const kind = "collectionType";
627
- const collectionName = "split_events";
628
- const info = {
645
+ const settlement$1 = { schema: schema$4 };
646
+ const kind$3 = "collectionType";
647
+ const collectionName$3 = "split_events";
648
+ const info$3 = {
629
649
  singularName: "event",
630
650
  pluralName: "events",
631
651
  displayName: "Split Event",
632
652
  description: "Audit trail: who did what in which group."
633
653
  };
634
- const options = {
654
+ const options$3 = {
635
655
  draftAndPublish: false
636
656
  };
637
- const pluginOptions = {
657
+ const pluginOptions$3 = {
638
658
  "content-manager": {
639
659
  visible: false
640
660
  },
@@ -642,7 +662,7 @@ const pluginOptions = {
642
662
  visible: false
643
663
  }
644
664
  };
645
- const attributes = {
665
+ const attributes$3 = {
646
666
  group: {
647
667
  type: "relation",
648
668
  relation: "manyToOne",
@@ -670,6 +690,175 @@ const attributes = {
670
690
  required: true
671
691
  }
672
692
  };
693
+ const schema$3 = {
694
+ kind: kind$3,
695
+ collectionName: collectionName$3,
696
+ info: info$3,
697
+ options: options$3,
698
+ pluginOptions: pluginOptions$3,
699
+ attributes: attributes$3
700
+ };
701
+ const event = { schema: schema$3 };
702
+ const kind$2 = "collectionType";
703
+ const collectionName$2 = "split_orders";
704
+ const info$2 = {
705
+ singularName: "order",
706
+ pluralName: "orders",
707
+ displayName: "Split Order",
708
+ description: "A list of priced items the members of a group order from until it closes; closing it writes one expense."
709
+ };
710
+ const options$2 = {
711
+ draftAndPublish: false
712
+ };
713
+ const pluginOptions$2 = {
714
+ "content-manager": {
715
+ visible: false
716
+ },
717
+ "content-type-builder": {
718
+ visible: false
719
+ }
720
+ };
721
+ const attributes$2 = {
722
+ group: {
723
+ type: "relation",
724
+ relation: "manyToOne",
725
+ target: "plugin::split.group"
726
+ },
727
+ organizer: {
728
+ type: "relation",
729
+ relation: "manyToOne",
730
+ target: "plugin::split.member"
731
+ },
732
+ title: {
733
+ type: "string",
734
+ maxLength: 120,
735
+ required: true
736
+ },
737
+ closesAt: {
738
+ type: "datetime"
739
+ },
740
+ status: {
741
+ type: "enumeration",
742
+ "enum": [
743
+ "open",
744
+ "closed",
745
+ "cancelled"
746
+ ],
747
+ "default": "open",
748
+ required: true
749
+ },
750
+ deliveryFee: {
751
+ type: "integer",
752
+ "default": 0,
753
+ min: 0
754
+ },
755
+ expenseRef: {
756
+ type: "string",
757
+ maxLength: 64
758
+ },
759
+ closedAt: {
760
+ type: "datetime"
761
+ }
762
+ };
763
+ const schema$2 = {
764
+ kind: kind$2,
765
+ collectionName: collectionName$2,
766
+ info: info$2,
767
+ options: options$2,
768
+ pluginOptions: pluginOptions$2,
769
+ attributes: attributes$2
770
+ };
771
+ const order$1 = { schema: schema$2 };
772
+ const kind$1 = "collectionType";
773
+ const collectionName$1 = "split_order_items";
774
+ const info$1 = {
775
+ singularName: "order-item",
776
+ pluralName: "order-items",
777
+ displayName: "Split Order Item",
778
+ description: "One thing that can be ordered, at a unit price."
779
+ };
780
+ const options$1 = {
781
+ draftAndPublish: false
782
+ };
783
+ const pluginOptions$1 = {
784
+ "content-manager": {
785
+ visible: false
786
+ },
787
+ "content-type-builder": {
788
+ visible: false
789
+ }
790
+ };
791
+ const attributes$1 = {
792
+ order: {
793
+ type: "relation",
794
+ relation: "manyToOne",
795
+ target: "plugin::split.order"
796
+ },
797
+ label: {
798
+ type: "string",
799
+ maxLength: 120,
800
+ required: true
801
+ },
802
+ price: {
803
+ type: "integer",
804
+ required: true,
805
+ min: 1
806
+ },
807
+ position: {
808
+ type: "integer",
809
+ "default": 0
810
+ }
811
+ };
812
+ const schema$1 = {
813
+ kind: kind$1,
814
+ collectionName: collectionName$1,
815
+ info: info$1,
816
+ options: options$1,
817
+ pluginOptions: pluginOptions$1,
818
+ attributes: attributes$1
819
+ };
820
+ const orderItem = { schema: schema$1 };
821
+ const kind = "collectionType";
822
+ const collectionName = "split_order_lines";
823
+ const info = {
824
+ singularName: "order-line",
825
+ pluralName: "order-lines",
826
+ displayName: "Split Order Line",
827
+ description: "How many of one item one member takes."
828
+ };
829
+ const options = {
830
+ draftAndPublish: false
831
+ };
832
+ const pluginOptions = {
833
+ "content-manager": {
834
+ visible: false
835
+ },
836
+ "content-type-builder": {
837
+ visible: false
838
+ }
839
+ };
840
+ const attributes = {
841
+ order: {
842
+ type: "relation",
843
+ relation: "manyToOne",
844
+ target: "plugin::split.order"
845
+ },
846
+ item: {
847
+ type: "relation",
848
+ relation: "manyToOne",
849
+ target: "plugin::split.order-item"
850
+ },
851
+ member: {
852
+ type: "relation",
853
+ relation: "manyToOne",
854
+ target: "plugin::split.member"
855
+ },
856
+ quantity: {
857
+ type: "integer",
858
+ required: true,
859
+ min: 1
860
+ }
861
+ };
673
862
  const schema = {
674
863
  kind,
675
864
  collectionName,
@@ -678,8 +867,19 @@ const schema = {
678
867
  pluginOptions,
679
868
  attributes
680
869
  };
681
- const event = { schema };
682
- const contentTypes = { person: person$2, group: group$1, member: member$1, expense: expense$1, share, settlement: settlement$1, event };
870
+ const orderLine = { schema };
871
+ const contentTypes = {
872
+ person: person$2,
873
+ group: group$1,
874
+ member: member$1,
875
+ expense: expense$1,
876
+ share,
877
+ settlement: settlement$1,
878
+ event,
879
+ order: order$1,
880
+ "order-item": orderItem,
881
+ "order-line": orderLine
882
+ };
683
883
  class SplitError extends Error {
684
884
  /**
685
885
  * @param {number} status HTTP status
@@ -751,6 +951,7 @@ const app = ({ strapi }) => {
751
951
  const viewer = (ctx) => ctx.state.splitPerson;
752
952
  const seat = (ctx, options2) => svc("group").seat(viewer(ctx), ctx.params.group, options2);
753
953
  const writable = (ctx) => seat(ctx, { writable: true });
954
+ const orderView = (ctx, mine, order2) => svc("order").view(order2, mine, viewer(ctx), { detailed: true });
754
955
  return {
755
956
  // ── Person ───────────────────────────────────────────────────────────
756
957
  me: handle(strapi, async (ctx) => {
@@ -850,6 +1051,36 @@ const app = ({ strapi }) => {
850
1051
  const mine = await seat(ctx);
851
1052
  const settlement2 = await svc("settlement").cancel(mine, ctx.params.settlement);
852
1053
  ok(ctx, svc("format").settlement(settlement2, mine.me, viewer(ctx)));
1054
+ }),
1055
+ // ── Orders ───────────────────────────────────────────────────────────
1056
+ orders: handle(
1057
+ strapi,
1058
+ async (ctx) => ok(ctx, await svc("order").list(await seat(ctx), viewer(ctx)))
1059
+ ),
1060
+ createOrder: handle(strapi, async (ctx) => {
1061
+ const mine = await writable(ctx);
1062
+ const order2 = await svc("order").create(mine, body(ctx));
1063
+ written(ctx, await orderView(ctx, mine, order2), false);
1064
+ }),
1065
+ order: handle(strapi, async (ctx) => {
1066
+ const mine = await seat(ctx);
1067
+ const order2 = await svc("order").find(mine.group, ctx.params.order);
1068
+ ok(ctx, await orderView(ctx, mine, order2));
1069
+ }),
1070
+ setOrderLines: handle(strapi, async (ctx) => {
1071
+ const mine = await writable(ctx);
1072
+ const order2 = await svc("order").setLines(mine, ctx.params.order, body(ctx));
1073
+ ok(ctx, await orderView(ctx, mine, order2));
1074
+ }),
1075
+ closeOrder: handle(strapi, async (ctx) => {
1076
+ const mine = await writable(ctx);
1077
+ const order2 = await svc("order").close(mine, ctx.params.order, body(ctx));
1078
+ ok(ctx, await orderView(ctx, mine, order2));
1079
+ }),
1080
+ cancelOrder: handle(strapi, async (ctx) => {
1081
+ const mine = await writable(ctx);
1082
+ const order2 = await svc("order").cancel(mine, ctx.params.order);
1083
+ ok(ctx, await orderView(ctx, mine, order2));
853
1084
  })
854
1085
  };
855
1086
  };
@@ -909,6 +1140,7 @@ const view = ({ strapi }) => {
909
1140
  return books.payments.filter((p) => p.to === me.id).map((p) => ({
910
1141
  from: format2.member(books.seatById.get(p.from), viewer),
911
1142
  amount: p.amount,
1143
+ receivable: Math.min(p.amount, books.room(p.from, me.id)),
912
1144
  pending: svc("ledger").pendingBetween(books, p.from, me.id)
913
1145
  }));
914
1146
  },
@@ -1180,6 +1412,8 @@ const contentApi = [
1180
1412
  route$1("POST", "/groups/join", "joinGroup"),
1181
1413
  route$1("GET", "/groups/:group", "group"),
1182
1414
  route$1("PATCH", "/groups/:group", "renameGroup"),
1415
+ // The same under PUT: some app runtimes (mini-programs) cannot send PATCH.
1416
+ route$1("PUT", "/groups/:group", "renameGroup"),
1183
1417
  route$1("POST", "/groups/:group/archive", "archiveGroup"),
1184
1418
  route$1("POST", "/groups/:group/leave", "leaveGroup"),
1185
1419
  // members
@@ -1195,7 +1429,14 @@ const contentApi = [
1195
1429
  route$1("POST", "/groups/:group/settlements", "createSettlement"),
1196
1430
  route$1("POST", "/groups/:group/settlements/:settlement/confirm", "confirmSettlement"),
1197
1431
  route$1("POST", "/groups/:group/settlements/:settlement/reject", "rejectSettlement"),
1198
- route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement")
1432
+ route$1("POST", "/groups/:group/settlements/:settlement/cancel", "cancelSettlement"),
1433
+ // orders: priced items the members order from; closing one writes an expense
1434
+ route$1("GET", "/groups/:group/orders", "orders"),
1435
+ route$1("POST", "/groups/:group/orders", "createOrder"),
1436
+ route$1("GET", "/groups/:group/orders/:order", "order"),
1437
+ route$1("PUT", "/groups/:group/orders/:order/lines", "setOrderLines"),
1438
+ route$1("POST", "/groups/:group/orders/:order/close", "closeOrder"),
1439
+ route$1("POST", "/groups/:group/orders/:order/cancel", "cancelOrder")
1199
1440
  ];
1200
1441
  const can = (...actions) => ({
1201
1442
  policies: [
@@ -1297,7 +1538,7 @@ const audit = ({ strapi }) => ({
1297
1538
  return { items, total };
1298
1539
  }
1299
1540
  });
1300
- const iso = (date) => date ? new Date(date).toISOString() : null;
1541
+ const iso$1 = (date) => date ? new Date(date).toISOString() : null;
1301
1542
  const format = () => ({
1302
1543
  person(p, isNew = false) {
1303
1544
  return { id: p.documentId, displayName: p.displayName ?? null, phone: p.phone ?? null, isNew };
@@ -1326,7 +1567,7 @@ const format = () => ({
1326
1567
  },
1327
1568
  /** A seat as an administrator sees it: the phone masked. */
1328
1569
  adminMember(m) {
1329
- return { ...this.member(m), phone: maskPhone(this.phoneOf(m)), joinedAt: iso(m.joinedAt) };
1570
+ return { ...this.member(m), phone: maskPhone(this.phoneOf(m)), joinedAt: iso$1(m.joinedAt) };
1330
1571
  },
1331
1572
  group(g) {
1332
1573
  return {
@@ -1334,7 +1575,7 @@ const format = () => ({
1334
1575
  name: g.name,
1335
1576
  inviteCode: g.inviteCode,
1336
1577
  isArchived: Boolean(g.archivedAt),
1337
- lastActivityAt: iso(g.lastActivityAt)
1578
+ lastActivityAt: iso$1(g.lastActivityAt)
1338
1579
  };
1339
1580
  },
1340
1581
  /**
@@ -1356,7 +1597,7 @@ const format = () => ({
1356
1597
  category: e.category ?? null,
1357
1598
  amount: e.amount,
1358
1599
  mode: e.mode,
1359
- spentAt: iso(e.spentAt),
1600
+ spentAt: iso$1(e.spentAt),
1360
1601
  paidBy: this.member(e.paidBy, viewer),
1361
1602
  yourShare: mine ? mine.amount : 0,
1362
1603
  shares,
@@ -1379,8 +1620,8 @@ const format = () => ({
1379
1620
  status: s.status,
1380
1621
  reference: s.reference ?? null,
1381
1622
  note: s.note ?? null,
1382
- declaredAt: iso(s.declaredAt),
1383
- resolvedAt: iso(s.resolvedAt),
1623
+ declaredAt: iso$1(s.declaredAt),
1624
+ resolvedAt: iso$1(s.resolvedAt),
1384
1625
  canConfirm: pending && idOf(s.to) === me.id,
1385
1626
  canCancel: pending && idOf(s.from) === me.id
1386
1627
  };
@@ -1910,7 +2151,7 @@ const member = ({ strapi }) => {
1910
2151
  }
1911
2152
  };
1912
2153
  };
1913
- const invalid = (message, details) => unprocessable(ERROR_CODES.SPLIT_INVALID, message, details);
2154
+ const invalid$1 = (message, details) => unprocessable(ERROR_CODES.SPLIT_INVALID, message, details);
1914
2155
  const sharesByWeight = (amount, weights) => {
1915
2156
  const total = weights.reduce((sum, w) => sum + w, 0);
1916
2157
  if (total === 0) return weights.map(() => 0);
@@ -1926,26 +2167,26 @@ const isCount = (n) => Number.isInteger(n) && n >= 0;
1926
2167
  const weightOf = (part, mode) => {
1927
2168
  if (mode === SPLIT_MODE.EQUAL) return 1;
1928
2169
  if (!isCount(part.weight) || part.weight > MAX_WEIGHT)
1929
- throw invalid(`Chaque part est un entier entre 0 et ${MAX_WEIGHT}.`);
2170
+ throw invalid$1(`Chaque part est un entier entre 0 et ${MAX_WEIGHT}.`);
1930
2171
  return part.weight;
1931
2172
  };
1932
2173
  const freeShares = (amount, parts) => {
1933
2174
  if (!parts.every((p) => isCount(p.amount)))
1934
- throw invalid("Chaque montant est un entier positif.");
2175
+ throw invalid$1("Chaque montant est un entier positif.");
1935
2176
  const sum = parts.reduce((total, p) => total + p.amount, 0);
1936
2177
  if (sum !== amount)
1937
- throw invalid("La somme des parts ne correspond pas au montant.", { amount, sum });
2178
+ throw invalid$1("La somme des parts ne correspond pas au montant.", { amount, sum });
1938
2179
  return parts.map((p) => p.amount);
1939
2180
  };
1940
2181
  const resolveShares = ({ amount, mode, parts }) => {
1941
- if (!Object.values(SPLIT_MODE).includes(mode)) throw invalid("Mode de partage inconnu.");
1942
- if (!Array.isArray(parts) || parts.length === 0) throw invalid("Personne ne participe.");
2182
+ if (!Object.values(SPLIT_MODE).includes(mode)) throw invalid$1("Mode de partage inconnu.");
2183
+ if (!Array.isArray(parts) || parts.length === 0) throw invalid$1("Personne ne participe.");
1943
2184
  if (new Set(parts.map((p) => String(p.member))).size !== parts.length)
1944
- throw invalid("Un membre apparaît deux fois.");
2185
+ throw invalid$1("Un membre apparaît deux fois.");
1945
2186
  const weights = mode === SPLIT_MODE.FREE ? null : parts.map((p) => weightOf(p, mode));
1946
2187
  const amounts = weights ? sharesByWeight(amount, weights) : freeShares(amount, parts);
1947
2188
  const shares = parts.map((p, i) => ({ member: p.member, amount: amounts[i], weight: weights ? weights[i] : 0 })).filter((s) => s.amount > 0);
1948
- if (shares.length === 0) throw invalid("Personne ne participe.");
2189
+ if (shares.length === 0) throw invalid$1("Personne ne participe.");
1949
2190
  return shares;
1950
2191
  };
1951
2192
  const POPULATE$1 = {
@@ -1970,8 +2211,8 @@ const expense = ({ strapi }) => {
1970
2211
  * paidBy: number, shares: Array<{ member: number, amount: number, weight: number }> }}
1971
2212
  */
1972
2213
  parse(input, active) {
1973
- const label = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
1974
- if (!label) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
2214
+ const label2 = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
2215
+ if (!label2) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
1975
2216
  const { maxAmount } = svc("settings").limits();
1976
2217
  const amount = input?.amount;
1977
2218
  if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
@@ -1990,7 +2231,7 @@ const expense = ({ strapi }) => {
1990
2231
  amount: p?.amount
1991
2232
  }));
1992
2233
  return {
1993
- label,
2234
+ label: label2,
1994
2235
  category: input?.category ? String(input.category).slice(0, 40) : null,
1995
2236
  amount,
1996
2237
  mode,
@@ -2129,7 +2370,10 @@ const settlement = ({ strapi }) => {
2129
2370
  const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
2130
2371
  const settlements = () => strapi.db.query(UID.SETTLEMENT);
2131
2372
  return {
2132
- /** What the caller sent, checked. The receiving seat is looked up in the group. */
2373
+ /**
2374
+ * What the caller sent, checked. The other seat is looked up in the group: the one paid
2375
+ * (`to`) when the caller pays, the one who paid (`from`) when the caller received.
2376
+ */
2133
2377
  async parse({ group: group2, me }, input) {
2134
2378
  const { maxAmount } = svc("settings").limits();
2135
2379
  const amount = input?.amount;
@@ -2137,14 +2381,20 @@ const settlement = ({ strapi }) => {
2137
2381
  throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
2138
2382
  const method = svc("settings").methods()[String(input?.method)];
2139
2383
  if (!method) throw badRequest(ERROR_CODES.METHOD_UNKNOWN, "Moyen de paiement inconnu.");
2140
- const to = await svc("member").find(group2, input?.to);
2141
- if (to.id === me.id)
2384
+ const received = input?.from != null;
2385
+ if (received && input?.to != null)
2386
+ throw badRequest(ERROR_CODES.VALIDATION, "Indique qui paie ou qui reçoit, pas les deux.");
2387
+ const other = await svc("member").find(group2, received ? input.from : input?.to);
2388
+ if (other.id === me.id)
2142
2389
  throw badRequest(ERROR_CODES.VALIDATION, "Tu ne peux pas te régler à toi-même.");
2390
+ const [from, to] = received ? [other, me] : [me, other];
2143
2391
  return {
2144
2392
  amount,
2393
+ from,
2145
2394
  to,
2395
+ received,
2146
2396
  method: String(input.method),
2147
- instant: method.instant || !to.person,
2397
+ instant: received || method.instant || !to.person,
2148
2398
  reference: text(input?.reference, REF_MAX),
2149
2399
  note: text(input?.note, NOTE_MAX),
2150
2400
  clientRef: text(input?.clientRef, REF_MAX)
@@ -2167,7 +2417,7 @@ const settlement = ({ strapi }) => {
2167
2417
  async write({ group: group2, me }, data) {
2168
2418
  await svc("group").lock(group2);
2169
2419
  const books = await svc("ledger").of(group2);
2170
- const outstanding = books.room(me.id, data.to.id);
2420
+ const outstanding = books.room(data.from.id, data.to.id);
2171
2421
  if (data.amount > outstanding)
2172
2422
  throw unprocessable(
2173
2423
  ERROR_CODES.SETTLEMENT_EXCEEDS_DEBT,
@@ -2178,7 +2428,7 @@ const settlement = ({ strapi }) => {
2178
2428
  return settlements().create({
2179
2429
  data: {
2180
2430
  group: group2.id,
2181
- from: me.id,
2431
+ from: data.from.id,
2182
2432
  to: data.to.id,
2183
2433
  amount: data.amount,
2184
2434
  method: data.method,
@@ -2193,8 +2443,8 @@ const settlement = ({ strapi }) => {
2193
2443
  });
2194
2444
  },
2195
2445
  /**
2196
- * @param {{ group: Object, me: Object }} seat the payer's
2197
- * @param {Object} input `{ to, amount, method, reference?, note?, clientRef? }`
2446
+ * @param {{ group: Object, me: Object }} seat the caller's: the payer's, or the receiver's
2447
+ * @param {Object} input `{ to | from, amount, method, reference?, note?, clientRef? }`
2198
2448
  * @returns {Promise<{ settlement: Object, replayed: boolean }>}
2199
2449
  */
2200
2450
  async create(seat, input) {
@@ -2212,7 +2462,8 @@ const settlement = ({ strapi }) => {
2212
2462
  amount: data.amount,
2213
2463
  method: data.method,
2214
2464
  status: created.status,
2215
- reference: data.reference
2465
+ reference: data.reference,
2466
+ declaredBy: data.received ? "receiver" : "payer"
2216
2467
  }
2217
2468
  });
2218
2469
  return { settlement: await this.one(created.id), replayed: false };
@@ -2309,6 +2560,327 @@ const settlement = ({ strapi }) => {
2309
2560
  }
2310
2561
  };
2311
2562
  };
2563
+ const orderTotals = ({ items, lines, deliveryFee = 0 }) => {
2564
+ const priceOf = new Map(items.map((item) => [item.id, item.price]));
2565
+ const taken = /* @__PURE__ */ new Map();
2566
+ for (const { item, member: member2, quantity } of lines) {
2567
+ if (!priceOf.has(item) || quantity <= 0) continue;
2568
+ const sofar = taken.get(member2) ?? { quantity: 0, subtotal: 0 };
2569
+ taken.set(member2, {
2570
+ quantity: sofar.quantity + quantity,
2571
+ subtotal: sofar.subtotal + quantity * priceOf.get(item)
2572
+ });
2573
+ }
2574
+ const members = [...taken.keys()].sort((a, b) => a - b);
2575
+ const fees = sharesByWeight(
2576
+ deliveryFee,
2577
+ members.map(() => 1)
2578
+ );
2579
+ const people = members.map((member2, i) => ({
2580
+ member: member2,
2581
+ ...taken.get(member2),
2582
+ delivery: fees[i],
2583
+ total: taken.get(member2).subtotal + fees[i]
2584
+ }));
2585
+ const subtotal = people.reduce((sum, p) => sum + p.subtotal, 0);
2586
+ return { people, subtotal, total: subtotal + (people.length ? deliveryFee : 0) };
2587
+ };
2588
+ const LINE_POPULATE = { item: { select: ["id"] }, member: { select: ["id"] } };
2589
+ const ORDER_POPULATE = { organizer: { select: ["id"] } };
2590
+ const iso = (date) => date ? new Date(date).toISOString() : null;
2591
+ const label = (raw) => String(raw ?? "").trim().replace(/\s+/g, " ").slice(0, LABEL_MAX);
2592
+ const invalid = (message, details) => badRequest(ERROR_CODES.VALIDATION, message, details);
2593
+ const expenseRefOf = (order2) => `order:${order2.documentId}`;
2594
+ const order = ({ strapi }) => {
2595
+ const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
2596
+ const orders = () => strapi.db.query(UID.ORDER);
2597
+ const items = () => strapi.db.query(UID.ORDER_ITEM);
2598
+ const lines = () => strapi.db.query(UID.ORDER_LINE);
2599
+ return {
2600
+ /** Members can still say what they take. */
2601
+ accepts(order2, now = /* @__PURE__ */ new Date()) {
2602
+ return order2.status === ORDER_STATUS.OPEN && (!order2.closesAt || now < new Date(order2.closesAt));
2603
+ },
2604
+ /** When ordering stops: nothing, or a real date still ahead. */
2605
+ closesAt(raw) {
2606
+ if (raw == null || raw === "") return null;
2607
+ const date = new Date(raw);
2608
+ if (Number.isNaN(date.getTime()) || date <= /* @__PURE__ */ new Date())
2609
+ throw invalid("L'heure de clôture doit être à venir.");
2610
+ return date;
2611
+ },
2612
+ /** What the organiser sent, checked. */
2613
+ parse(input) {
2614
+ const title = label(input?.title);
2615
+ if (!title) throw invalid("Donne un nom à la commande.");
2616
+ const { maxAmount } = svc("settings").limits();
2617
+ const list = Array.isArray(input?.items) ? input.items : [];
2618
+ if (list.length === 0 || list.length > ORDER_MAX_ITEMS)
2619
+ throw invalid(`Entre 1 et ${ORDER_MAX_ITEMS} articles.`, { max: ORDER_MAX_ITEMS });
2620
+ const parsed = list.map((raw) => ({ label: label(raw?.label), price: raw?.price }));
2621
+ if (parsed.some((item) => !item.label)) throw invalid("Chaque article a un nom.");
2622
+ if (parsed.some((i) => !Number.isInteger(i.price) || i.price <= 0 || i.price > maxAmount))
2623
+ throw invalid("Chaque article a un prix.", { maxAmount });
2624
+ return { title, closesAt: this.closesAt(input?.closesAt), items: parsed };
2625
+ },
2626
+ /**
2627
+ * @param {{ group: Object, me: Object }} seat the organiser's
2628
+ * @param {{ title: string, closesAt?: string, items: Array<{ label: string, price: number }> }} input
2629
+ */
2630
+ async create({ group: group2, me }, input) {
2631
+ const data = this.parse(input);
2632
+ const order2 = await strapi.db.transaction(async () => {
2633
+ const created = await orders().create({
2634
+ data: {
2635
+ group: group2.id,
2636
+ organizer: me.id,
2637
+ title: data.title,
2638
+ closesAt: data.closesAt,
2639
+ status: ORDER_STATUS.OPEN,
2640
+ deliveryFee: 0
2641
+ }
2642
+ });
2643
+ for (const [position, item] of data.items.entries())
2644
+ await items().create({ data: { order: created.id, ...item, position } });
2645
+ return created;
2646
+ });
2647
+ await svc("audit").log({
2648
+ group: group2,
2649
+ actor: me.person,
2650
+ action: EVENT.ORDER_OPENED,
2651
+ targetId: order2.documentId,
2652
+ data: { items: data.items.length }
2653
+ });
2654
+ return this.find(group2, order2.documentId);
2655
+ },
2656
+ /** An order of this group. */
2657
+ async find(group2, documentId) {
2658
+ const order2 = await orders().findOne({
2659
+ where: { group: group2.id, documentId: String(documentId) },
2660
+ populate: ORDER_POPULATE
2661
+ });
2662
+ if (!order2) throw notFound(ERROR_CODES.ORDER_NOT_FOUND, "Commande introuvable.");
2663
+ return order2;
2664
+ },
2665
+ /** An order with what it offers and what was taken, relations as ids. */
2666
+ async load(order2) {
2667
+ const [offered, taken] = await Promise.all([
2668
+ items().findMany({ where: { order: order2.id }, orderBy: [{ position: "asc" }] }),
2669
+ lines().findMany({ where: { order: order2.id }, populate: LINE_POPULATE })
2670
+ ]);
2671
+ return {
2672
+ order: order2,
2673
+ items: offered,
2674
+ lines: taken.map((l) => ({
2675
+ item: idOf(l.item),
2676
+ member: idOf(l.member),
2677
+ quantity: l.quantity
2678
+ }))
2679
+ };
2680
+ },
2681
+ assertOrganizer(order2, me) {
2682
+ if (idOf(order2.organizer) !== me.id)
2683
+ throw forbidden(
2684
+ ERROR_CODES.NOT_ALLOWED,
2685
+ "Seul l'organisateur de la commande peut faire ça."
2686
+ );
2687
+ },
2688
+ assertOpen(order2) {
2689
+ if (order2.status !== ORDER_STATUS.OPEN)
2690
+ throw unprocessable(ERROR_CODES.ORDER_CLOSED, "Cette commande est close.", {
2691
+ status: order2.status
2692
+ });
2693
+ },
2694
+ /** The quantities sent, by item row id; unknown items and odd quantities are refused. */
2695
+ quantities(input, offered) {
2696
+ const byDoc = new Map(offered.map((item) => [item.documentId, item.id]));
2697
+ const list = Array.isArray(input?.lines) ? input.lines : null;
2698
+ if (!list) throw invalid("Liste de quantités invalide.");
2699
+ const wanted = /* @__PURE__ */ new Map();
2700
+ for (const raw of list) {
2701
+ const item = byDoc.get(String(raw?.item));
2702
+ if (!item) throw invalid("Cet article n'est pas dans la commande.");
2703
+ const quantity = raw?.quantity;
2704
+ if (!Number.isInteger(quantity) || quantity < 0 || quantity > ORDER_MAX_QUANTITY)
2705
+ throw invalid(`Une quantité va de 0 à ${ORDER_MAX_QUANTITY}.`, {
2706
+ max: ORDER_MAX_QUANTITY
2707
+ });
2708
+ wanted.set(item, quantity);
2709
+ }
2710
+ return wanted;
2711
+ },
2712
+ /**
2713
+ * What one member takes, replaced whole. A member sets their own; the organiser sets anyone's
2714
+ * (someone who told them, someone without the app), and still can after the closing time.
2715
+ * @param {{ group: Object, me: Object }} seat the caller's
2716
+ * @param {string} documentId the order
2717
+ * @param {{ member?: string, lines: Array<{ item: string, quantity: number }> }} input
2718
+ */
2719
+ async setLines({ group: group2, me }, documentId, input) {
2720
+ const order2 = await this.find(group2, documentId);
2721
+ this.assertOpen(order2);
2722
+ const organizes = idOf(order2.organizer) === me.id;
2723
+ const target = input?.member ? await svc("member").find(group2, input.member) : me;
2724
+ if (target.id !== me.id && !organizes)
2725
+ throw forbidden(ERROR_CODES.NOT_ALLOWED, "Tu ne peux commander que pour toi.");
2726
+ if (!organizes && !this.accepts(order2))
2727
+ throw unprocessable(ERROR_CODES.ORDER_CLOSED, "Les commandes sont closes.", {
2728
+ status: order2.status
2729
+ });
2730
+ const { items: offered } = await this.load(order2);
2731
+ const wanted = this.quantities(input, offered);
2732
+ await strapi.db.transaction(async () => {
2733
+ await lines().deleteMany({ where: { order: order2.id, member: target.id } });
2734
+ for (const [item, quantity] of wanted)
2735
+ if (quantity > 0)
2736
+ await lines().create({
2737
+ data: { order: order2.id, item, member: target.id, quantity }
2738
+ });
2739
+ });
2740
+ return order2;
2741
+ },
2742
+ /**
2743
+ * Close the order: one expense, paid by the organiser, each member owing what they took and
2744
+ * an equal part of the delivery. Closing an order already closed answers it as it is.
2745
+ * @param {{ group: Object, me: Object }} seat the organiser's
2746
+ * @param {string} documentId
2747
+ * @param {{ deliveryFee?: number, category?: string }} [input]
2748
+ */
2749
+ async close(seat, documentId, input = {}) {
2750
+ const { group: group2, me } = seat;
2751
+ const order2 = await this.find(group2, documentId);
2752
+ this.assertOrganizer(order2, me);
2753
+ if (order2.status === ORDER_STATUS.CLOSED) return order2;
2754
+ this.assertOpen(order2);
2755
+ const { maxAmount } = svc("settings").limits();
2756
+ const deliveryFee = input?.deliveryFee ?? 0;
2757
+ if (!Number.isInteger(deliveryFee) || deliveryFee < 0 || deliveryFee > maxAmount)
2758
+ throw invalid("Frais de livraison invalides.", { maxAmount });
2759
+ const [{ items: offered, lines: taken }, books] = await Promise.all([
2760
+ this.load(order2),
2761
+ svc("ledger").of(group2)
2762
+ ]);
2763
+ const here = new Set(books.active.map((s) => s.id));
2764
+ const totals = orderTotals({
2765
+ items: offered,
2766
+ lines: taken.filter((l) => here.has(l.member)),
2767
+ deliveryFee
2768
+ });
2769
+ if (totals.people.length === 0)
2770
+ throw unprocessable(ERROR_CODES.ORDER_EMPTY, "Personne n'a rien commandé.");
2771
+ const { expense: expense2 } = await svc("expense").create(seat, {
2772
+ label: order2.title,
2773
+ amount: totals.total,
2774
+ category: input?.category ?? null,
2775
+ mode: SPLIT_MODE.FREE,
2776
+ paidBy: me.documentId,
2777
+ clientRef: expenseRefOf(order2),
2778
+ shares: totals.people.map((p) => ({
2779
+ member: books.seatById.get(p.member).documentId,
2780
+ amount: p.total
2781
+ }))
2782
+ });
2783
+ await orders().update({
2784
+ where: { id: order2.id },
2785
+ data: {
2786
+ status: ORDER_STATUS.CLOSED,
2787
+ deliveryFee,
2788
+ expenseRef: expense2.documentId,
2789
+ closedAt: /* @__PURE__ */ new Date()
2790
+ }
2791
+ });
2792
+ await svc("audit").log({
2793
+ group: group2,
2794
+ actor: me.person,
2795
+ action: EVENT.ORDER_CLOSED,
2796
+ targetId: order2.documentId,
2797
+ data: { amount: totals.total, deliveryFee, people: totals.people.length }
2798
+ });
2799
+ return this.find(group2, documentId);
2800
+ },
2801
+ /** Drop an open order: nothing was written, nothing is owed. */
2802
+ async cancel({ group: group2, me }, documentId) {
2803
+ const order2 = await this.find(group2, documentId);
2804
+ this.assertOrganizer(order2, me);
2805
+ this.assertOpen(order2);
2806
+ await orders().update({
2807
+ where: { id: order2.id },
2808
+ data: { status: ORDER_STATUS.CANCELLED, closedAt: /* @__PURE__ */ new Date() }
2809
+ });
2810
+ await svc("audit").log({
2811
+ group: group2,
2812
+ actor: me.person,
2813
+ action: EVENT.ORDER_CANCELLED,
2814
+ targetId: order2.documentId
2815
+ });
2816
+ return this.find(group2, documentId);
2817
+ },
2818
+ /**
2819
+ * An order as a member reads it.
2820
+ * @param {Object} order
2821
+ * @param {{ group: Object, me: Object }} seat the viewer's
2822
+ * @param {Object} viewer the person asking
2823
+ * @param {{ detailed?: boolean }} [options] `detailed` adds the items and who took what
2824
+ */
2825
+ async view(order2, { group: group2, me }, viewer, { detailed = false } = {}) {
2826
+ const [{ items: offered, lines: taken }, books] = await Promise.all([
2827
+ this.load(order2),
2828
+ svc("ledger").of(group2)
2829
+ ]);
2830
+ const format2 = svc("format");
2831
+ const totals = orderTotals({ items: offered, lines: taken, deliveryFee: order2.deliveryFee });
2832
+ const docOf = new Map(offered.map((item) => [item.id, item.documentId]));
2833
+ const none = { quantity: 0, subtotal: 0, delivery: 0, total: 0 };
2834
+ const { member: _mine, ...yours } = totals.people.find((p) => p.member === me.id) ?? none;
2835
+ const summary = {
2836
+ id: order2.documentId,
2837
+ title: order2.title,
2838
+ status: order2.status,
2839
+ closesAt: iso(order2.closesAt),
2840
+ closedAt: iso(order2.closedAt),
2841
+ acceptsOrders: this.accepts(order2),
2842
+ isOrganizer: idOf(order2.organizer) === me.id,
2843
+ organizer: format2.member(books.seatById.get(idOf(order2.organizer)), viewer),
2844
+ deliveryFee: order2.deliveryFee ?? 0,
2845
+ expenseId: order2.expenseRef ?? null,
2846
+ participantCount: totals.people.length,
2847
+ subtotal: totals.subtotal,
2848
+ total: totals.total,
2849
+ yours
2850
+ };
2851
+ if (!detailed) return summary;
2852
+ const takenBy = (member2) => taken.filter((l) => l.member === member2 && docOf.has(l.item)).map((l) => ({ item: docOf.get(l.item), quantity: l.quantity }));
2853
+ const quantityOf = (item, member2) => taken.filter((l) => l.item === item && (member2 == null || l.member === member2)).reduce((sum, l) => sum + l.quantity, 0);
2854
+ return {
2855
+ ...summary,
2856
+ items: offered.map((item) => ({
2857
+ id: item.documentId,
2858
+ label: item.label,
2859
+ price: item.price,
2860
+ quantity: quantityOf(item.id),
2861
+ yours: quantityOf(item.id, me.id)
2862
+ })),
2863
+ people: totals.people.map(({ member: member2, ...sums }) => ({
2864
+ member: format2.member(books.seatById.get(member2), viewer),
2865
+ ...sums,
2866
+ lines: takenBy(member2)
2867
+ }))
2868
+ };
2869
+ },
2870
+ /** The group's orders as a member reads them: the open ones first, then the latest. */
2871
+ async list(seat, viewer) {
2872
+ const rows = await orders().findMany({
2873
+ where: { group: seat.group.id, status: { $in: [ORDER_STATUS.OPEN, ORDER_STATUS.CLOSED] } },
2874
+ populate: ORDER_POPULATE,
2875
+ orderBy: [{ id: "desc" }],
2876
+ limit: ORDER_LIST_SIZE
2877
+ });
2878
+ const open = (order2) => Number(order2.status === ORDER_STATUS.OPEN);
2879
+ const sorted = [...rows].sort((a, b) => open(b) - open(a));
2880
+ return Promise.all(sorted.map((order2) => this.view(order2, seat, viewer)));
2881
+ }
2882
+ };
2883
+ };
2312
2884
  const ADMIN_RECENT = 50;
2313
2885
  const stats = ({ strapi }) => {
2314
2886
  const svc = (name) => strapi.plugin(PLUGIN_ID).service(name);
@@ -2417,6 +2989,7 @@ const services = {
2417
2989
  member,
2418
2990
  expense,
2419
2991
  settlement,
2992
+ order,
2420
2993
  view,
2421
2994
  stats
2422
2995
  };