@sonatel-os/strapi-plugin-split 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,165 @@
1
+ import { jsxs, jsx } from "react/jsx-runtime";
2
+ import { Flex, Grid, Field, NumberInput, Button, Box, Typography } from "@strapi/design-system";
3
+ import { useNotification, useRBAC, Page, Layouts } from "@strapi/strapi/admin";
4
+ import { q as useSetLimitsMutation, j as errorMessage, r as useGetSettingsQuery, b as Section, M as Mono } from "./format-CNjIwTKo.mjs";
5
+ import { useState } from "react";
6
+ import { Check } from "@strapi/icons";
7
+ import { a as PERMISSIONS } from "./index-oF7vL92A.mjs";
8
+ const FIELDS = [
9
+ {
10
+ key: "maxGroupsPerPerson",
11
+ label: "Groups per person",
12
+ hint: "Groups a person sits in, archived ones included."
13
+ },
14
+ { key: "maxMembersPerGroup", label: "Members per group", hint: "Seats of one group." },
15
+ {
16
+ key: "maxAmount",
17
+ label: "Largest amount",
18
+ hint: "One expense or one settlement, in the currency's smallest unit."
19
+ }
20
+ ];
21
+ const errorOf = (value, ceiling) => Number.isInteger(value) && value > 0 && value <= ceiling ? void 0 : `A whole number from 1 to ${ceiling.toLocaleString()}.`;
22
+ const LimitsForm = ({ limits = {}, ceilings = {}, canEdit }) => {
23
+ const { toggleNotification } = useNotification();
24
+ const [save, { isLoading }] = useSetLimitsMutation();
25
+ const [draft, setDraft] = useState(limits);
26
+ const errors = Object.fromEntries(
27
+ FIELDS.map((f) => [f.key, errorOf(draft[f.key], ceilings[f.key])])
28
+ );
29
+ const changed = FIELDS.some((f) => draft[f.key] !== limits[f.key]);
30
+ const valid = FIELDS.every((f) => !errors[f.key]);
31
+ const onSave = async () => {
32
+ try {
33
+ setDraft(await save(draft).unwrap());
34
+ toggleNotification({ type: "success", message: "Limits saved. They apply from now on." });
35
+ } catch (err) {
36
+ toggleNotification({ type: "danger", message: errorMessage(err) });
37
+ }
38
+ };
39
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 5, children: [
40
+ /* @__PURE__ */ jsx(Grid.Root, { gap: 5, children: FIELDS.map((f) => /* @__PURE__ */ jsx(Grid.Item, { col: 4, s: 12, direction: "column", alignItems: "stretch", children: /* @__PURE__ */ jsxs(Field.Root, { name: f.key, hint: f.hint, error: canEdit ? errors[f.key] : void 0, children: [
41
+ /* @__PURE__ */ jsx(Field.Label, { children: f.label }),
42
+ /* @__PURE__ */ jsx(
43
+ NumberInput,
44
+ {
45
+ value: draft[f.key],
46
+ disabled: !canEdit,
47
+ onValueChange: (value) => setDraft({ ...draft, [f.key]: value })
48
+ }
49
+ ),
50
+ /* @__PURE__ */ jsx(Field.Hint, {}),
51
+ /* @__PURE__ */ jsx(Field.Error, {})
52
+ ] }) }, f.key)) }),
53
+ canEdit ? /* @__PURE__ */ jsx(Flex, { justifyContent: "flex-end", children: /* @__PURE__ */ jsx(
54
+ Button,
55
+ {
56
+ startIcon: /* @__PURE__ */ jsx(Check, {}),
57
+ loading: isLoading,
58
+ disabled: !changed || !valid,
59
+ onClick: onSave,
60
+ children: "Save the limits"
61
+ }
62
+ ) }) : null
63
+ ] });
64
+ };
65
+ const Row = ({ k, v, hint }) => /* @__PURE__ */ jsxs(
66
+ Flex,
67
+ {
68
+ justifyContent: "space-between",
69
+ alignItems: "flex-start",
70
+ gap: 4,
71
+ paddingTop: 3,
72
+ paddingBottom: 3,
73
+ style: { borderBottom: "1px solid #eaeaef" },
74
+ children: [
75
+ /* @__PURE__ */ jsxs(Box, { style: { flex: 1, minWidth: 0 }, children: [
76
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "semiBold", tag: "p", children: k }),
77
+ hint ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", tag: "p", children: hint }) : null
78
+ ] }),
79
+ /* @__PURE__ */ jsx(Mono, { variant: "pi", fontWeight: "semiBold", children: String(v ?? "—") || "—" })
80
+ ]
81
+ }
82
+ );
83
+ const SettingsPage = () => {
84
+ const { data, isLoading, isError } = useGetSettingsQuery();
85
+ const { allowedActions, isLoading: checking } = useRBAC({ write: PERMISSIONS.settingsWrite });
86
+ if (isLoading || checking) return /* @__PURE__ */ jsx(Page.Loading, {});
87
+ if (isError) return /* @__PURE__ */ jsx(Page.Error, {});
88
+ const s = data ?? {};
89
+ const methods = Object.entries(s.methods ?? {});
90
+ return /* @__PURE__ */ jsx(Page.Protect, { permissions: PERMISSIONS.settingsRead, children: /* @__PURE__ */ jsxs(Page.Main, { children: [
91
+ /* @__PURE__ */ jsx(Page.Title, { children: "Split · Configuration" }),
92
+ /* @__PURE__ */ jsx(
93
+ Layouts.Header,
94
+ {
95
+ title: "Split configuration",
96
+ subtitle: "Read from config/plugins.js and the server environment. Only the limits are changed here."
97
+ }
98
+ ),
99
+ /* @__PURE__ */ jsx(Layouts.Content, { children: /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 6, children: [
100
+ /* @__PURE__ */ jsxs(
101
+ Section,
102
+ {
103
+ title: "Who is calling",
104
+ help: "The app routes under /api/split are protected by Strapi API tokens. The caller names the person with a header.",
105
+ children: [
106
+ /* @__PURE__ */ jsx(
107
+ Row,
108
+ {
109
+ k: "Person id header",
110
+ v: s.people?.idHeader,
111
+ hint: "Any stable id the host owns; a phone number is stored under one spelling."
112
+ }
113
+ ),
114
+ /* @__PURE__ */ jsx(
115
+ Row,
116
+ {
117
+ k: "Display name header",
118
+ v: s.people?.nameHeader,
119
+ hint: "Optional; refreshes the person's name."
120
+ }
121
+ ),
122
+ /* @__PURE__ */ jsx(Row, { k: "Create unknown people", v: s.people?.autoProvision ? "yes" : "no" }),
123
+ /* @__PURE__ */ jsx(
124
+ Row,
125
+ {
126
+ k: "Home country code",
127
+ v: s.countryCode,
128
+ hint: "Dropped from stored phone numbers."
129
+ }
130
+ )
131
+ ]
132
+ }
133
+ ),
134
+ /* @__PURE__ */ jsx(
135
+ Section,
136
+ {
137
+ title: "Limits",
138
+ help: "What is refused past these numbers. A change applies to what comes next: nothing that already exists is touched.",
139
+ index: 1,
140
+ children: /* @__PURE__ */ jsx(
141
+ LimitsForm,
142
+ {
143
+ limits: s.limits,
144
+ ceilings: s.limitCeilings,
145
+ canEdit: allowedActions.canWrite
146
+ }
147
+ )
148
+ }
149
+ ),
150
+ /* @__PURE__ */ jsx(Section, { title: "Groups", index: 2, children: /* @__PURE__ */ jsx(Row, { k: "Invite code prefix", v: s.inviteCodePrefix }) }),
151
+ /* @__PURE__ */ jsx(
152
+ Section,
153
+ {
154
+ title: "Settlement methods",
155
+ help: "An instant method is one the host pays itself: it is confirmed at once. The others wait for the receiver.",
156
+ index: 3,
157
+ children: methods.map(([name, m]) => /* @__PURE__ */ jsx(Row, { k: name, v: m.instant ? "instant" : "receiver confirms" }, name))
158
+ }
159
+ )
160
+ ] }) })
161
+ ] }) });
162
+ };
163
+ export {
164
+ SettingsPage
165
+ };
@@ -6,7 +6,7 @@ import "@strapi/icons/symbols";
6
6
  import { useNavigate } from "react-router-dom";
7
7
  import { styled, css, keyframes } from "styled-components";
8
8
  import { adminApi } from "@strapi/strapi/admin";
9
- import { P as PLUGIN_ID } from "./index-PFbwTznf.mjs";
9
+ import { P as PLUGIN_ID } from "./index-oF7vL92A.mjs";
10
10
  const SPRING = "cubic-bezier(0.32, 0.72, 0, 1)";
11
11
  const rise = keyframes`
12
12
  from { opacity: 0; transform: translateY(14px); filter: blur(6px); }
@@ -379,7 +379,12 @@ styled.span`
379
379
  flex-shrink: 0;
380
380
  `;
381
381
  const BASE = `/${PLUGIN_ID}`;
382
- const TAG = Object.freeze({ DASH: "SplitDashboard", GROUP: "SplitGroup", PERSON: "SplitPerson" });
382
+ const TAG = Object.freeze({
383
+ DASH: "SplitDashboard",
384
+ GROUP: "SplitGroup",
385
+ PERSON: "SplitPerson",
386
+ SETTINGS: "SplitSettings"
387
+ });
383
388
  const unwrap = (res) => res && typeof res === "object" && "data" in res ? res.data : res;
384
389
  const qs = (params = {}) => {
385
390
  const clean = Object.fromEntries(
@@ -426,7 +431,20 @@ const api = adminApi.enhanceEndpoints({ addTagTypes: Object.values(TAG) }).injec
426
431
  }),
427
432
  getSettlements: b.query({ query: (p) => `${BASE}/settlements${qs(p)}` }),
428
433
  getEvents: b.query({ query: (p) => `${BASE}/events${qs(p)}` }),
429
- getSettings: b.query({ query: () => `${BASE}/settings`, transformResponse: unwrap })
434
+ getSettings: b.query({
435
+ query: () => `${BASE}/settings`,
436
+ transformResponse: unwrap,
437
+ providesTags: [TAG.SETTINGS]
438
+ }),
439
+ setLimits: b.mutation({
440
+ query: (limits) => ({
441
+ url: `${BASE}/settings/limits`,
442
+ method: "PUT",
443
+ data: { data: limits }
444
+ }),
445
+ transformResponse: unwrap,
446
+ invalidatesTags: [TAG.SETTINGS]
447
+ })
430
448
  }),
431
449
  overrideExisting: true
432
450
  });
@@ -441,8 +459,27 @@ const {
441
459
  useSetPersonActiveMutation,
442
460
  useGetSettlementsQuery,
443
461
  useGetEventsQuery,
444
- useGetSettingsQuery
462
+ useGetSettingsQuery,
463
+ useSetLimitsMutation
445
464
  } = api;
465
+ const fmtDateTime = (value, locale) => {
466
+ if (!value) return "—";
467
+ try {
468
+ return new Intl.DateTimeFormat(locale ?? void 0, {
469
+ dateStyle: "medium",
470
+ timeStyle: "short"
471
+ }).format(new Date(value));
472
+ } catch {
473
+ return String(value);
474
+ }
475
+ };
476
+ const fmtNumber = (value, locale) => new Intl.NumberFormat(locale ?? void 0).format(Number(value ?? 0));
477
+ const fmtSigned = (value, locale) => {
478
+ const n = Number(value ?? 0);
479
+ const digits = fmtNumber(Math.abs(n), locale);
480
+ return n > 0 ? `+${digits}` : n < 0 ? `−${digits}` : digits;
481
+ };
482
+ const errorMessage = (err) => err?.data?.error?.message ?? err?.response?.data?.error?.message ?? err?.error?.message ?? err?.message ?? "Une erreur est survenue.";
446
483
  export {
447
484
  Bar as B,
448
485
  Eyebrow as E,
@@ -453,14 +490,19 @@ export {
453
490
  Section as b,
454
491
  useGetGroupsQuery as c,
455
492
  StatusBadge as d,
456
- useGetGroupQuery as e,
457
- useArchiveGroupMutation as f,
458
- useGetPeopleQuery as g,
459
- useGetPersonQuery as h,
460
- useRevealPhoneMutation as i,
461
- useSetPersonActiveMutation as j,
462
- useGetSettlementsQuery as k,
463
- useGetEventsQuery as l,
464
- useGetSettingsQuery as m,
493
+ fmtDateTime as e,
494
+ fmtNumber as f,
495
+ useGetGroupQuery as g,
496
+ useArchiveGroupMutation as h,
497
+ fmtSigned as i,
498
+ errorMessage as j,
499
+ useGetPeopleQuery as k,
500
+ useGetPersonQuery as l,
501
+ useRevealPhoneMutation as m,
502
+ useSetPersonActiveMutation as n,
503
+ useGetSettlementsQuery as o,
504
+ useGetEventsQuery as p,
505
+ useSetLimitsMutation as q,
506
+ useGetSettingsQuery as r,
465
507
  useGetDashboardQuery as u
466
508
  };
@@ -7,7 +7,7 @@ require("@strapi/icons/symbols");
7
7
  const reactRouterDom = require("react-router-dom");
8
8
  const styledComponents = require("styled-components");
9
9
  const admin = require("@strapi/strapi/admin");
10
- const index = require("./index-oyRhs5fN.js");
10
+ const index = require("./index-Uv5-E0cg.js");
11
11
  const SPRING = "cubic-bezier(0.32, 0.72, 0, 1)";
12
12
  const rise = styledComponents.keyframes`
13
13
  from { opacity: 0; transform: translateY(14px); filter: blur(6px); }
@@ -380,7 +380,12 @@ styledComponents.styled.span`
380
380
  flex-shrink: 0;
381
381
  `;
382
382
  const BASE = `/${index.PLUGIN_ID}`;
383
- const TAG = Object.freeze({ DASH: "SplitDashboard", GROUP: "SplitGroup", PERSON: "SplitPerson" });
383
+ const TAG = Object.freeze({
384
+ DASH: "SplitDashboard",
385
+ GROUP: "SplitGroup",
386
+ PERSON: "SplitPerson",
387
+ SETTINGS: "SplitSettings"
388
+ });
384
389
  const unwrap = (res) => res && typeof res === "object" && "data" in res ? res.data : res;
385
390
  const qs = (params = {}) => {
386
391
  const clean = Object.fromEntries(
@@ -427,7 +432,20 @@ const api = admin.adminApi.enhanceEndpoints({ addTagTypes: Object.values(TAG) })
427
432
  }),
428
433
  getSettlements: b.query({ query: (p) => `${BASE}/settlements${qs(p)}` }),
429
434
  getEvents: b.query({ query: (p) => `${BASE}/events${qs(p)}` }),
430
- getSettings: b.query({ query: () => `${BASE}/settings`, transformResponse: unwrap })
435
+ getSettings: b.query({
436
+ query: () => `${BASE}/settings`,
437
+ transformResponse: unwrap,
438
+ providesTags: [TAG.SETTINGS]
439
+ }),
440
+ setLimits: b.mutation({
441
+ query: (limits) => ({
442
+ url: `${BASE}/settings/limits`,
443
+ method: "PUT",
444
+ data: { data: limits }
445
+ }),
446
+ transformResponse: unwrap,
447
+ invalidatesTags: [TAG.SETTINGS]
448
+ })
431
449
  }),
432
450
  overrideExisting: true
433
451
  });
@@ -442,8 +460,27 @@ const {
442
460
  useSetPersonActiveMutation,
443
461
  useGetSettlementsQuery,
444
462
  useGetEventsQuery,
445
- useGetSettingsQuery
463
+ useGetSettingsQuery,
464
+ useSetLimitsMutation
446
465
  } = api;
466
+ const fmtDateTime = (value, locale) => {
467
+ if (!value) return "—";
468
+ try {
469
+ return new Intl.DateTimeFormat(locale ?? void 0, {
470
+ dateStyle: "medium",
471
+ timeStyle: "short"
472
+ }).format(new Date(value));
473
+ } catch {
474
+ return String(value);
475
+ }
476
+ };
477
+ const fmtNumber = (value, locale) => new Intl.NumberFormat(locale ?? void 0).format(Number(value ?? 0));
478
+ const fmtSigned = (value, locale) => {
479
+ const n = Number(value ?? 0);
480
+ const digits = fmtNumber(Math.abs(n), locale);
481
+ return n > 0 ? `+${digits}` : n < 0 ? `−${digits}` : digits;
482
+ };
483
+ const errorMessage = (err) => err?.data?.error?.message ?? err?.response?.data?.error?.message ?? err?.error?.message ?? err?.message ?? "Une erreur est survenue.";
447
484
  exports.Bar = Bar;
448
485
  exports.Eyebrow = Eyebrow;
449
486
  exports.Intro = Intro;
@@ -452,6 +489,10 @@ exports.SPRING = SPRING;
452
489
  exports.Section = Section;
453
490
  exports.StatTile = StatTile;
454
491
  exports.StatusBadge = StatusBadge;
492
+ exports.errorMessage = errorMessage;
493
+ exports.fmtDateTime = fmtDateTime;
494
+ exports.fmtNumber = fmtNumber;
495
+ exports.fmtSigned = fmtSigned;
455
496
  exports.useArchiveGroupMutation = useArchiveGroupMutation;
456
497
  exports.useGetDashboardQuery = useGetDashboardQuery;
457
498
  exports.useGetEventsQuery = useGetEventsQuery;
@@ -462,4 +503,5 @@ exports.useGetPersonQuery = useGetPersonQuery;
462
503
  exports.useGetSettingsQuery = useGetSettingsQuery;
463
504
  exports.useGetSettlementsQuery = useGetSettlementsQuery;
464
505
  exports.useRevealPhoneMutation = useRevealPhoneMutation;
506
+ exports.useSetLimitsMutation = useSetLimitsMutation;
465
507
  exports.useSetPersonActiveMutation = useSetPersonActiveMutation;
@@ -39,7 +39,8 @@ const PERMISSIONS = Object.freeze({
39
39
  peopleWrite: one("people.write"),
40
40
  settlementsRead: one("settlements.read"),
41
41
  auditRead: one("audit.read"),
42
- settingsRead: one("settings.read")
42
+ settingsRead: one("settings.read"),
43
+ settingsWrite: one("settings.write")
43
44
  });
44
45
  const prefixPluginTranslations = (dictionary, pluginId) => Object.keys(dictionary).reduce((acc, key) => {
45
46
  acc[`${pluginId}.${key}`] = dictionary[key];
@@ -53,7 +54,7 @@ const index = {
53
54
  intlLabel: { id: `${PLUGIN_ID}.menu.label`, defaultMessage: "Split" },
54
55
  permissions: PERMISSIONS.access,
55
56
  Component: async () => {
56
- const { App } = await Promise.resolve().then(() => require("./App-CLfoPnvq.js"));
57
+ const { App } = await Promise.resolve().then(() => require("./App-CYAjChoJ.js"));
57
58
  return App;
58
59
  }
59
60
  });
@@ -66,7 +67,7 @@ const index = {
66
67
  intlLabel: { id: `${PLUGIN_ID}.settings.link`, defaultMessage: "Configuration" },
67
68
  permissions: PERMISSIONS.settingsRead,
68
69
  Component: async () => {
69
- const { SettingsPage } = await Promise.resolve().then(() => require("./SettingsPage-B746YfAA.js"));
70
+ const { SettingsPage } = await Promise.resolve().then(() => require("./SettingsPage-BqEpGpCs.js"));
70
71
  return SettingsPage;
71
72
  }
72
73
  }
@@ -38,7 +38,8 @@ const PERMISSIONS = Object.freeze({
38
38
  peopleWrite: one("people.write"),
39
39
  settlementsRead: one("settlements.read"),
40
40
  auditRead: one("audit.read"),
41
- settingsRead: one("settings.read")
41
+ settingsRead: one("settings.read"),
42
+ settingsWrite: one("settings.write")
42
43
  });
43
44
  const prefixPluginTranslations = (dictionary, pluginId) => Object.keys(dictionary).reduce((acc, key) => {
44
45
  acc[`${pluginId}.${key}`] = dictionary[key];
@@ -52,7 +53,7 @@ const index = {
52
53
  intlLabel: { id: `${PLUGIN_ID}.menu.label`, defaultMessage: "Split" },
53
54
  permissions: PERMISSIONS.access,
54
55
  Component: async () => {
55
- const { App } = await import("./App-8QwzQSyg.mjs");
56
+ const { App } = await import("./App-CyHrReR9.mjs");
56
57
  return App;
57
58
  }
58
59
  });
@@ -65,7 +66,7 @@ const index = {
65
66
  intlLabel: { id: `${PLUGIN_ID}.settings.link`, defaultMessage: "Configuration" },
66
67
  permissions: PERMISSIONS.settingsRead,
67
68
  Component: async () => {
68
- const { SettingsPage } = await import("./SettingsPage-CH92IYGk.mjs");
69
+ const { SettingsPage } = await import("./SettingsPage-By2SGFAk.mjs");
69
70
  return SettingsPage;
70
71
  }
71
72
  }
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
- const index = require("../_chunks/index-oyRhs5fN.js");
2
+ const index = require("../_chunks/index-Uv5-E0cg.js");
3
3
  module.exports = index.index;
@@ -1,4 +1,4 @@
1
- import { i } from "../_chunks/index-PFbwTznf.mjs";
1
+ import { i } from "../_chunks/index-oF7vL92A.mjs";
2
2
  export {
3
3
  i as default
4
4
  };
@@ -25,7 +25,8 @@ const RBAC = Object.freeze({
25
25
  PEOPLE_WRITE: "people.write",
26
26
  SETTLEMENTS_READ: "settlements.read",
27
27
  AUDIT_READ: "audit.read",
28
- SETTINGS_READ: "settings.read"
28
+ SETTINGS_READ: "settings.read",
29
+ SETTINGS_WRITE: "settings.write"
29
30
  });
30
31
  const SPLIT_MODE = Object.freeze({ EQUAL: "equal", WEIGHTED: "weighted", FREE: "free" });
31
32
  const ROLE = Object.freeze({ OWNER: "owner", MEMBER: "member" });
@@ -84,11 +85,17 @@ const ORDER_LIST_SIZE = 20;
84
85
  const ORDER_NOTE_MAX = 80;
85
86
  const ORDER_RECENT_MS = 24 * 60 * 60 * 1e3;
86
87
  const DEFAULT_LIMITS = Object.freeze({
87
- maxGroupsPerPerson: 50,
88
- maxMembersPerGroup: 50,
88
+ maxGroupsPerPerson: 150,
89
+ maxMembersPerGroup: 150,
89
90
  /** Largest single expense or settlement, in the currency's smallest unit. */
90
- maxAmount: 5e7
91
+ maxAmount: 15e7
91
92
  });
93
+ const LIMIT_CEILINGS = Object.freeze({
94
+ maxGroupsPerPerson: 1e3,
95
+ maxMembersPerGroup: 500,
96
+ maxAmount: 2e9
97
+ });
98
+ const LIMITS_STORE_KEY = "limits";
92
99
  const DEFAULT_INVITE_PREFIX = "SPL";
93
100
  const DEFAULT_COUNTRY_CODE = "";
94
101
  const CODE_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
@@ -145,6 +152,12 @@ const ACTIONS = [
145
152
  category: PLUGIN_DISPLAY_NAME,
146
153
  uid: RBAC.SETTINGS_READ,
147
154
  displayName: "Read settings"
155
+ },
156
+ {
157
+ section: "settings",
158
+ category: PLUGIN_DISPLAY_NAME,
159
+ uid: RBAC.SETTINGS_WRITE,
160
+ displayName: "Change the limits"
148
161
  }
149
162
  ].map((a) => ({ ...a, pluginName: PLUGIN_ID }));
150
163
  const UNIQUE_COLUMNS = [
@@ -1406,8 +1419,16 @@ const admin$1 = ({ strapi }) => {
1406
1419
  countryCode: settings2.countryCode(),
1407
1420
  people: settings2.people(),
1408
1421
  methods: settings2.methods(),
1409
- limits: settings2.limits()
1422
+ limits: await settings2.limits(),
1423
+ limitCeilings: LIMIT_CEILINGS
1410
1424
  });
1425
+ }),
1426
+ setLimits: handle(strapi, async (ctx) => {
1427
+ const limits = await svc("settings").setLimits(body(ctx));
1428
+ strapi.log.info(
1429
+ `${LOG_PREFIX} limits set to ${JSON.stringify(limits)} by admin ${ctx.state.user?.id}`
1430
+ );
1431
+ ok(ctx, limits);
1411
1432
  })
1412
1433
  };
1413
1434
  };
@@ -1524,14 +1545,23 @@ const admin = [
1524
1545
  route("PUT", "/people/:id/active", "setPersonActive", RBAC.PEOPLE_WRITE),
1525
1546
  route("GET", "/settlements", "settlements", RBAC.SETTLEMENTS_READ),
1526
1547
  route("GET", "/events", "events", RBAC.AUDIT_READ),
1527
- route("GET", "/settings", "settings", RBAC.SETTINGS_READ)
1548
+ route("GET", "/settings", "settings", RBAC.SETTINGS_READ),
1549
+ route("PUT", "/settings/limits", "setLimits", RBAC.SETTINGS_WRITE)
1528
1550
  ];
1529
1551
  const routes = {
1530
1552
  "content-api": { type: "content-api", routes: contentApi },
1531
1553
  admin: { type: "admin", routes: admin }
1532
1554
  };
1533
1555
  const DEFAULT_PEOPLE = Object.freeze({ idHeader: "x-person-id", nameHeader: "x-person-name" });
1556
+ const LIMIT_KEYS = Object.keys(DEFAULT_LIMITS);
1557
+ const withinCeiling = (key, value) => Number.isInteger(value) && value > 0 && value <= LIMIT_CEILINGS[key];
1558
+ const usable = (limits) => Object.fromEntries(
1559
+ LIMIT_KEYS.filter((key) => withinCeiling(key, limits?.[key])).map((key) => [key, limits[key]])
1560
+ );
1534
1561
  const settings = ({ strapi }) => ({
1562
+ store() {
1563
+ return strapi.store({ type: "plugin", name: PLUGIN_ID });
1564
+ },
1535
1565
  /** @returns {Object} the full plugin config */
1536
1566
  all() {
1537
1567
  return strapi.config.get(`plugin::${PLUGIN_ID}`) ?? {};
@@ -1558,8 +1588,34 @@ const settings = ({ strapi }) => ({
1558
1588
  Object.entries(methods).map(([name, m]) => [name, { instant: Boolean(m?.instant) }])
1559
1589
  );
1560
1590
  },
1561
- limits() {
1591
+ /** The limits from the configuration file, before anything set in the back office. */
1592
+ configuredLimits() {
1562
1593
  return { ...DEFAULT_LIMITS, ...this.all().limits ?? {} };
1594
+ },
1595
+ /**
1596
+ * The limits in force: what an administrator set, else the configuration file, else the defaults.
1597
+ * @returns {Promise<{ maxGroupsPerPerson: number, maxMembersPerGroup: number, maxAmount: number }>}
1598
+ */
1599
+ async limits() {
1600
+ const saved = await this.store().get({ key: LIMITS_STORE_KEY });
1601
+ return { ...this.configuredLimits(), ...usable(saved) };
1602
+ },
1603
+ /**
1604
+ * Sets the limits from the back office. Every limit is given, each a whole number from 1 to its
1605
+ * ceiling. Lowering one never touches what already exists: it only refuses what comes next.
1606
+ * @param {Object} input
1607
+ * @returns {Promise<Object>} the limits now in force
1608
+ */
1609
+ async setLimits(input) {
1610
+ const refused = LIMIT_KEYS.filter((key) => !withinCeiling(key, input?.[key]));
1611
+ if (refused.length > 0)
1612
+ throw badRequest(
1613
+ ERROR_CODES.VALIDATION,
1614
+ "Chaque limite est un entier entre 1 et son plafond.",
1615
+ { fields: refused, ceilings: LIMIT_CEILINGS }
1616
+ );
1617
+ await this.store().set({ key: LIMITS_STORE_KEY, value: usable(input) });
1618
+ return this.limits();
1563
1619
  }
1564
1620
  });
1565
1621
  const audit = ({ strapi }) => ({
@@ -2007,7 +2063,7 @@ const group = ({ strapi }) => {
2007
2063
  async create(person2, input) {
2008
2064
  const name = cleanName(input.name);
2009
2065
  if (!name) throw badRequest(ERROR_CODES.VALIDATION, "Donne un nom au groupe.");
2010
- const limits = svc("settings").limits();
2066
+ const limits = await svc("settings").limits();
2011
2067
  const held = await members().count({ where: { person: person2.id, ...HELD } });
2012
2068
  if (held >= limits.maxGroupsPerPerson)
2013
2069
  throw unprocessable(
@@ -2084,7 +2140,7 @@ const group = ({ strapi }) => {
2084
2140
  });
2085
2141
  if (existing && !existing.joinedAt) await svc("member").take({ ...existing, group: group2 }, person2);
2086
2142
  if (existing) return group2;
2087
- const limits = svc("settings").limits();
2143
+ const limits = await svc("settings").limits();
2088
2144
  const count = await members().count({ where: { group: group2.id, leftAt: { $null: true } } });
2089
2145
  if (count >= limits.maxMembersPerGroup)
2090
2146
  throw unprocessable(ERROR_CODES.MEMBER_LIMIT, "Ce groupe est complet.");
@@ -2192,7 +2248,7 @@ const member = ({ strapi }) => {
2192
2248
  */
2193
2249
  async add({ group: group2, me }, raw) {
2194
2250
  const input = this.parse(raw);
2195
- const limits = svc("settings").limits();
2251
+ const limits = await svc("settings").limits();
2196
2252
  const seats = await members().findMany({
2197
2253
  where: { group: group2.id, leftAt: { $null: true } },
2198
2254
  populate: { person: true }
@@ -2407,10 +2463,10 @@ const expense = ({ strapi }) => {
2407
2463
  * @returns {{ label: string, category: string|null, amount: number, mode: string, spentAt: Date,
2408
2464
  * paidBy: number, shares: Array<{ member: number, amount: number, weight: number }> }}
2409
2465
  */
2410
- parse(input, active) {
2466
+ async parse(input, active) {
2411
2467
  const label2 = String(input?.label ?? "").trim().slice(0, LABEL_MAX);
2412
2468
  if (!label2) throw badRequest(ERROR_CODES.VALIDATION, "Dis ce que tu as payé.");
2413
- const { maxAmount } = svc("settings").limits();
2469
+ const { maxAmount } = await svc("settings").limits();
2414
2470
  const amount = input?.amount;
2415
2471
  if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
2416
2472
  throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
@@ -2466,7 +2522,7 @@ const expense = ({ strapi }) => {
2466
2522
  const earlier = await this.replayed(group2, clientRef);
2467
2523
  if (earlier) return { expense: earlier, replayed: true };
2468
2524
  const { active } = await svc("ledger").of(group2);
2469
- const { shares: list, ...data } = this.parse(input, active);
2525
+ const { shares: list, ...data } = await this.parse(input, active);
2470
2526
  try {
2471
2527
  const created = await strapi.db.transaction(async () => {
2472
2528
  await svc("group").lock(group2);
@@ -2509,7 +2565,7 @@ const expense = ({ strapi }) => {
2509
2565
  const { group: group2, me } = seat;
2510
2566
  const expense2 = await this.editable(seat, documentId);
2511
2567
  const { active } = await svc("ledger").of(group2);
2512
- const { shares: list, ...data } = this.parse(input, active);
2568
+ const { shares: list, ...data } = await this.parse(input, active);
2513
2569
  await strapi.db.transaction(async () => {
2514
2570
  await svc("group").lock(group2);
2515
2571
  await expenses().update({ where: { id: expense2.id }, data });
@@ -2572,7 +2628,7 @@ const settlement = ({ strapi }) => {
2572
2628
  * (`to`) when the caller pays, the one who paid (`from`) when the caller received.
2573
2629
  */
2574
2630
  async parse({ group: group2, me }, input) {
2575
- const { maxAmount } = svc("settings").limits();
2631
+ const { maxAmount } = await svc("settings").limits();
2576
2632
  const amount = input?.amount;
2577
2633
  if (!Number.isInteger(amount) || amount <= 0 || amount > maxAmount)
2578
2634
  throw badRequest(ERROR_CODES.VALIDATION, "Montant invalide.", { maxAmount });
@@ -2809,10 +2865,10 @@ const order = ({ strapi }) => {
2809
2865
  return date;
2810
2866
  },
2811
2867
  /** What the organiser sent, checked. */
2812
- parse(input) {
2868
+ async parse(input) {
2813
2869
  const title = label(input?.title);
2814
2870
  if (!title) throw invalid("Donne un nom à la commande.");
2815
- const { maxAmount } = svc("settings").limits();
2871
+ const { maxAmount } = await svc("settings").limits();
2816
2872
  const list = Array.isArray(input?.items) ? input.items : [];
2817
2873
  if (list.length === 0 || list.length > ORDER_MAX_ITEMS)
2818
2874
  throw invalid(`Entre 1 et ${ORDER_MAX_ITEMS} articles.`, { max: ORDER_MAX_ITEMS });
@@ -2827,7 +2883,7 @@ const order = ({ strapi }) => {
2827
2883
  * @param {{ title: string, closesAt?: string, items: Array<{ label: string, price: number }> }} input
2828
2884
  */
2829
2885
  async create({ group: group2, me }, input) {
2830
- const data = this.parse(input);
2886
+ const data = await this.parse(input);
2831
2887
  const order2 = await strapi.db.transaction(async () => {
2832
2888
  const created = await orders().create({
2833
2889
  data: {
@@ -2956,7 +3012,7 @@ const order = ({ strapi }) => {
2956
3012
  this.assertOrganizer(order2, me);
2957
3013
  if (order2.status === ORDER_STATUS.CLOSED) return order2;
2958
3014
  this.assertOpen(order2);
2959
- const { maxAmount } = svc("settings").limits();
3015
+ const { maxAmount } = await svc("settings").limits();
2960
3016
  const deliveryFee = input?.deliveryFee ?? 0;
2961
3017
  if (!Number.isInteger(deliveryFee) || deliveryFee < 0 || deliveryFee > maxAmount)
2962
3018
  throw invalid("Frais de livraison invalides.", { maxAmount });