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