@10x-media/form-builder 0.1.0-beta.10 → 0.1.0-beta.12
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.
- package/CHANGELOG.md +25 -0
- package/dist/actions/assertNoBlockCollision.js +18 -0
- package/dist/actions/assertNoBlockCollision.js.map +1 -0
- package/dist/actions/builtin/confirmation.js +2 -1
- package/dist/actions/builtin/confirmation.js.map +1 -1
- package/dist/actions/builtin/emailAction.d.ts +3 -1
- package/dist/actions/builtin/emailAction.js +43 -12
- package/dist/actions/builtin/emailAction.js.map +1 -1
- package/dist/actions/builtin/emailTeam.js +11 -5
- package/dist/actions/builtin/emailTeam.js.map +1 -1
- package/dist/actions/defineAction.d.ts +3 -1
- package/dist/actions/defineAction.js.map +1 -1
- package/dist/actions/dispatch.js +1 -1
- package/dist/actions/dispatch.js.map +1 -1
- package/dist/actions/emailRecipients.js +34 -7
- package/dist/actions/emailRecipients.js.map +1 -1
- package/dist/actions/recipientSources.d.ts +34 -0
- package/dist/actions/recipientSources.js +11 -0
- package/dist/actions/recipientSources.js.map +1 -0
- package/dist/actions/task.js +20 -0
- package/dist/actions/task.js.map +1 -1
- package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
- package/dist/aggregation/resolveResultsRequest.js +32 -3
- package/dist/aggregation/resolveResultsRequest.js.map +1 -1
- package/dist/calc/computeCalcFields.d.ts +5 -3
- package/dist/calc/computeCalcFields.js +4 -3
- package/dist/calc/computeCalcFields.js.map +1 -1
- package/dist/calc/evaluate.d.ts +26 -3
- package/dist/calc/evaluate.js +33 -11
- package/dist/calc/evaluate.js.map +1 -1
- package/dist/calc/formatCalc.d.ts +11 -0
- package/dist/calc/formatCalc.js +35 -0
- package/dist/calc/formatCalc.js.map +1 -0
- package/dist/calc/formatCalcValue.d.ts +17 -0
- package/dist/calc/formatCalcValue.js +17 -0
- package/dist/calc/formatCalcValue.js.map +1 -0
- package/dist/calc/normalizeCalc.d.ts +17 -3
- package/dist/calc/normalizeCalc.js +39 -17
- package/dist/calc/normalizeCalc.js.map +1 -1
- package/dist/calc/registry.d.ts +43 -0
- package/dist/calc/registry.js +27 -0
- package/dist/calc/registry.js.map +1 -0
- package/dist/calc/resolveCalcContext.d.ts +36 -0
- package/dist/calc/resolveCalcContext.js +87 -0
- package/dist/calc/resolveCalcContext.js.map +1 -0
- package/dist/calc/types.d.ts +18 -3
- package/dist/calc/types.js +2 -1
- package/dist/calc/types.js.map +1 -1
- package/dist/client/CalcExpressionBuilder.d.ts +20 -0
- package/dist/client/CalcExpressionBuilder.js +890 -0
- package/dist/client/CalcExpressionBuilder.js.map +1 -0
- package/dist/client/RecipientsSelect.d.ts +5 -1
- package/dist/client/RecipientsSelect.js +22 -3
- package/dist/client/RecipientsSelect.js.map +1 -1
- package/dist/client/admin.css +282 -0
- package/dist/collections/formSubmissions.js +34 -16
- package/dist/collections/formSubmissions.js.map +1 -1
- package/dist/collections/forms.js +59 -27
- package/dist/collections/forms.js.map +1 -1
- package/dist/collections/formsEndpoints.js +4 -2
- package/dist/collections/formsEndpoints.js.map +1 -1
- package/dist/collections/settingsFields.d.ts +31 -0
- package/dist/collections/settingsFields.js +45 -0
- package/dist/collections/settingsFields.js.map +1 -0
- package/dist/context/formContext.d.ts +30 -0
- package/dist/context/formContext.js +54 -0
- package/dist/context/formContext.js.map +1 -0
- package/dist/exports/client.d.ts +2 -1
- package/dist/exports/client.js +2 -1
- package/dist/exports/react.d.ts +7 -3
- package/dist/exports/react.js +6 -2
- package/dist/exports/rsc.d.ts +2 -1
- package/dist/exports/rsc.js +3 -2
- package/dist/exports/types.d.ts +1 -1
- package/dist/fields/buildFieldBlocks.js +2 -1
- package/dist/fields/buildFieldBlocks.js.map +1 -1
- package/dist/fields/builtin/calculation.d.ts +17 -0
- package/dist/fields/builtin/calculation.js +170 -115
- package/dist/fields/builtin/calculation.js.map +1 -1
- package/dist/fields/builtin/checkbox.js +15 -0
- package/dist/fields/builtin/checkbox.js.map +1 -1
- package/dist/fields/builtin/email.js +7 -0
- package/dist/fields/builtin/email.js.map +1 -1
- package/dist/fields/builtin/index.d.ts +6 -2
- package/dist/fields/builtin/index.js +9 -4
- package/dist/fields/builtin/index.js.map +1 -1
- package/dist/fields/builtin/select.js +20 -1
- package/dist/fields/builtin/select.js.map +1 -1
- package/dist/fields/builtin/text.js +7 -0
- package/dist/fields/builtin/text.js.map +1 -1
- package/dist/fields/instanceOptions.js +1 -1
- package/dist/fields/instanceOptions.js.map +1 -1
- package/dist/fields/sharedConfig.js +15 -11
- package/dist/fields/sharedConfig.js.map +1 -1
- package/dist/fields/types.d.ts +8 -2
- package/dist/form/toFormDocument.d.ts +7 -0
- package/dist/form/toFormDocument.js +2 -1
- package/dist/form/toFormDocument.js.map +1 -1
- package/dist/form/types.d.ts +7 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.js +40 -9
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +42 -0
- package/dist/plugin/registerCollections.js +29 -19
- package/dist/plugin/registerCollections.js.map +1 -1
- package/dist/poll/closeJob.d.ts +4 -3
- package/dist/poll/closeJob.js +6 -4
- package/dist/poll/closeJob.js.map +1 -1
- package/dist/poll/pollTypeRegistry.js +1 -1
- package/dist/poll/resolvePollCloseRequest.js +2 -1
- package/dist/poll/resolvePollCloseRequest.js.map +1 -1
- package/dist/poll/resolvePollOutcome.d.ts +6 -0
- package/dist/poll/resolvePollOutcome.js +17 -3
- package/dist/poll/resolvePollOutcome.js.map +1 -1
- package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
- package/dist/poll/votes/aggregateFromVotes.js +53 -0
- package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
- package/dist/poll/votes/bumpPollVote.js +72 -0
- package/dist/poll/votes/bumpPollVote.js.map +1 -0
- package/dist/poll/votes/recountPollVotes.d.ts +20 -0
- package/dist/poll/votes/recountPollVotes.js +63 -0
- package/dist/poll/votes/recountPollVotes.js.map +1 -0
- package/dist/poll/votes/voteTallyHook.js +58 -0
- package/dist/poll/votes/voteTallyHook.js.map +1 -0
- package/dist/poll/votes/votesCollection.d.ts +19 -0
- package/dist/poll/votes/votesCollection.js +89 -0
- package/dist/poll/votes/votesCollection.js.map +1 -0
- package/dist/react/Form.d.ts +15 -1
- package/dist/react/Form.js +24 -3
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +8 -1
- package/dist/react/FormContext.js.map +1 -1
- package/dist/react/primitives/Checkbox.d.ts +4 -2
- package/dist/react/primitives/Checkbox.js +3 -2
- package/dist/react/primitives/Checkbox.js.map +1 -1
- package/dist/react/primitives/ChoiceGroup.d.ts +40 -0
- package/dist/react/primitives/ChoiceGroup.js +33 -0
- package/dist/react/primitives/ChoiceGroup.js.map +1 -0
- package/dist/react/primitives/FieldShell.d.ts +11 -1
- package/dist/react/primitives/FieldShell.js +43 -33
- package/dist/react/primitives/FieldShell.js.map +1 -1
- package/dist/react/primitives/Input.d.ts +3 -1
- package/dist/react/primitives/Input.js +2 -1
- package/dist/react/primitives/Input.js.map +1 -1
- package/dist/react/renderers/calculation.js +6 -1
- package/dist/react/renderers/calculation.js.map +1 -1
- package/dist/react/renderers/checkbox.js +2 -1
- package/dist/react/renderers/checkbox.js.map +1 -1
- package/dist/react/renderers/email.js +3 -1
- package/dist/react/renderers/email.js.map +1 -1
- package/dist/react/renderers/select.js +20 -2
- package/dist/react/renderers/select.js.map +1 -1
- package/dist/react/renderers/text.js +3 -1
- package/dist/react/renderers/text.js.map +1 -1
- package/dist/react/useCalcValues.d.ts +10 -0
- package/dist/react/useCalcValues.js +13 -0
- package/dist/react/useCalcValues.js.map +1 -0
- package/dist/recall/resolver.js +1 -1
- package/dist/recall/resolver.js.map +1 -1
- package/dist/spam/constants.js +7 -1
- package/dist/spam/constants.js.map +1 -1
- package/dist/submissions/formIdOf.js +13 -0
- package/dist/submissions/formIdOf.js.map +1 -0
- package/dist/submissions/runSubmission.js +3 -3
- package/dist/submissions/runSubmission.js.map +1 -1
- package/dist/submissions/validateSubmission.js +26 -2
- package/dist/submissions/validateSubmission.js.map +1 -1
- package/dist/submissions/verifyContext.js +35 -0
- package/dist/submissions/verifyContext.js.map +1 -0
- package/dist/translations/de.js +62 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +62 -3
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/keys.d.ts +60 -1
- package/dist/translations/keys.js +60 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/validation/builtin/index.js +2 -0
- package/dist/validation/builtin/index.js.map +1 -1
- package/dist/validation/builtin/integer.js +15 -0
- package/dist/validation/builtin/integer.js.map +1 -0
- package/package.json +11 -5
- package/styles/form-builder.css +84 -0
package/dist/options.d.ts
CHANGED
|
@@ -10,8 +10,11 @@ import { FormResultsAccess } from "./aggregation/resolveResultsRequest.js";
|
|
|
10
10
|
import { ButtonsOption } from "./collections/buttonFields.js";
|
|
11
11
|
import { ConsentSnapshotMode } from "./consent/captureConsent.js";
|
|
12
12
|
import { DepartmentEmailsResolver } from "./email/departments.js";
|
|
13
|
+
import { RecipientSourceRegistry } from "./actions/recipientSources.js";
|
|
13
14
|
import { RecipientsConfig } from "./actions/emailRecipients.js";
|
|
15
|
+
import { CalcFunction, CalcSource } from "./calc/registry.js";
|
|
14
16
|
import { ResponseOption } from "./collections/redirectFields.js";
|
|
17
|
+
import { SettingsOption } from "./collections/settingsFields.js";
|
|
15
18
|
import { CollectionOverrides } from "./plugin/collectionOverrides.js";
|
|
16
19
|
import { SpamOption } from "./spam/types.js";
|
|
17
20
|
import { UploadsOption } from "./plugin/uploadsCollection.js";
|
|
@@ -46,6 +49,23 @@ type FormBuilderPluginOptions = {
|
|
|
46
49
|
fields?: FieldTypesConfig; /** Add, override, or remove validation rule types. `false` removes a built-in, `true` keeps it, an object adds or replaces one. */
|
|
47
50
|
rules?: ValidationRulesConfig; /** Add, override, or remove post-submit action types. `false` removes a built-in, `true` keeps it, an object adds or replaces one. */
|
|
48
51
|
actions?: ActionsConfig;
|
|
52
|
+
/**
|
|
53
|
+
* Calculation extensions. `sources` registers named value resolvers the calculation field can
|
|
54
|
+
* reference: `resolve` supplies one number per render/submission (a tax rate, a member
|
|
55
|
+
* discount), `resolveWeights` supplies per-option numbers for a chosen field (a product's
|
|
56
|
+
* price per selectable product). Values resolve server-side, ride the form document for the
|
|
57
|
+
* client's live preview, and re-resolve at submit, so the client never supplies them.
|
|
58
|
+
* `functions` registers extra calculation functions; client-side live preview additionally
|
|
59
|
+
* needs the same map passed to the Form component.
|
|
60
|
+
*
|
|
61
|
+
* Resolvers receive an unauthenticated visitor `req` on public reads and submits: never feed
|
|
62
|
+
* data derived from it into access-escalated queries, and gate per-user-sensitive numbers on
|
|
63
|
+
* `req.user`, because resolved values are embedded on every readable form document.
|
|
64
|
+
*/
|
|
65
|
+
calc?: {
|
|
66
|
+
sources?: Record<string, CalcSource>;
|
|
67
|
+
functions?: Record<string, CalcFunction>;
|
|
68
|
+
};
|
|
49
69
|
/**
|
|
50
70
|
* Customize how the plugin's rich text is authored and rendered. `editor` is the default
|
|
51
71
|
* Lexical/richText editor for every plugin richText field (message content, consent
|
|
@@ -85,6 +105,12 @@ type FormBuilderPluginOptions = {
|
|
|
85
105
|
fromAddresses?: FromAddressesResolver;
|
|
86
106
|
departments?: DepartmentEmailsResolver; /** Narrows the recipient fields' behavior (free-typed emails, field tokens). See {@link RecipientsConfig}. */
|
|
87
107
|
recipients?: RecipientsConfig;
|
|
108
|
+
/**
|
|
109
|
+
* Server-resolved recipients, offered in every recipient field as their own option group and
|
|
110
|
+
* resolved to addresses at send time. Each source's `value` is a namespaced string (so it cannot
|
|
111
|
+
* collide with an address); its `resolve` receives the verified form context. See {@link RecipientSource}.
|
|
112
|
+
*/
|
|
113
|
+
recipientSources?: RecipientSourceRegistry;
|
|
88
114
|
};
|
|
89
115
|
/**
|
|
90
116
|
* Where the consent statements a form can reference come from. Absent (the default): no sources,
|
|
@@ -130,6 +156,12 @@ type FormBuilderPluginOptions = {
|
|
|
130
156
|
* host-added sibling field is still stored but is read off the raw document, not `doc.buttons`.
|
|
131
157
|
*/
|
|
132
158
|
buttons?: ButtonsOption;
|
|
159
|
+
/**
|
|
160
|
+
* Form-level flag fields (`multistep`, `pollEnabled`, `persistSubmissions`), sidebar
|
|
161
|
+
* checkboxes by default. `fields` composes them from the defaults so a host can
|
|
162
|
+
* relocate, wrap, extend, or drop them.
|
|
163
|
+
*/
|
|
164
|
+
settings?: SettingsOption;
|
|
133
165
|
/**
|
|
134
166
|
* The success-response group. `redirect.fields` composes the fields inside the `response.redirect`
|
|
135
167
|
* group, mirroring `buttons.fields`: it receives the default fields (the `url` text field, plus the
|
|
@@ -200,6 +232,16 @@ type FormBuilderPluginOptions = {
|
|
|
200
232
|
sources?: PollOptionSourcesConfig;
|
|
201
233
|
types?: PollTypesConfig;
|
|
202
234
|
outcomeFields?: OutcomeFieldsOverride;
|
|
235
|
+
/**
|
|
236
|
+
* Poll vote tally store (default on). Votes are counted into an append-only hidden
|
|
237
|
+
* collection of aggregate rows at submit time, so results reads are O(options), never
|
|
238
|
+
* truncate, and survive `persistSubmissions: false`. `false` restores scan-based results
|
|
239
|
+
* (and then a persist-off poll is rejected at save). `overrides` opens the tally
|
|
240
|
+
* collection (slug stays `form-poll-votes`).
|
|
241
|
+
*/
|
|
242
|
+
votes?: false | {
|
|
243
|
+
overrides?: CollectionOverrides;
|
|
244
|
+
};
|
|
203
245
|
};
|
|
204
246
|
/**
|
|
205
247
|
* When `true`, the raw `values`, `descriptors`, and `consent` JSON fields are visible in the
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
import { buildPollVotesCollection } from "../poll/votes/votesCollection.js";
|
|
1
2
|
import { registerPollCloseTask } from "../poll/closeJob.js";
|
|
2
3
|
import { buildFormsCollection } from "../collections/forms.js";
|
|
3
4
|
import { buildSubmissionsCollection } from "../collections/formSubmissions.js";
|
|
4
5
|
import { registerActionsTask } from "../actions/task.js";
|
|
5
6
|
import { attachUploadsCollection } from "./uploadsCollection.js";
|
|
6
7
|
//#region src/plugin/registerCollections.ts
|
|
7
|
-
const registerCollections = ({ config, registry, ruleRegistry, consentSources, consentSnapshot, consentResolveOnRead, actionRegistry, richText, hasJobsPlugin, events, uploads, spam, showSubmissionRawFields, localizeContent, resultsAccess, votedCookie, pollSourceRegistry, pollTypeRegistry, outcomeFields, buttons, response, fromAddresses, departments, redirectRelationships, overrides }) => {
|
|
8
|
+
const registerCollections = ({ config, registry, ruleRegistry, calcAllowed, calcSources, calcFunctions, consentSources, consentSnapshot, consentResolveOnRead, actionRegistry, richText, hasJobsPlugin, events, uploads, spam, showSubmissionRawFields, localizeContent, resultsAccess, votedCookie, pollSourceRegistry, pollTypeRegistry, outcomeFields, pollVotes, buttons, settings, response, fromAddresses, departments, redirectRelationships, overrides }) => {
|
|
9
|
+
const pollVotesEnabled = pollVotes !== false;
|
|
8
10
|
registerActionsTask(config, actionRegistry, richText);
|
|
9
|
-
registerPollCloseTask(config);
|
|
11
|
+
registerPollCloseTask(config, pollVotesEnabled);
|
|
10
12
|
const hasRunner = Boolean(config.jobs?.autoRun) || hasJobsPlugin;
|
|
11
13
|
const uploadSlug = uploads === false ? void 0 : uploads.collection;
|
|
12
14
|
if (uploads !== false) attachUploadsCollection({
|
|
@@ -16,25 +18,11 @@ const registerCollections = ({ config, registry, ruleRegistry, consentSources, c
|
|
|
16
18
|
});
|
|
17
19
|
config.collections = [
|
|
18
20
|
...config.collections ?? [],
|
|
19
|
-
buildSubmissionsCollection({
|
|
20
|
-
registry,
|
|
21
|
-
ruleRegistry,
|
|
22
|
-
consentSources,
|
|
23
|
-
consentSnapshot,
|
|
24
|
-
actionRegistry,
|
|
25
|
-
richText,
|
|
26
|
-
events,
|
|
27
|
-
hasRunner,
|
|
28
|
-
uploadSlug,
|
|
29
|
-
spam,
|
|
30
|
-
votedCookie,
|
|
31
|
-
pollSourceRegistry,
|
|
32
|
-
showRawFields: showSubmissionRawFields,
|
|
33
|
-
overrides: overrides?.formSubmissions
|
|
34
|
-
}),
|
|
35
21
|
buildFormsCollection({
|
|
36
22
|
registry,
|
|
37
23
|
ruleRegistry,
|
|
24
|
+
calcAllowed,
|
|
25
|
+
calcSources,
|
|
38
26
|
consentSources,
|
|
39
27
|
consentResolveOnRead,
|
|
40
28
|
actionRegistry,
|
|
@@ -42,16 +30,38 @@ const registerCollections = ({ config, registry, ruleRegistry, consentSources, c
|
|
|
42
30
|
richText,
|
|
43
31
|
uploadsCollectionSlug: uploadSlug,
|
|
44
32
|
resultsAccess,
|
|
33
|
+
pollVotesEnabled,
|
|
45
34
|
pollSourceRegistry,
|
|
46
35
|
pollTypeRegistry,
|
|
47
36
|
outcomeFields,
|
|
48
37
|
buttons,
|
|
38
|
+
settings,
|
|
49
39
|
response,
|
|
50
40
|
fromAddresses,
|
|
51
41
|
departments,
|
|
52
42
|
redirectRelationships,
|
|
53
43
|
overrides: overrides?.forms
|
|
54
|
-
})
|
|
44
|
+
}),
|
|
45
|
+
buildSubmissionsCollection({
|
|
46
|
+
registry,
|
|
47
|
+
ruleRegistry,
|
|
48
|
+
calcSources,
|
|
49
|
+
calcFunctions,
|
|
50
|
+
consentSources,
|
|
51
|
+
consentSnapshot,
|
|
52
|
+
actionRegistry,
|
|
53
|
+
richText,
|
|
54
|
+
events,
|
|
55
|
+
hasRunner,
|
|
56
|
+
uploadSlug,
|
|
57
|
+
spam,
|
|
58
|
+
votedCookie,
|
|
59
|
+
pollSourceRegistry,
|
|
60
|
+
pollVotes,
|
|
61
|
+
showRawFields: showSubmissionRawFields,
|
|
62
|
+
overrides: overrides?.formSubmissions
|
|
63
|
+
}),
|
|
64
|
+
...pollVotes === false ? [] : [buildPollVotesCollection({ overrides: pollVotes.overrides })]
|
|
55
65
|
];
|
|
56
66
|
};
|
|
57
67
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerCollections.js","names":[],"sources":["../../src/plugin/registerCollections.ts"],"sourcesContent":["import type { CollectionSlug, Config } from 'payload'\nimport type { RichTextBodyOption } from '../actions/body/serializeBody'\nimport type { FromAddressesResolver } from '../actions/fromAddresses'\nimport type { ActionRegistry } from '../actions/registry'\nimport { registerActionsTask } from '../actions/task'\nimport type { FormResultsAccess } from '../aggregation/resolveResultsRequest'\nimport type { ButtonsOption } from '../collections/buttonFields'\nimport { buildSubmissionsCollection } from '../collections/formSubmissions'\nimport { buildFormsCollection } from '../collections/forms'\nimport type { ResponseOption } from '../collections/redirectFields'\nimport type { ConsentSnapshotMode } from '../consent/captureConsent'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport type { DepartmentEmailsResolver } from '../email/departments'\nimport type { FormEventSink } from '../events/types'\nimport type { FieldTypeRegistry } from '../fields/registry'\nimport { registerPollCloseTask } from '../poll/closeJob'\nimport type { OutcomeFieldsOverride } from '../poll/outcomeFields'\nimport type { PollTypeRegistry } from '../poll/pollTypeRegistry'\nimport type { PollOptionSourceRegistry } from '../poll/registry'\nimport type { ResolvedSpamConfig } from '../spam/types'\nimport type { ValidationRuleRegistry } from '../validation/registry'\nimport type { CollectionOverrides } from './collectionOverrides'\nimport { attachUploadsCollection, type UploadsOption } from './uploadsCollection'\n\ntype RegisterCollectionsArgs = {\n\tconfig: Config\n\tregistry: FieldTypeRegistry\n\truleRegistry: ValidationRuleRegistry\n\tconsentSources?: ConsentSourcesResolver\n\tconsentSnapshot?: ConsentSnapshotMode\n\t/** Plugin `consent.resolveOnRead` (default true); false skips the per-read consent afterRead hook. */\n\tconsentResolveOnRead?: boolean\n\tactionRegistry: ActionRegistry\n\trichText?: RichTextBodyOption\n\thasJobsPlugin: boolean\n\tevents?: FormEventSink\n\tuploads: UploadsOption\n\tspam: ResolvedSpamConfig | false\n\tshowSubmissionRawFields: boolean\n\tlocalizeContent: boolean\n\tresultsAccess?: FormResultsAccess\n\tvotedCookie: boolean\n\tpollSourceRegistry: PollOptionSourceRegistry\n\tpollTypeRegistry: PollTypeRegistry\n\toutcomeFields?: OutcomeFieldsOverride\n\tbuttons?: ButtonsOption\n\tresponse?: ResponseOption\n\tfromAddresses?: FromAddressesResolver\n\tdepartments?: DepartmentEmailsResolver\n\tredirectRelationships?: CollectionSlug[]\n\toverrides?: {\n\t\tforms?: CollectionOverrides\n\t\tformSubmissions?: CollectionOverrides\n\t}\n}\n\nexport const registerCollections = ({\n\tconfig,\n\tregistry,\n\truleRegistry,\n\tconsentSources,\n\tconsentSnapshot,\n\tconsentResolveOnRead,\n\tactionRegistry,\n\trichText,\n\thasJobsPlugin,\n\tevents,\n\tuploads,\n\tspam,\n\tshowSubmissionRawFields,\n\tlocalizeContent,\n\tresultsAccess,\n\tvotedCookie,\n\tpollSourceRegistry,\n\tpollTypeRegistry,\n\toutcomeFields,\n\tbuttons,\n\tresponse,\n\tfromAddresses,\n\tdepartments,\n\tredirectRelationships,\n\toverrides,\n}: RegisterCollectionsArgs): void => {\n\tregisterActionsTask(config, actionRegistry, richText)\n\tregisterPollCloseTask(config)\n\tconst hasRunner = Boolean(config.jobs?.autoRun) || hasJobsPlugin\n\n\tconst uploadSlug = uploads === false ? undefined : uploads.collection\n\tif (uploads !== false) {\n\t\tattachUploadsCollection({ config, slug: uploads.collection, spam })\n\t}\n\n\t// Payload
|
|
1
|
+
{"version":3,"file":"registerCollections.js","names":[],"sources":["../../src/plugin/registerCollections.ts"],"sourcesContent":["import type { CollectionSlug, Config } from 'payload'\nimport type { RichTextBodyOption } from '../actions/body/serializeBody'\nimport type { FromAddressesResolver } from '../actions/fromAddresses'\nimport type { ActionRegistry } from '../actions/registry'\nimport { registerActionsTask } from '../actions/task'\nimport type { FormResultsAccess } from '../aggregation/resolveResultsRequest'\nimport type { CalcAllowed } from '../calc/normalizeCalc'\nimport type { CalcFunction, CalcSource } from '../calc/registry'\nimport type { ButtonsOption } from '../collections/buttonFields'\nimport { buildSubmissionsCollection } from '../collections/formSubmissions'\nimport { buildFormsCollection } from '../collections/forms'\nimport type { ResponseOption } from '../collections/redirectFields'\nimport type { SettingsOption } from '../collections/settingsFields'\nimport type { ConsentSnapshotMode } from '../consent/captureConsent'\nimport type { ConsentSourcesResolver } from '../consent/types'\nimport type { DepartmentEmailsResolver } from '../email/departments'\nimport type { FormEventSink } from '../events/types'\nimport type { FieldTypeRegistry } from '../fields/registry'\nimport { registerPollCloseTask } from '../poll/closeJob'\nimport type { OutcomeFieldsOverride } from '../poll/outcomeFields'\nimport type { PollTypeRegistry } from '../poll/pollTypeRegistry'\nimport type { PollOptionSourceRegistry } from '../poll/registry'\nimport { buildPollVotesCollection } from '../poll/votes/votesCollection'\nimport type { ResolvedSpamConfig } from '../spam/types'\nimport type { ValidationRuleRegistry } from '../validation/registry'\nimport type { CollectionOverrides } from './collectionOverrides'\nimport { attachUploadsCollection, type UploadsOption } from './uploadsCollection'\n\ntype RegisterCollectionsArgs = {\n\tconfig: Config\n\tregistry: FieldTypeRegistry\n\truleRegistry: ValidationRuleRegistry\n\t/** Registered calc extension names; gates which expressions the forms beforeValidate accepts. */\n\tcalcAllowed?: CalcAllowed\n\t/** Registered calc sources (plugin option `calc.sources`); resolved on form reads and at submit. */\n\tcalcSources?: Record<string, CalcSource>\n\t/** Registered calc functions (plugin option `calc.functions`); threaded into submit-time evaluation. */\n\tcalcFunctions?: Record<string, CalcFunction>\n\tconsentSources?: ConsentSourcesResolver\n\tconsentSnapshot?: ConsentSnapshotMode\n\t/** Plugin `consent.resolveOnRead` (default true); false skips the per-read consent afterRead hook. */\n\tconsentResolveOnRead?: boolean\n\tactionRegistry: ActionRegistry\n\trichText?: RichTextBodyOption\n\thasJobsPlugin: boolean\n\tevents?: FormEventSink\n\tuploads: UploadsOption\n\tspam: ResolvedSpamConfig | false\n\tshowSubmissionRawFields: boolean\n\tlocalizeContent: boolean\n\tresultsAccess?: FormResultsAccess\n\tvotedCookie: boolean\n\tpollSourceRegistry: PollOptionSourceRegistry\n\tpollTypeRegistry: PollTypeRegistry\n\toutcomeFields?: OutcomeFieldsOverride\n\t/** Resolved `poll.votes` option; `false` skips registering the hidden tally collection. */\n\tpollVotes: false | { overrides?: CollectionOverrides }\n\tbuttons?: ButtonsOption\n\tsettings?: SettingsOption\n\tresponse?: ResponseOption\n\tfromAddresses?: FromAddressesResolver\n\tdepartments?: DepartmentEmailsResolver\n\tredirectRelationships?: CollectionSlug[]\n\toverrides?: {\n\t\tforms?: CollectionOverrides\n\t\tformSubmissions?: CollectionOverrides\n\t}\n}\n\nexport const registerCollections = ({\n\tconfig,\n\tregistry,\n\truleRegistry,\n\tcalcAllowed,\n\tcalcSources,\n\tcalcFunctions,\n\tconsentSources,\n\tconsentSnapshot,\n\tconsentResolveOnRead,\n\tactionRegistry,\n\trichText,\n\thasJobsPlugin,\n\tevents,\n\tuploads,\n\tspam,\n\tshowSubmissionRawFields,\n\tlocalizeContent,\n\tresultsAccess,\n\tvotedCookie,\n\tpollSourceRegistry,\n\tpollTypeRegistry,\n\toutcomeFields,\n\tpollVotes,\n\tbuttons,\n\tsettings,\n\tresponse,\n\tfromAddresses,\n\tdepartments,\n\tredirectRelationships,\n\toverrides,\n}: RegisterCollectionsArgs): void => {\n\tconst pollVotesEnabled = pollVotes !== false\n\tregisterActionsTask(config, actionRegistry, richText)\n\tregisterPollCloseTask(config, pollVotesEnabled)\n\tconst hasRunner = Boolean(config.jobs?.autoRun) || hasJobsPlugin\n\n\tconst uploadSlug = uploads === false ? undefined : uploads.collection\n\tif (uploads !== false) {\n\t\tattachUploadsCollection({ config, slug: uploads.collection, spam })\n\t}\n\n\t// Payload lists nav entries in registration order (no nav-sort option). The primary\n\t// collection leads: forms, then form-submissions. Ordering the plugin's nav group against\n\t// host collections (including a BYO uploads collection) stays a host concern.\n\tconfig.collections = [\n\t\t...(config.collections ?? []),\n\t\tbuildFormsCollection({\n\t\t\tregistry,\n\t\t\truleRegistry,\n\t\t\tcalcAllowed,\n\t\t\tcalcSources,\n\t\t\tconsentSources,\n\t\t\tconsentResolveOnRead,\n\t\t\tactionRegistry,\n\t\t\tlocalizeContent,\n\t\t\trichText,\n\t\t\tuploadsCollectionSlug: uploadSlug,\n\t\t\tresultsAccess,\n\t\t\tpollVotesEnabled,\n\t\t\tpollSourceRegistry,\n\t\t\tpollTypeRegistry,\n\t\t\toutcomeFields,\n\t\t\tbuttons,\n\t\t\tsettings,\n\t\t\tresponse,\n\t\t\tfromAddresses,\n\t\t\tdepartments,\n\t\t\tredirectRelationships,\n\t\t\toverrides: overrides?.forms,\n\t\t}),\n\t\tbuildSubmissionsCollection({\n\t\t\tregistry,\n\t\t\truleRegistry,\n\t\t\tcalcSources,\n\t\t\tcalcFunctions,\n\t\t\tconsentSources,\n\t\t\tconsentSnapshot,\n\t\t\tactionRegistry,\n\t\t\trichText,\n\t\t\tevents,\n\t\t\thasRunner,\n\t\t\tuploadSlug,\n\t\t\tspam,\n\t\t\tvotedCookie,\n\t\t\tpollSourceRegistry,\n\t\t\tpollVotes,\n\t\t\tshowRawFields: showSubmissionRawFields,\n\t\t\toverrides: overrides?.formSubmissions,\n\t\t}),\n\t\t...(pollVotes === false ? [] : [buildPollVotesCollection({ overrides: pollVotes.overrides })]),\n\t]\n}\n"],"mappings":";;;;;;;AAqEA,MAAa,uBAAuB,EACnC,QACA,UACA,cACA,aACA,aACA,eACA,gBACA,iBACA,sBACA,gBACA,UACA,eACA,QACA,SACA,MACA,yBACA,iBACA,eACA,aACA,oBACA,kBACA,eACA,WACA,SACA,UACA,UACA,eACA,aACA,uBACA,gBACoC;CACpC,MAAM,mBAAmB,cAAc;CACvC,oBAAoB,QAAQ,gBAAgB,QAAQ;CACpD,sBAAsB,QAAQ,gBAAgB;CAC9C,MAAM,YAAY,QAAQ,OAAO,MAAM,OAAO,KAAK;CAEnD,MAAM,aAAa,YAAY,QAAQ,KAAA,IAAY,QAAQ;CAC3D,IAAI,YAAY,OACf,wBAAwB;EAAE;EAAQ,MAAM,QAAQ;EAAY;CAAK,CAAC;CAMnE,OAAO,cAAc;EACpB,GAAI,OAAO,eAAe,CAAC;EAC3B,qBAAqB;GACpB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,uBAAuB;GACvB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,WAAW,WAAW;EACvB,CAAC;EACD,2BAA2B;GAC1B;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA,eAAe;GACf,WAAW,WAAW;EACvB,CAAC;EACD,GAAI,cAAc,QAAQ,CAAC,IAAI,CAAC,yBAAyB,EAAE,WAAW,UAAU,UAAU,CAAC,CAAC;CAC7F;AACD"}
|
package/dist/poll/closeJob.d.ts
CHANGED
|
@@ -24,13 +24,14 @@ declare const shouldAutoResolvePoll: (form: PollFormLike) => boolean;
|
|
|
24
24
|
*/
|
|
25
25
|
declare const runPollClose: (args: {
|
|
26
26
|
payload: Payload;
|
|
27
|
-
input: PollCloseTaskInput;
|
|
27
|
+
input: PollCloseTaskInput; /** Whether the hidden tally store backs the outcome aggregation (see `resolvePollOutcome`). */
|
|
28
|
+
pollVotesEnabled?: boolean;
|
|
28
29
|
req?: PayloadRequest;
|
|
29
30
|
}) => Promise<void>;
|
|
30
31
|
/** Native Payload jobs task that resolves a poll's outcome once it closes. */
|
|
31
|
-
declare const buildPollCloseTask: () => TaskConfig;
|
|
32
|
+
declare const buildPollCloseTask: (pollVotesEnabled?: boolean) => TaskConfig;
|
|
32
33
|
/** Register the poll-close task on `config.jobs.tasks`, creating the jobs config if absent. */
|
|
33
|
-
declare const registerPollCloseTask: (config: Config) => void;
|
|
34
|
+
declare const registerPollCloseTask: (config: Config, pollVotesEnabled?: boolean) => void;
|
|
34
35
|
/**
|
|
35
36
|
* Schedule (or reschedule) the auto-close for a poll after a save. Enqueues a `waitUntil: closesAt`
|
|
36
37
|
* job when the poll is enabled, has a `closesAt`, is still unresolved, and its strategy is not
|
package/dist/poll/closeJob.js
CHANGED
|
@@ -25,7 +25,7 @@ const shouldAutoResolvePoll = (form) => {
|
|
|
25
25
|
* recorded (or a job that fires slightly early) is a safe no-op. Tolerates a deleted form.
|
|
26
26
|
*/
|
|
27
27
|
const runPollClose = async (args) => {
|
|
28
|
-
const { payload, input, req } = args;
|
|
28
|
+
const { payload, input, pollVotesEnabled, req } = args;
|
|
29
29
|
const form = await payload.findByID({
|
|
30
30
|
collection: FORMS_SLUG,
|
|
31
31
|
id: input.formId,
|
|
@@ -37,11 +37,12 @@ const runPollClose = async (args) => {
|
|
|
37
37
|
await resolvePollOutcome({
|
|
38
38
|
payload,
|
|
39
39
|
formId: input.formId,
|
|
40
|
+
pollVotesEnabled,
|
|
40
41
|
req
|
|
41
42
|
});
|
|
42
43
|
};
|
|
43
44
|
/** Native Payload jobs task that resolves a poll's outcome once it closes. */
|
|
44
|
-
const buildPollCloseTask = () => ({
|
|
45
|
+
const buildPollCloseTask = (pollVotesEnabled = false) => ({
|
|
45
46
|
slug: POLL_CLOSE_TASK_SLUG,
|
|
46
47
|
inputSchema: [{
|
|
47
48
|
name: "formId",
|
|
@@ -52,16 +53,17 @@ const buildPollCloseTask = () => ({
|
|
|
52
53
|
await runPollClose({
|
|
53
54
|
payload: req.payload,
|
|
54
55
|
input,
|
|
56
|
+
pollVotesEnabled,
|
|
55
57
|
req
|
|
56
58
|
});
|
|
57
59
|
return { output: {} };
|
|
58
60
|
}
|
|
59
61
|
});
|
|
60
62
|
/** Register the poll-close task on `config.jobs.tasks`, creating the jobs config if absent. */
|
|
61
|
-
const registerPollCloseTask = (config) => {
|
|
63
|
+
const registerPollCloseTask = (config, pollVotesEnabled = false) => {
|
|
62
64
|
config.jobs ??= {};
|
|
63
65
|
config.jobs.tasks ??= [];
|
|
64
|
-
config.jobs.tasks.push(buildPollCloseTask());
|
|
66
|
+
config.jobs.tasks.push(buildPollCloseTask(pollVotesEnabled));
|
|
65
67
|
};
|
|
66
68
|
const canQueue = (payload) => typeof payload.jobs?.queue === "function";
|
|
67
69
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"closeJob.js","names":[],"sources":["../../src/poll/closeJob.ts"],"sourcesContent":["import type { Config, Payload, PayloadRequest, TaskConfig } from 'payload'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { isPollClosed, type PollConfigLike, pollConfigOf } from '../form/pollState'\nimport { resolvePollOutcome } from './resolvePollOutcome'\n\nexport const POLL_CLOSE_TASK_SLUG = 'form-builder-poll-close'\n\n/** Payload's jobs collection; queried directly to supersede a superseded pending close job. */\nconst JOBS_SLUG = 'payload-jobs'\n\n/** Input the enqueue path stores; the handler re-loads everything else from the DB. */\nexport type PollCloseTaskInput = { formId: number | string }\n\n/** The slice of a loaded form the close gate reads. */\nexport type PollFormLike = { pollEnabled?: boolean | null; poll?: unknown }\n\nconst hasEmptyWinners = (poll: PollConfigLike): boolean => {\n\tconst winners = poll.outcome?.winningValues\n\treturn (\n\t\t!Array.isArray(winners) ||\n\t\twinners.filter((value) => typeof value === 'string' && value.length > 0).length === 0\n\t)\n}\n\nconst strategyOf = (poll: PollConfigLike): string =>\n\ttypeof poll.type === 'string' && poll.type.length > 0 ? poll.type : 'manual'\n\n/**\n * True when a poll's outcome should auto-resolve now: enabled, closed, still unresolved, and its\n * strategy is not `manual`. Shared by the close-job handler and the results-read fallback so the two\n * triggers apply the exact same gate.\n */\nexport const shouldAutoResolvePoll = (form: PollFormLike): boolean => {\n\tconst poll = pollConfigOf(form.poll)\n\treturn (\n\t\tform.pollEnabled === true &&\n\t\tpoll != null &&\n\t\tisPollClosed(poll) &&\n\t\thasEmptyWinners(poll) &&\n\t\tstrategyOf(poll) !== 'manual'\n\t)\n}\n\n/**\n * Run the scheduled close for one form. Idempotent: re-loads the form and only resolves when the\n * poll is enabled, closed, still unresolved, and not `manual`, so a re-run after the outcome was\n * recorded (or a job that fires slightly early) is a safe no-op. Tolerates a deleted form.\n */\nexport const runPollClose = async (args: {\n\tpayload: Payload\n\tinput: PollCloseTaskInput\n\treq?: PayloadRequest\n}): Promise<void> => {\n\tconst { payload, input, req } = args\n\tconst form = await payload\n\t\t.findByID({ collection: FORMS_SLUG, id: input.formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tif (!form || !shouldAutoResolvePoll(form as PollFormLike)) {\n\t\treturn\n\t}\n\tawait resolvePollOutcome({ payload, formId: input.formId, req })\n}\n\n/** Native Payload jobs task that resolves a poll's outcome once it closes. */\nexport const buildPollCloseTask = (): TaskConfig =>\n\t({\n\t\tslug: POLL_CLOSE_TASK_SLUG,\n\t\tinputSchema: [{ name: 'formId', type: 'text', required: true }],\n\t\thandler: async ({ input, req }) => {\n\t\t\tawait runPollClose({
|
|
1
|
+
{"version":3,"file":"closeJob.js","names":[],"sources":["../../src/poll/closeJob.ts"],"sourcesContent":["import type { Config, Payload, PayloadRequest, TaskConfig } from 'payload'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { isPollClosed, type PollConfigLike, pollConfigOf } from '../form/pollState'\nimport { resolvePollOutcome } from './resolvePollOutcome'\n\nexport const POLL_CLOSE_TASK_SLUG = 'form-builder-poll-close'\n\n/** Payload's jobs collection; queried directly to supersede a superseded pending close job. */\nconst JOBS_SLUG = 'payload-jobs'\n\n/** Input the enqueue path stores; the handler re-loads everything else from the DB. */\nexport type PollCloseTaskInput = { formId: number | string }\n\n/** The slice of a loaded form the close gate reads. */\nexport type PollFormLike = { pollEnabled?: boolean | null; poll?: unknown }\n\nconst hasEmptyWinners = (poll: PollConfigLike): boolean => {\n\tconst winners = poll.outcome?.winningValues\n\treturn (\n\t\t!Array.isArray(winners) ||\n\t\twinners.filter((value) => typeof value === 'string' && value.length > 0).length === 0\n\t)\n}\n\nconst strategyOf = (poll: PollConfigLike): string =>\n\ttypeof poll.type === 'string' && poll.type.length > 0 ? poll.type : 'manual'\n\n/**\n * True when a poll's outcome should auto-resolve now: enabled, closed, still unresolved, and its\n * strategy is not `manual`. Shared by the close-job handler and the results-read fallback so the two\n * triggers apply the exact same gate.\n */\nexport const shouldAutoResolvePoll = (form: PollFormLike): boolean => {\n\tconst poll = pollConfigOf(form.poll)\n\treturn (\n\t\tform.pollEnabled === true &&\n\t\tpoll != null &&\n\t\tisPollClosed(poll) &&\n\t\thasEmptyWinners(poll) &&\n\t\tstrategyOf(poll) !== 'manual'\n\t)\n}\n\n/**\n * Run the scheduled close for one form. Idempotent: re-loads the form and only resolves when the\n * poll is enabled, closed, still unresolved, and not `manual`, so a re-run after the outcome was\n * recorded (or a job that fires slightly early) is a safe no-op. Tolerates a deleted form.\n */\nexport const runPollClose = async (args: {\n\tpayload: Payload\n\tinput: PollCloseTaskInput\n\t/** Whether the hidden tally store backs the outcome aggregation (see `resolvePollOutcome`). */\n\tpollVotesEnabled?: boolean\n\treq?: PayloadRequest\n}): Promise<void> => {\n\tconst { payload, input, pollVotesEnabled, req } = args\n\tconst form = await payload\n\t\t.findByID({ collection: FORMS_SLUG, id: input.formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tif (!form || !shouldAutoResolvePoll(form as PollFormLike)) {\n\t\treturn\n\t}\n\tawait resolvePollOutcome({ payload, formId: input.formId, pollVotesEnabled, req })\n}\n\n/** Native Payload jobs task that resolves a poll's outcome once it closes. */\nexport const buildPollCloseTask = (pollVotesEnabled = false): TaskConfig =>\n\t({\n\t\tslug: POLL_CLOSE_TASK_SLUG,\n\t\tinputSchema: [{ name: 'formId', type: 'text', required: true }],\n\t\thandler: async ({ input, req }) => {\n\t\t\tawait runPollClose({\n\t\t\t\tpayload: req.payload,\n\t\t\t\tinput: input as PollCloseTaskInput,\n\t\t\t\tpollVotesEnabled,\n\t\t\t\treq,\n\t\t\t})\n\t\t\treturn { output: {} }\n\t\t},\n\t}) as TaskConfig\n\n/** Register the poll-close task on `config.jobs.tasks`, creating the jobs config if absent. */\nexport const registerPollCloseTask = (config: Config, pollVotesEnabled = false): void => {\n\tconfig.jobs ??= {}\n\tconfig.jobs.tasks ??= []\n\tconfig.jobs.tasks.push(buildPollCloseTask(pollVotesEnabled))\n}\n\nconst canQueue = (payload: Payload): boolean => typeof payload.jobs?.queue === 'function'\n\n/**\n * Delete this form's pending (never-run) close jobs so a re-enqueue supersedes the prior one. Payload\n * 3.85's `jobs.queue` has no concurrency key, so this mirrors core's `deleteScheduledPublishJobs`:\n * a direct `db.deleteMany` on the jobs collection, scoped by task slug and the JSON `input.formId`.\n * Best-effort; a failure here only risks a duplicate future job, which the idempotent handler absorbs.\n */\nconst deletePendingCloseJobs = async (\n\tpayload: Payload,\n\tformId: number | string,\n\treq?: PayloadRequest\n): Promise<void> => {\n\ttry {\n\t\tawait payload.db.deleteMany({\n\t\t\tcollection: JOBS_SLUG,\n\t\t\treq,\n\t\t\twhere: {\n\t\t\t\tand: [\n\t\t\t\t\t{ completedAt: { exists: false } },\n\t\t\t\t\t{ processing: { equals: false } },\n\t\t\t\t\t{ taskSlug: { equals: POLL_CLOSE_TASK_SLUG } },\n\t\t\t\t\t{ 'input.formId': { equals: String(formId) } },\n\t\t\t\t],\n\t\t\t},\n\t\t})\n\t} catch (error) {\n\t\tpayload.logger?.error(\n\t\t\t`@10x-media/form-builder: failed to clear pending poll-close jobs for form ${String(formId)}: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`\n\t\t)\n\t}\n}\n\n/**\n * Schedule (or reschedule) the auto-close for a poll after a save. Enqueues a `waitUntil: closesAt`\n * job when the poll is enabled, has a `closesAt`, is still unresolved, and its strategy is not\n * `manual`, and only when a job runner is present (`payload.jobs.queue`); otherwise the resolve-on-read\n * fallback is the safety net. Any prior pending close job for the form is deleted first so the newest\n * `closesAt` wins. Never throws; a queue failure is logged and swallowed.\n */\nexport const enqueuePollClose = async (args: {\n\tpayload: Payload\n\tform: { id: number | string; pollEnabled?: boolean | null; poll?: unknown }\n\treq?: PayloadRequest\n}): Promise<void> => {\n\tconst { payload, form, req } = args\n\tconst poll = pollConfigOf(form.poll)\n\tif (form.pollEnabled !== true || !poll) {\n\t\treturn\n\t}\n\tconst closesAt =\n\t\ttypeof poll.closesAt === 'string' && poll.closesAt.length > 0 ? poll.closesAt : undefined\n\tif (!closesAt || !hasEmptyWinners(poll) || strategyOf(poll) === 'manual' || !canQueue(payload)) {\n\t\treturn\n\t}\n\tconst waitUntil = new Date(closesAt)\n\tif (Number.isNaN(waitUntil.getTime())) {\n\t\treturn\n\t}\n\tawait deletePendingCloseJobs(payload, form.id, req)\n\ttry {\n\t\tawait payload.jobs.queue({\n\t\t\ttask: POLL_CLOSE_TASK_SLUG,\n\t\t\tinput: { formId: String(form.id) },\n\t\t\twaitUntil,\n\t\t\treq,\n\t\t})\n\t} catch (error) {\n\t\tpayload.logger?.error(\n\t\t\t`@10x-media/form-builder: failed to enqueue poll-close for form ${String(form.id)}: ${\n\t\t\t\terror instanceof Error ? error.message : String(error)\n\t\t\t}`\n\t\t)\n\t}\n}\n"],"mappings":";;;;AAKA,MAAa,uBAAuB;;AAGpC,MAAM,YAAY;AAQlB,MAAM,mBAAmB,SAAkC;CAC1D,MAAM,UAAU,KAAK,SAAS;CAC9B,OACC,CAAC,MAAM,QAAQ,OAAO,KACtB,QAAQ,QAAQ,UAAU,OAAO,UAAU,YAAY,MAAM,SAAS,CAAC,EAAE,WAAW;AAEtF;AAEA,MAAM,cAAc,SACnB,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,IAAI,KAAK,OAAO;;;;;;AAOrE,MAAa,yBAAyB,SAAgC;CACrE,MAAM,OAAO,aAAa,KAAK,IAAI;CACnC,OACC,KAAK,gBAAgB,QACrB,QAAQ,QACR,aAAa,IAAI,KACjB,gBAAgB,IAAI,KACpB,WAAW,IAAI,MAAM;AAEvB;;;;;;AAOA,MAAa,eAAe,OAAO,SAMd;CACpB,MAAM,EAAE,SAAS,OAAO,kBAAkB,QAAQ;CAClD,MAAM,OAAO,MAAM,QACjB,SAAS;EAAE,YAAY;EAAY,IAAI,MAAM;EAAQ,OAAO;EAAG,gBAAgB;EAAM;CAAI,CAAC,EAC1F,YAAY,IAAI;CAClB,IAAI,CAAC,QAAQ,CAAC,sBAAsB,IAAoB,GACvD;CAED,MAAM,mBAAmB;EAAE;EAAS,QAAQ,MAAM;EAAQ;EAAkB;CAAI,CAAC;AAClF;;AAGA,MAAa,sBAAsB,mBAAmB,WACpD;CACA,MAAM;CACN,aAAa,CAAC;EAAE,MAAM;EAAU,MAAM;EAAQ,UAAU;CAAK,CAAC;CAC9D,SAAS,OAAO,EAAE,OAAO,UAAU;EAClC,MAAM,aAAa;GAClB,SAAS,IAAI;GACN;GACP;GACA;EACD,CAAC;EACD,OAAO,EAAE,QAAQ,CAAC,EAAE;CACrB;AACD;;AAGD,MAAa,yBAAyB,QAAgB,mBAAmB,UAAgB;CACxF,OAAO,SAAS,CAAC;CACjB,OAAO,KAAK,UAAU,CAAC;CACvB,OAAO,KAAK,MAAM,KAAK,mBAAmB,gBAAgB,CAAC;AAC5D;AAEA,MAAM,YAAY,YAA8B,OAAO,QAAQ,MAAM,UAAU;;;;;;;AAQ/E,MAAM,yBAAyB,OAC9B,SACA,QACA,QACmB;CACnB,IAAI;EACH,MAAM,QAAQ,GAAG,WAAW;GAC3B,YAAY;GACZ;GACA,OAAO,EACN,KAAK;IACJ,EAAE,aAAa,EAAE,QAAQ,MAAM,EAAE;IACjC,EAAE,YAAY,EAAE,QAAQ,MAAM,EAAE;IAChC,EAAE,UAAU,EAAE,QAAQ,qBAAqB,EAAE;IAC7C,EAAE,gBAAgB,EAAE,QAAQ,OAAO,MAAM,EAAE,EAAE;GAC9C,EACD;EACD,CAAC;CACF,SAAS,OAAO;EACf,QAAQ,QAAQ,MACf,6EAA6E,OAAO,MAAM,EAAE,IAC3F,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEvD;CACD;AACD;;;;;;;;AASA,MAAa,mBAAmB,OAAO,SAIlB;CACpB,MAAM,EAAE,SAAS,MAAM,QAAQ;CAC/B,MAAM,OAAO,aAAa,KAAK,IAAI;CACnC,IAAI,KAAK,gBAAgB,QAAQ,CAAC,MACjC;CAED,MAAM,WACL,OAAO,KAAK,aAAa,YAAY,KAAK,SAAS,SAAS,IAAI,KAAK,WAAW,KAAA;CACjF,IAAI,CAAC,YAAY,CAAC,gBAAgB,IAAI,KAAK,WAAW,IAAI,MAAM,YAAY,CAAC,SAAS,OAAO,GAC5F;CAED,MAAM,YAAY,IAAI,KAAK,QAAQ;CACnC,IAAI,OAAO,MAAM,UAAU,QAAQ,CAAC,GACnC;CAED,MAAM,uBAAuB,SAAS,KAAK,IAAI,GAAG;CAClD,IAAI;EACH,MAAM,QAAQ,KAAK,MAAM;GACxB,MAAM;GACN,OAAO,EAAE,QAAQ,OAAO,KAAK,EAAE,EAAE;GACjC;GACA;EACD,CAAC;CACF,SAAS,OAAO;EACf,QAAQ,QAAQ,MACf,kEAAkE,OAAO,KAAK,EAAE,EAAE,IACjF,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAEvD;CACD;AACD"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { keys } from "../translations/keys.js";
|
|
2
2
|
import { applyRegistryConfig } from "../plugin/applyRegistryConfig.js";
|
|
3
3
|
import { customStateOf, stashCustomState } from "../plugin/customState.js";
|
|
4
|
+
import { pollOptionSourcesOf } from "./resolvePollOptions.js";
|
|
4
5
|
import { definePollType } from "./definePollType.js";
|
|
5
6
|
import { mostVotedStrategy } from "./mostVoted.js";
|
|
6
|
-
import { pollOptionSourcesOf } from "./resolvePollOptions.js";
|
|
7
7
|
//#region src/poll/pollTypeRegistry.ts
|
|
8
8
|
/** The default: an admin records `winningValues` by hand, so there is nothing to auto-resolve. */
|
|
9
9
|
const manualStrategy = definePollType({
|
|
@@ -47,7 +47,7 @@ const planPollClose = (form) => {
|
|
|
47
47
|
* with no result. Idempotent: an already-closed poll returns 400 rather than re-closing.
|
|
48
48
|
*/
|
|
49
49
|
const resolvePollCloseRequest = async (args) => {
|
|
50
|
-
const { payload, formId, isAuthed, req } = args;
|
|
50
|
+
const { payload, formId, isAuthed, pollVotesEnabled, req } = args;
|
|
51
51
|
if (!isAuthed) return {
|
|
52
52
|
status: 403,
|
|
53
53
|
body: { errors: [{ message: "Forbidden" }] }
|
|
@@ -94,6 +94,7 @@ const resolvePollCloseRequest = async (args) => {
|
|
|
94
94
|
winningValues: plan.resolveOutcome ? await resolvePollOutcome({
|
|
95
95
|
payload,
|
|
96
96
|
formId,
|
|
97
|
+
pollVotesEnabled,
|
|
97
98
|
req
|
|
98
99
|
}) : winnersOf(pollConfigOf(form.poll) ?? {})
|
|
99
100
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolvePollCloseRequest.js","names":[],"sources":["../../src/poll/resolvePollCloseRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { isPollClosed, type PollConfigLike, pollConfigOf } from '../form/pollState'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\nimport { resolvePollOutcome } from './resolvePollOutcome'\n\n/** The recorded winning set as non-empty strings; empty means no winner has been set yet. */\nconst winnersOf = (poll: PollConfigLike): string[] => {\n\tconst winners = poll.outcome?.winningValues\n\tif (!Array.isArray(winners)) {\n\t\treturn []\n\t}\n\treturn winners.filter((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\n/** The selected outcome strategy slug; an absent or empty `type` is `manual`. */\nconst strategyOf = (poll: PollConfigLike): string =>\n\ttypeof poll.type === 'string' && poll.type.length > 0 ? poll.type : 'manual'\n\n/** The slice of a loaded form the close planner reads. */\nexport type PollCloseFormLike = { pollEnabled?: boolean | null; poll?: unknown }\n\nexport type PollClosePlan =\n\t| { ok: false; reason: 'already-closed' | 'manual-no-winner' | 'not-poll' }\n\t| { ok: true; resolveOutcome: boolean }\n\n/**\n * Decide what closing a poll now should do, purely from a loaded form so the branch logic is testable\n * without a boot. `manual` requires a winner to already be recorded (closing only stamps the time);\n * `mostVoted`, `source`, and any host strategy auto-resolve on close. Refuses a non-poll form and an\n * already-closed poll (idempotency), so the request helper performs no write unless this returns `ok`.\n */\nexport const planPollClose = (form: PollCloseFormLike): PollClosePlan => {\n\tconst poll = pollConfigOf(form.poll)\n\tif (form.pollEnabled !== true || !poll) {\n\t\treturn { ok: false, reason: 'not-poll' }\n\t}\n\tif (isPollClosed(poll)) {\n\t\treturn { ok: false, reason: 'already-closed' }\n\t}\n\tif (strategyOf(poll) === 'manual' && winnersOf(poll).length === 0) {\n\t\treturn { ok: false, reason: 'manual-no-winner' }\n\t}\n\treturn { ok: true, resolveOutcome: strategyOf(poll) !== 'manual' }\n}\n\nexport type ResolvePollCloseRequestArgs = {\n\tpayload: Payload\n\tformId: number | string | undefined\n\t/** Whether the caller is authenticated (an admin/user). */\n\tisAuthed: boolean\n\treq: PayloadRequest\n}\n\nexport type ResolvePollCloseRequestResult = {\n\tstatus: number\n\tbody: { closesAt: string; winningValues: string[] } | { errors: { message: string }[] }\n}\n\n/**\n * Authorize and perform a manual poll close backing `POST /:id/close`. Only an authenticated caller\n * may close (anonymous is always 403, mirroring the other resolve* helpers); the route is a trusted\n * admin action, so the load and write run with `overrideAccess`. Sets `closesAt` to now through\n * `payload.update` so the collection hooks run, then for a non-manual strategy resolves the winners via\n * `resolvePollOutcome` (auto mode; a non-decidable poll simply records none and the read fallback heals\n * it later). A `manual` poll with no winner recorded is refused (400) so closing never strands a poll\n * with no result. Idempotent: an already-closed poll returns 400 rather than re-closing.\n */\nexport const resolvePollCloseRequest = async (\n\targs: ResolvePollCloseRequestArgs\n): Promise<ResolvePollCloseRequestResult> => {\n\tconst { payload, formId, isAuthed, req } = args\n\tif (!isAuthed) {\n\t\treturn { status: 403, body: { errors: [{ message: 'Forbidden' }] } }\n\t}\n\tif (formId == null) {\n\t\treturn { status: 400, body: { errors: [{ message: 'Missing form id' }] } }\n\t}\n\tconst form = await payload\n\t\t.findByID({ collection: FORMS_SLUG, id: formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tif (!form) {\n\t\treturn { status: 404, body: { errors: [{ message: 'Not found' }] } }\n\t}\n\n\tconst plan = planPollClose(form as PollCloseFormLike)\n\tif (!plan.ok) {\n\t\tif (plan.reason === 'manual-no-winner') {\n\t\t\treturn {\n\t\t\t\tstatus: 400,\n\t\t\t\tbody: { errors: [{ message: asTranslate(req.t)(keys.pollCloseManualNoWinner) }] },\n\t\t\t}\n\t\t}\n\t\tconst message = plan.reason === 'already-closed' ? 'Poll already closed' : 'Not a poll'\n\t\treturn { status: 400, body: { errors: [{ message }] } }\n\t}\n\n\tconst closesAt = new Date().toISOString()\n\tawait payload.update({\n\t\tcollection: FORMS_SLUG,\n\t\tid: formId,\n\t\tdata: { poll: { closesAt } },\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\n\tconst winningValues = plan.resolveOutcome\n\t\t? await resolvePollOutcome({ payload, formId, req })\n\t\t: winnersOf(pollConfigOf(form.poll) ?? {})\n\treturn { status: 200, body: { closesAt, winningValues } }\n}\n"],"mappings":";;;;;;;AAQA,MAAM,aAAa,SAAmC;CACrD,MAAM,UAAU,KAAK,SAAS;CAC9B,IAAI,CAAC,MAAM,QAAQ,OAAO,GACzB,OAAO,CAAC;CAET,OAAO,QAAQ,QAAQ,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,CAAC;AAChG;;AAGA,MAAM,cAAc,SACnB,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,IAAI,KAAK,OAAO;;;;;;;AAerE,MAAa,iBAAiB,SAA2C;CACxE,MAAM,OAAO,aAAa,KAAK,IAAI;CACnC,IAAI,KAAK,gBAAgB,QAAQ,CAAC,MACjC,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAW;CAExC,IAAI,aAAa,IAAI,GACpB,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAiB;CAE9C,IAAI,WAAW,IAAI,MAAM,YAAY,UAAU,IAAI,EAAE,WAAW,GAC/D,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAmB;CAEhD,OAAO;EAAE,IAAI;EAAM,gBAAgB,WAAW,IAAI,MAAM;CAAS;AAClE;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"resolvePollCloseRequest.js","names":[],"sources":["../../src/poll/resolvePollCloseRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { isPollClosed, type PollConfigLike, pollConfigOf } from '../form/pollState'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\nimport { resolvePollOutcome } from './resolvePollOutcome'\n\n/** The recorded winning set as non-empty strings; empty means no winner has been set yet. */\nconst winnersOf = (poll: PollConfigLike): string[] => {\n\tconst winners = poll.outcome?.winningValues\n\tif (!Array.isArray(winners)) {\n\t\treturn []\n\t}\n\treturn winners.filter((value): value is string => typeof value === 'string' && value.length > 0)\n}\n\n/** The selected outcome strategy slug; an absent or empty `type` is `manual`. */\nconst strategyOf = (poll: PollConfigLike): string =>\n\ttypeof poll.type === 'string' && poll.type.length > 0 ? poll.type : 'manual'\n\n/** The slice of a loaded form the close planner reads. */\nexport type PollCloseFormLike = { pollEnabled?: boolean | null; poll?: unknown }\n\nexport type PollClosePlan =\n\t| { ok: false; reason: 'already-closed' | 'manual-no-winner' | 'not-poll' }\n\t| { ok: true; resolveOutcome: boolean }\n\n/**\n * Decide what closing a poll now should do, purely from a loaded form so the branch logic is testable\n * without a boot. `manual` requires a winner to already be recorded (closing only stamps the time);\n * `mostVoted`, `source`, and any host strategy auto-resolve on close. Refuses a non-poll form and an\n * already-closed poll (idempotency), so the request helper performs no write unless this returns `ok`.\n */\nexport const planPollClose = (form: PollCloseFormLike): PollClosePlan => {\n\tconst poll = pollConfigOf(form.poll)\n\tif (form.pollEnabled !== true || !poll) {\n\t\treturn { ok: false, reason: 'not-poll' }\n\t}\n\tif (isPollClosed(poll)) {\n\t\treturn { ok: false, reason: 'already-closed' }\n\t}\n\tif (strategyOf(poll) === 'manual' && winnersOf(poll).length === 0) {\n\t\treturn { ok: false, reason: 'manual-no-winner' }\n\t}\n\treturn { ok: true, resolveOutcome: strategyOf(poll) !== 'manual' }\n}\n\nexport type ResolvePollCloseRequestArgs = {\n\tpayload: Payload\n\tformId: number | string | undefined\n\t/** Whether the caller is authenticated (an admin/user). */\n\tisAuthed: boolean\n\t/** Whether the hidden tally store backs the outcome aggregation (see `resolvePollOutcome`). */\n\tpollVotesEnabled?: boolean\n\treq: PayloadRequest\n}\n\nexport type ResolvePollCloseRequestResult = {\n\tstatus: number\n\tbody: { closesAt: string; winningValues: string[] } | { errors: { message: string }[] }\n}\n\n/**\n * Authorize and perform a manual poll close backing `POST /:id/close`. Only an authenticated caller\n * may close (anonymous is always 403, mirroring the other resolve* helpers); the route is a trusted\n * admin action, so the load and write run with `overrideAccess`. Sets `closesAt` to now through\n * `payload.update` so the collection hooks run, then for a non-manual strategy resolves the winners via\n * `resolvePollOutcome` (auto mode; a non-decidable poll simply records none and the read fallback heals\n * it later). A `manual` poll with no winner recorded is refused (400) so closing never strands a poll\n * with no result. Idempotent: an already-closed poll returns 400 rather than re-closing.\n */\nexport const resolvePollCloseRequest = async (\n\targs: ResolvePollCloseRequestArgs\n): Promise<ResolvePollCloseRequestResult> => {\n\tconst { payload, formId, isAuthed, pollVotesEnabled, req } = args\n\tif (!isAuthed) {\n\t\treturn { status: 403, body: { errors: [{ message: 'Forbidden' }] } }\n\t}\n\tif (formId == null) {\n\t\treturn { status: 400, body: { errors: [{ message: 'Missing form id' }] } }\n\t}\n\tconst form = await payload\n\t\t.findByID({ collection: FORMS_SLUG, id: formId, depth: 0, overrideAccess: true, req })\n\t\t.catch(() => null)\n\tif (!form) {\n\t\treturn { status: 404, body: { errors: [{ message: 'Not found' }] } }\n\t}\n\n\tconst plan = planPollClose(form as PollCloseFormLike)\n\tif (!plan.ok) {\n\t\tif (plan.reason === 'manual-no-winner') {\n\t\t\treturn {\n\t\t\t\tstatus: 400,\n\t\t\t\tbody: { errors: [{ message: asTranslate(req.t)(keys.pollCloseManualNoWinner) }] },\n\t\t\t}\n\t\t}\n\t\tconst message = plan.reason === 'already-closed' ? 'Poll already closed' : 'Not a poll'\n\t\treturn { status: 400, body: { errors: [{ message }] } }\n\t}\n\n\tconst closesAt = new Date().toISOString()\n\tawait payload.update({\n\t\tcollection: FORMS_SLUG,\n\t\tid: formId,\n\t\tdata: { poll: { closesAt } },\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\n\tconst winningValues = plan.resolveOutcome\n\t\t? await resolvePollOutcome({ payload, formId, pollVotesEnabled, req })\n\t\t: winnersOf(pollConfigOf(form.poll) ?? {})\n\treturn { status: 200, body: { closesAt, winningValues } }\n}\n"],"mappings":";;;;;;;AAQA,MAAM,aAAa,SAAmC;CACrD,MAAM,UAAU,KAAK,SAAS;CAC9B,IAAI,CAAC,MAAM,QAAQ,OAAO,GACzB,OAAO,CAAC;CAET,OAAO,QAAQ,QAAQ,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,CAAC;AAChG;;AAGA,MAAM,cAAc,SACnB,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,IAAI,KAAK,OAAO;;;;;;;AAerE,MAAa,iBAAiB,SAA2C;CACxE,MAAM,OAAO,aAAa,KAAK,IAAI;CACnC,IAAI,KAAK,gBAAgB,QAAQ,CAAC,MACjC,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAW;CAExC,IAAI,aAAa,IAAI,GACpB,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAiB;CAE9C,IAAI,WAAW,IAAI,MAAM,YAAY,UAAU,IAAI,EAAE,WAAW,GAC/D,OAAO;EAAE,IAAI;EAAO,QAAQ;CAAmB;CAEhD,OAAO;EAAE,IAAI;EAAM,gBAAgB,WAAW,IAAI,MAAM;CAAS;AAClE;;;;;;;;;;AA0BA,MAAa,0BAA0B,OACtC,SAC4C;CAC5C,MAAM,EAAE,SAAS,QAAQ,UAAU,kBAAkB,QAAQ;CAC7D,IAAI,CAAC,UACJ,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;CAAE;CAEpE,IAAI,UAAU,MACb,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,kBAAkB,CAAC,EAAE;CAAE;CAE1E,MAAM,OAAO,MAAM,QACjB,SAAS;EAAE,YAAY;EAAY,IAAI;EAAQ,OAAO;EAAG,gBAAgB;EAAM;CAAI,CAAC,EACpF,YAAY,IAAI;CAClB,IAAI,CAAC,MACJ,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;CAAE;CAGpE,MAAM,OAAO,cAAc,IAAyB;CACpD,IAAI,CAAC,KAAK,IAAI;EACb,IAAI,KAAK,WAAW,oBACnB,OAAO;GACN,QAAQ;GACR,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,IAAI,CAAC,EAAE,KAAK,uBAAuB,EAAE,CAAC,EAAE;EACjF;EAGD,OAAO;GAAE,QAAQ;GAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SADzB,KAAK,WAAW,mBAAmB,wBAAwB,aAC1B,CAAC,EAAE;EAAE;CACvD;CAEA,MAAM,4BAAW,IAAI,KAAK,GAAE,YAAY;CACxC,MAAM,QAAQ,OAAO;EACpB,YAAY;EACZ,IAAI;EACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE;EAC3B,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC;CAKD,OAAO;EAAE,QAAQ;EAAK,MAAM;GAAE;GAAU,eAHlB,KAAK,iBACxB,MAAM,mBAAmB;IAAE;IAAS;IAAQ;IAAkB;GAAI,CAAC,IACnE,UAAU,aAAa,KAAK,IAAI,KAAK,CAAC,CAAC;EACY;CAAE;AACzD"}
|
|
@@ -10,6 +10,12 @@ type ResolvePollOutcomeArgs = {
|
|
|
10
10
|
* the outcome. Omit to auto-resolve via the poll's selected outcome strategy (`poll.type`).
|
|
11
11
|
*/
|
|
12
12
|
winningValues?: string[];
|
|
13
|
+
/**
|
|
14
|
+
* Whether the hidden tally store backs the auto-resolve aggregation (`mostVoted` and any host
|
|
15
|
+
* strategy that calls `aggregate()`). False keeps the submission scan, so persist-off forms
|
|
16
|
+
* only resolve correctly with the store enabled.
|
|
17
|
+
*/
|
|
18
|
+
pollVotesEnabled?: boolean;
|
|
13
19
|
req?: PayloadRequest;
|
|
14
20
|
};
|
|
15
21
|
/**
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { pollConfigOf } from "../form/pollState.js";
|
|
2
2
|
import { aggregateFieldResponses } from "../aggregation/aggregateResponses.js";
|
|
3
|
+
import { resolveEffectivePollOptions } from "./effectivePollOptions.js";
|
|
3
4
|
import { pollTypesOf } from "./pollTypeRegistry.js";
|
|
5
|
+
import { aggregateFromVotes } from "./votes/aggregateFromVotes.js";
|
|
4
6
|
import { FORMS_SLUG } from "../collections/forms.js";
|
|
5
7
|
//#region src/poll/resolvePollOutcome.ts
|
|
6
8
|
/** A strategy result narrowed to a deduped set of non-empty strings. */
|
|
@@ -22,7 +24,7 @@ const cleanWinners = (value) => value === void 0 ? [] : [...new Set(value.filter
|
|
|
22
24
|
* auto mode did not decide).
|
|
23
25
|
*/
|
|
24
26
|
const resolvePollOutcome = async (args) => {
|
|
25
|
-
const { payload, formId, req } = args;
|
|
27
|
+
const { payload, formId, pollVotesEnabled, req } = args;
|
|
26
28
|
const form = await payload.findByID({
|
|
27
29
|
collection: FORMS_SLUG,
|
|
28
30
|
id: formId,
|
|
@@ -42,12 +44,24 @@ const resolvePollOutcome = async (args) => {
|
|
|
42
44
|
const aggregate = async () => {
|
|
43
45
|
if (aggregated === void 0) {
|
|
44
46
|
const resultsField = typeof poll.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
|
|
45
|
-
|
|
47
|
+
if (!resultsField) aggregated = null;
|
|
48
|
+
else if (pollVotesEnabled === true) aggregated = await aggregateFromVotes({
|
|
46
49
|
payload,
|
|
47
50
|
formId,
|
|
48
51
|
field: resultsField,
|
|
52
|
+
options: await resolveEffectivePollOptions({
|
|
53
|
+
payload,
|
|
54
|
+
req,
|
|
55
|
+
form
|
|
56
|
+
}).catch(() => []),
|
|
49
57
|
req
|
|
50
|
-
})
|
|
58
|
+
});
|
|
59
|
+
else aggregated = await aggregateFieldResponses({
|
|
60
|
+
payload,
|
|
61
|
+
formId,
|
|
62
|
+
field: resultsField,
|
|
63
|
+
req
|
|
64
|
+
});
|
|
51
65
|
}
|
|
52
66
|
return aggregated;
|
|
53
67
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolvePollOutcome.js","names":[],"sources":["../../src/poll/resolvePollOutcome.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { aggregateFieldResponses } from '../aggregation/aggregateResponses'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { pollConfigOf } from '../form/pollState'\nimport type { PollOutcomeStrategyArgs } from './definePollType'\nimport { pollTypesOf } from './pollTypeRegistry'\n\nexport type ResolvePollOutcomeArgs = {\n\tpayload: Payload\n\tformId: number | string\n\t/**\n\t * The winning set: stable option values, each matching one of the poll's choice values (the\n\t * host's contract with `PollOption.value`). Pass more than one for a tie, an empty array to clear\n\t * the outcome. Omit to auto-resolve via the poll's selected outcome strategy (`poll.type`).\n\t */\n\twinningValues?: string[]\n\treq?: PayloadRequest\n}\n\n/** A strategy result narrowed to a deduped set of non-empty strings. */\nconst cleanWinners = (value: string[] | undefined): string[] =>\n\tvalue === undefined\n\t\t? []\n\t\t: [\n\t\t\t\t...new Set(\n\t\t\t\t\tvalue.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)\n\t\t\t\t),\n\t\t\t]\n\n/**\n * Record a poll's final outcome server-side, in one of two modes:\n * - explicit: pass `winningValues` when host code already knows the winner(s); more than one is a\n * tie, and an empty array clears the outcome;\n * - auto: omit it and the poll's selected outcome strategy (`poll.type`, from the `poll.types`\n * registry, defaulting to `manual`) resolves the winners. `manual` is a no-op; `mostVoted` reads\n * the aggregated results field; `source` delegates to the option source. A strategy that is not\n * yet decidable (or `manual`) writes nothing and this returns an empty set, so auto mode is safe\n * to call repeatedly from the close job and the read fallback.\n *\n * Every write runs through `payload.update` with `overrideAccess`, so the forms collection hook\n * validates each value against the poll's effective options and owns the `poll.outcome.resolvedAt`\n * stamp in both modes (auto-resolved winners are validated exactly as hand-picked ones). Throws only\n * when the form does not exist or is not poll-enabled. Returns the recorded winning set (empty when\n * auto mode did not decide).\n */\nexport const resolvePollOutcome = async (args: ResolvePollOutcomeArgs): Promise<string[]> => {\n\tconst { payload, formId, req } = args\n\tconst form = await payload.findByID({\n\t\tcollection: FORMS_SLUG,\n\t\tid: formId,\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\tconst poll = pollConfigOf(form.poll)\n\tif (form.pollEnabled !== true || !poll) {\n\t\tthrow new Error(`Form ${String(formId)} is not poll-enabled; cannot record an outcome.`)\n\t}\n\n\tlet winningValues: string[]\n\tif (args.winningValues !== undefined) {\n\t\twinningValues = args.winningValues\n\t} else {\n\t\tconst strategyType =\n\t\t\ttypeof poll.type === 'string' && poll.type.length > 0 ? poll.type : 'manual'\n\t\tconst strategy = pollTypesOf(payload).get(strategyType)\n\t\tif (!strategy) {\n\t\t\treturn []\n\t\t}\n\t\tlet aggregated: FieldAggregation | null | undefined\n\t\tconst aggregate = async (): Promise<FieldAggregation | null> => {\n\t\t\tif (aggregated === undefined) {\n\t\t\t\tconst resultsField =\n\t\t\t\t\ttypeof poll.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t\t\t? poll.resultsField\n\t\t\t\t\t\t: undefined\n\t\t\t\taggregated = resultsField\n\t\t\t\t\t
|
|
1
|
+
{"version":3,"file":"resolvePollOutcome.js","names":[],"sources":["../../src/poll/resolvePollOutcome.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { aggregateFieldResponses } from '../aggregation/aggregateResponses'\nimport type { FieldAggregation } from '../aggregation/types'\nimport { FORMS_SLUG } from '../collections/forms'\nimport { pollConfigOf } from '../form/pollState'\nimport type { PollOutcomeStrategyArgs } from './definePollType'\nimport { resolveEffectivePollOptions } from './effectivePollOptions'\nimport { pollTypesOf } from './pollTypeRegistry'\nimport { aggregateFromVotes } from './votes/aggregateFromVotes'\n\nexport type ResolvePollOutcomeArgs = {\n\tpayload: Payload\n\tformId: number | string\n\t/**\n\t * The winning set: stable option values, each matching one of the poll's choice values (the\n\t * host's contract with `PollOption.value`). Pass more than one for a tie, an empty array to clear\n\t * the outcome. Omit to auto-resolve via the poll's selected outcome strategy (`poll.type`).\n\t */\n\twinningValues?: string[]\n\t/**\n\t * Whether the hidden tally store backs the auto-resolve aggregation (`mostVoted` and any host\n\t * strategy that calls `aggregate()`). False keeps the submission scan, so persist-off forms\n\t * only resolve correctly with the store enabled.\n\t */\n\tpollVotesEnabled?: boolean\n\treq?: PayloadRequest\n}\n\n/** A strategy result narrowed to a deduped set of non-empty strings. */\nconst cleanWinners = (value: string[] | undefined): string[] =>\n\tvalue === undefined\n\t\t? []\n\t\t: [\n\t\t\t\t...new Set(\n\t\t\t\t\tvalue.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0)\n\t\t\t\t),\n\t\t\t]\n\n/**\n * Record a poll's final outcome server-side, in one of two modes:\n * - explicit: pass `winningValues` when host code already knows the winner(s); more than one is a\n * tie, and an empty array clears the outcome;\n * - auto: omit it and the poll's selected outcome strategy (`poll.type`, from the `poll.types`\n * registry, defaulting to `manual`) resolves the winners. `manual` is a no-op; `mostVoted` reads\n * the aggregated results field; `source` delegates to the option source. A strategy that is not\n * yet decidable (or `manual`) writes nothing and this returns an empty set, so auto mode is safe\n * to call repeatedly from the close job and the read fallback.\n *\n * Every write runs through `payload.update` with `overrideAccess`, so the forms collection hook\n * validates each value against the poll's effective options and owns the `poll.outcome.resolvedAt`\n * stamp in both modes (auto-resolved winners are validated exactly as hand-picked ones). Throws only\n * when the form does not exist or is not poll-enabled. Returns the recorded winning set (empty when\n * auto mode did not decide).\n */\nexport const resolvePollOutcome = async (args: ResolvePollOutcomeArgs): Promise<string[]> => {\n\tconst { payload, formId, pollVotesEnabled, req } = args\n\tconst form = await payload.findByID({\n\t\tcollection: FORMS_SLUG,\n\t\tid: formId,\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\tconst poll = pollConfigOf(form.poll)\n\tif (form.pollEnabled !== true || !poll) {\n\t\tthrow new Error(`Form ${String(formId)} is not poll-enabled; cannot record an outcome.`)\n\t}\n\n\tlet winningValues: string[]\n\tif (args.winningValues !== undefined) {\n\t\twinningValues = args.winningValues\n\t} else {\n\t\tconst strategyType =\n\t\t\ttypeof poll.type === 'string' && poll.type.length > 0 ? poll.type : 'manual'\n\t\tconst strategy = pollTypesOf(payload).get(strategyType)\n\t\tif (!strategy) {\n\t\t\treturn []\n\t\t}\n\t\tlet aggregated: FieldAggregation | null | undefined\n\t\tconst aggregate = async (): Promise<FieldAggregation | null> => {\n\t\t\tif (aggregated === undefined) {\n\t\t\t\tconst resultsField =\n\t\t\t\t\ttypeof poll.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t\t\t\t? poll.resultsField\n\t\t\t\t\t\t: undefined\n\t\t\t\tif (!resultsField) {\n\t\t\t\t\taggregated = null\n\t\t\t\t} else if (pollVotesEnabled === true) {\n\t\t\t\t\t// Best-effort options: a source/resolver failure degrades to raw tally values\n\t\t\t\t\t// (the outcome hook still validates winners against the effective options).\n\t\t\t\t\tconst options = await resolveEffectivePollOptions({ payload, req, form }).catch(() => [])\n\t\t\t\t\taggregated = await aggregateFromVotes({\n\t\t\t\t\t\tpayload,\n\t\t\t\t\t\tformId,\n\t\t\t\t\t\tfield: resultsField,\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\treq,\n\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\taggregated = await aggregateFieldResponses({ payload, formId, field: resultsField, req })\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn aggregated\n\t\t}\n\t\twinningValues = cleanWinners(\n\t\t\tawait strategy.resolveOutcome({\n\t\t\t\tpayload,\n\t\t\t\treq,\n\t\t\t\tform: form as unknown as PollOutcomeStrategyArgs['form'],\n\t\t\t\tpoll,\n\t\t\t\taggregate,\n\t\t\t})\n\t\t)\n\t\tif (winningValues.length === 0) {\n\t\t\treturn []\n\t\t}\n\t}\n\n\tawait payload.update({\n\t\tcollection: FORMS_SLUG,\n\t\tid: formId,\n\t\tdata: { poll: { outcome: { winningValues } } },\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\treturn winningValues\n}\n"],"mappings":";;;;;;;;AA6BA,MAAM,gBAAgB,UACrB,UAAU,KAAA,IACP,CAAC,IACD,CACA,GAAG,IAAI,IACN,MAAM,QAAQ,UAA2B,OAAO,UAAU,YAAY,MAAM,SAAS,CAAC,CACvF,CACD;;;;;;;;;;;;;;;;;AAkBH,MAAa,qBAAqB,OAAO,SAAoD;CAC5F,MAAM,EAAE,SAAS,QAAQ,kBAAkB,QAAQ;CACnD,MAAM,OAAO,MAAM,QAAQ,SAAS;EACnC,YAAY;EACZ,IAAI;EACJ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC;CACD,MAAM,OAAO,aAAa,KAAK,IAAI;CACnC,IAAI,KAAK,gBAAgB,QAAQ,CAAC,MACjC,MAAM,IAAI,MAAM,QAAQ,OAAO,MAAM,EAAE,gDAAgD;CAGxF,IAAI;CACJ,IAAI,KAAK,kBAAkB,KAAA,GAC1B,gBAAgB,KAAK;MACf;EACN,MAAM,eACL,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,SAAS,IAAI,KAAK,OAAO;EACrE,MAAM,WAAW,YAAY,OAAO,EAAE,IAAI,YAAY;EACtD,IAAI,CAAC,UACJ,OAAO,CAAC;EAET,IAAI;EACJ,MAAM,YAAY,YAA8C;GAC/D,IAAI,eAAe,KAAA,GAAW;IAC7B,MAAM,eACL,OAAO,KAAK,iBAAiB,YAAY,KAAK,aAAa,SAAS,IACjE,KAAK,eACL,KAAA;IACJ,IAAI,CAAC,cACJ,aAAa;SACP,IAAI,qBAAqB,MAI/B,aAAa,MAAM,mBAAmB;KACrC;KACA;KACA,OAAO;KACP,SAAA,MALqB,4BAA4B;MAAE;MAAS;MAAK;KAAK,CAAC,EAAE,YAAY,CAAC,CAAC;KAMvF;IACD,CAAC;SAED,aAAa,MAAM,wBAAwB;KAAE;KAAS;KAAQ,OAAO;KAAc;IAAI,CAAC;GAE1F;GACA,OAAO;EACR;EACA,gBAAgB,aACf,MAAM,SAAS,eAAe;GAC7B;GACA;GACM;GACN;GACA;EACD,CAAC,CACF;EACA,IAAI,cAAc,WAAW,GAC5B,OAAO,CAAC;CAEV;CAEA,MAAM,QAAQ,OAAO;EACpB,YAAY;EACZ,IAAI;EACJ,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,cAAc,EAAE,EAAE;EAC7C,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC;CACD,OAAO;AACR"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { FieldAggregation } from "../../aggregation/types.js";
|
|
2
|
+
import { Payload, PayloadRequest } from "payload";
|
|
3
|
+
|
|
4
|
+
//#region src/poll/votes/aggregateFromVotes.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Poll results from the tally store: one find over the form's rows for the field (O(options),
|
|
7
|
+
* no scan, no truncation), buckets zero-seeded from the effective options so order and labels
|
|
8
|
+
* match the scan-based shape. Counts sum across shard rows (see VOTE_SHARDS). `total` comes
|
|
9
|
+
* from the respondents rows, keeping the percentage denominator exact for multi-value answers.
|
|
10
|
+
*/
|
|
11
|
+
declare const aggregateFromVotes: (args: {
|
|
12
|
+
payload: Payload;
|
|
13
|
+
formId: number | string;
|
|
14
|
+
field: string;
|
|
15
|
+
meta?: {
|
|
16
|
+
label?: string;
|
|
17
|
+
fieldType?: string;
|
|
18
|
+
};
|
|
19
|
+
options: {
|
|
20
|
+
value: string;
|
|
21
|
+
label: string;
|
|
22
|
+
}[];
|
|
23
|
+
req?: PayloadRequest;
|
|
24
|
+
}) => Promise<FieldAggregation>;
|
|
25
|
+
//#endregion
|
|
26
|
+
export { aggregateFromVotes };
|
|
27
|
+
//# sourceMappingURL=aggregateFromVotes.d.ts.map
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { POLL_VOTES_SLUG } from "./votesCollection.js";
|
|
2
|
+
//#region src/poll/votes/aggregateFromVotes.ts
|
|
3
|
+
const round1 = (n) => Math.round(n * 10) / 10;
|
|
4
|
+
/**
|
|
5
|
+
* Poll results from the tally store: one find over the form's rows for the field (O(options),
|
|
6
|
+
* no scan, no truncation), buckets zero-seeded from the effective options so order and labels
|
|
7
|
+
* match the scan-based shape. Counts sum across shard rows (see VOTE_SHARDS). `total` comes
|
|
8
|
+
* from the respondents rows, keeping the percentage denominator exact for multi-value answers.
|
|
9
|
+
*/
|
|
10
|
+
const aggregateFromVotes = async (args) => {
|
|
11
|
+
const { payload, formId, field, meta, options, req } = args;
|
|
12
|
+
const { docs } = await payload.find({
|
|
13
|
+
collection: POLL_VOTES_SLUG,
|
|
14
|
+
where: { and: [{ form: { equals: String(formId) } }, { field: { equals: field } }] },
|
|
15
|
+
limit: 1e5,
|
|
16
|
+
pagination: false,
|
|
17
|
+
depth: 0,
|
|
18
|
+
overrideAccess: true,
|
|
19
|
+
req
|
|
20
|
+
});
|
|
21
|
+
const counts = /* @__PURE__ */ new Map();
|
|
22
|
+
let total = 0;
|
|
23
|
+
for (const doc of docs) {
|
|
24
|
+
const value = doc.value == null ? "" : String(doc.value);
|
|
25
|
+
const count = typeof doc.count === "number" ? doc.count : 0;
|
|
26
|
+
if (value === "") total += count;
|
|
27
|
+
else counts.set(value, (counts.get(value) ?? 0) + count);
|
|
28
|
+
}
|
|
29
|
+
const optionValues = new Set(options.map((option) => option.value));
|
|
30
|
+
const leftovers = [...counts.keys()].filter((value) => !optionValues.has(value)).sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0));
|
|
31
|
+
const labelByValue = new Map(options.map((option) => [option.value, option.label]));
|
|
32
|
+
const buckets = [...options.map((option) => option.value), ...leftovers].map((value) => {
|
|
33
|
+
const count = counts.get(value) ?? 0;
|
|
34
|
+
return {
|
|
35
|
+
value,
|
|
36
|
+
label: labelByValue.get(value) ?? value,
|
|
37
|
+
count,
|
|
38
|
+
percentage: total > 0 ? round1(count / total * 100) : 0
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
return {
|
|
42
|
+
field,
|
|
43
|
+
label: meta?.label,
|
|
44
|
+
fieldType: meta?.fieldType,
|
|
45
|
+
total,
|
|
46
|
+
buckets,
|
|
47
|
+
truncated: false
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
//#endregion
|
|
51
|
+
export { aggregateFromVotes };
|
|
52
|
+
|
|
53
|
+
//# sourceMappingURL=aggregateFromVotes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aggregateFromVotes.js","names":[],"sources":["../../../src/poll/votes/aggregateFromVotes.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport type { FieldAggregation } from '../../aggregation/types'\nimport { POLL_VOTES_SLUG, RESPONDENTS_VALUE } from './votesCollection'\n\ntype VoteRow = { field?: unknown; value?: unknown; count?: unknown }\n\nconst round1 = (n: number): number => Math.round(n * 10) / 10\n\n/**\n * Poll results from the tally store: one find over the form's rows for the field (O(options),\n * no scan, no truncation), buckets zero-seeded from the effective options so order and labels\n * match the scan-based shape. Counts sum across shard rows (see VOTE_SHARDS). `total` comes\n * from the respondents rows, keeping the percentage denominator exact for multi-value answers.\n */\nexport const aggregateFromVotes = async (args: {\n\tpayload: Payload\n\tformId: number | string\n\tfield: string\n\tmeta?: { label?: string; fieldType?: string }\n\toptions: { value: string; label: string }[]\n\treq?: PayloadRequest\n}): Promise<FieldAggregation> => {\n\tconst { payload, formId, field, meta, options, req } = args\n\tconst { docs } = await payload.find({\n\t\tcollection: POLL_VOTES_SLUG,\n\t\twhere: { and: [{ form: { equals: String(formId) } }, { field: { equals: field } }] },\n\t\tlimit: 100_000,\n\t\tpagination: false,\n\t\tdepth: 0,\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\n\tconst counts = new Map<string, number>()\n\tlet total = 0\n\tfor (const doc of docs as VoteRow[]) {\n\t\tconst value = doc.value == null ? RESPONDENTS_VALUE : String(doc.value)\n\t\tconst count = typeof doc.count === 'number' ? doc.count : 0\n\t\tif (value === RESPONDENTS_VALUE) {\n\t\t\ttotal += count\n\t\t} else {\n\t\t\tcounts.set(value, (counts.get(value) ?? 0) + count)\n\t\t}\n\t}\n\n\tconst optionValues = new Set(options.map((option) => option.value))\n\tconst leftovers = [...counts.keys()]\n\t\t.filter((value) => !optionValues.has(value))\n\t\t.sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0))\n\tconst labelByValue = new Map(options.map((option) => [option.value, option.label]))\n\n\tconst buckets = [...options.map((option) => option.value), ...leftovers].map((value) => {\n\t\tconst count = counts.get(value) ?? 0\n\t\treturn {\n\t\t\tvalue,\n\t\t\tlabel: labelByValue.get(value) ?? value,\n\t\t\tcount,\n\t\t\tpercentage: total > 0 ? round1((count / total) * 100) : 0,\n\t\t}\n\t})\n\n\treturn {\n\t\tfield,\n\t\tlabel: meta?.label,\n\t\tfieldType: meta?.fieldType,\n\t\ttotal,\n\t\tbuckets,\n\t\ttruncated: false,\n\t}\n}\n"],"mappings":";;AAMA,MAAM,UAAU,MAAsB,KAAK,MAAM,IAAI,EAAE,IAAI;;;;;;;AAQ3D,MAAa,qBAAqB,OAAO,SAOR;CAChC,MAAM,EAAE,SAAS,QAAQ,OAAO,MAAM,SAAS,QAAQ;CACvD,MAAM,EAAE,SAAS,MAAM,QAAQ,KAAK;EACnC,YAAY;EACZ,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,MAAM,EAAE,CAAC,EAAE;EACnF,OAAO;EACP,YAAY;EACZ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC;CAED,MAAM,yBAAS,IAAI,IAAoB;CACvC,IAAI,QAAQ;CACZ,KAAK,MAAM,OAAO,MAAmB;EACpC,MAAM,QAAQ,IAAI,SAAS,OAAA,KAA2B,OAAO,IAAI,KAAK;EACtE,MAAM,QAAQ,OAAO,IAAI,UAAU,WAAW,IAAI,QAAQ;EAC1D,IAAI,UAAA,IACH,SAAS;OAET,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,KAAK;CAEpD;CAEA,MAAM,eAAe,IAAI,IAAI,QAAQ,KAAK,WAAW,OAAO,KAAK,CAAC;CAClE,MAAM,YAAY,CAAC,GAAG,OAAO,KAAK,CAAC,EACjC,QAAQ,UAAU,CAAC,aAAa,IAAI,KAAK,CAAC,EAC1C,MAAM,GAAG,OAAO,OAAO,IAAI,CAAC,KAAK,MAAM,OAAO,IAAI,CAAC,KAAK,EAAE;CAC5D,MAAM,eAAe,IAAI,IAAI,QAAQ,KAAK,WAAW,CAAC,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC;CAElF,MAAM,UAAU,CAAC,GAAG,QAAQ,KAAK,WAAW,OAAO,KAAK,GAAG,GAAG,SAAS,EAAE,KAAK,UAAU;EACvF,MAAM,QAAQ,OAAO,IAAI,KAAK,KAAK;EACnC,OAAO;GACN;GACA,OAAO,aAAa,IAAI,KAAK,KAAK;GAClC;GACA,YAAY,QAAQ,IAAI,OAAQ,QAAQ,QAAS,GAAG,IAAI;EACzD;CACD,CAAC;CAED,OAAO;EACN;EACA,OAAO,MAAM;EACb,WAAW,MAAM;EACjB;EACA;EACA,WAAW;CACZ;AACD"}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { POLL_VOTES_SLUG } from "./votesCollection.js";
|
|
2
|
+
//#region src/poll/votes/bumpPollVote.ts
|
|
3
|
+
const PG_TABLE_KEY = "form_poll_votes";
|
|
4
|
+
/**
|
|
5
|
+
* Atomically bumps one (form, field, value) tally by `by` in a single upsert-increment
|
|
6
|
+
* statement (Mongo `$inc` + upsert, Postgres `INSERT ... ON CONFLICT DO UPDATE`); the unique
|
|
7
|
+
* compound index makes concurrent bumps for the same key safe without read-modify-write races.
|
|
8
|
+
* The shard column is internal: transactional Mongo bumps pick a random shard in
|
|
9
|
+
* [0, VOTE_SHARDS) so concurrent transactions rarely write the same document (see VOTE_SHARDS);
|
|
10
|
+
* Postgres and non-transactional Mongo always bump shard 0. Readers sum across shards.
|
|
11
|
+
*
|
|
12
|
+
* When `transactionID` names an open Payload transaction, the write joins it: a bump failure
|
|
13
|
+
* thrown from the submission hook rolls back the submission create (no undercount), and an
|
|
14
|
+
* aborted create rolls back the joined bump (no overcount). Residual risk on transactional
|
|
15
|
+
* Mongo: two concurrent bumps that land on the same shard still abort one transaction
|
|
16
|
+
* (WriteConflict, labelled TransientTransactionError); the losing submission rolls back whole,
|
|
17
|
+
* so counts stay consistent and the client can safely resubmit. Without a transaction (e.g.
|
|
18
|
+
* Mongo with transactions disabled) the write lands on the root handle immediately; a later
|
|
19
|
+
* recount from stored submissions is the healer for any drift that window allows.
|
|
20
|
+
*/
|
|
21
|
+
async function bumpPollVote(payload, key, by, transactionID) {
|
|
22
|
+
if (payload.db.name === "mongoose") {
|
|
23
|
+
const db = payload.db;
|
|
24
|
+
const model = db.collections[POLL_VOTES_SLUG];
|
|
25
|
+
if (!model) throw new Error(`form-builder: mongoose collection "${POLL_VOTES_SLUG}" not found`);
|
|
26
|
+
const session = transactionID !== void 0 ? db.sessions?.[transactionID] : void 0;
|
|
27
|
+
const shard = session ? Math.floor(Math.random() * 8) : 0;
|
|
28
|
+
const shardedKey = {
|
|
29
|
+
...key,
|
|
30
|
+
shard
|
|
31
|
+
};
|
|
32
|
+
const update = {
|
|
33
|
+
$inc: { count: by },
|
|
34
|
+
$setOnInsert: shardedKey
|
|
35
|
+
};
|
|
36
|
+
const options = session ? {
|
|
37
|
+
upsert: true,
|
|
38
|
+
session
|
|
39
|
+
} : { upsert: true };
|
|
40
|
+
try {
|
|
41
|
+
await model.collection.updateOne(shardedKey, update, options);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
const duplicate = error?.code === 11e3;
|
|
44
|
+
if (session || !duplicate) throw error;
|
|
45
|
+
await model.collection.updateOne(shardedKey, update, options);
|
|
46
|
+
}
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const { sql } = await import("@payloadcms/db-postgres");
|
|
50
|
+
const db = payload.db;
|
|
51
|
+
const tableName = db.tableNameMap.get(PG_TABLE_KEY);
|
|
52
|
+
if (!tableName) throw new Error(`form-builder: drizzle table "${PG_TABLE_KEY}" not found`);
|
|
53
|
+
const table = db.tables[tableName];
|
|
54
|
+
if (!table) throw new Error(`form-builder: drizzle table object for "${tableName}" not found`);
|
|
55
|
+
await ((transactionID !== void 0 ? db.sessions?.[transactionID]?.db : void 0) ?? db.drizzle).insert(table).values({
|
|
56
|
+
...key,
|
|
57
|
+
shard: 0,
|
|
58
|
+
count: by
|
|
59
|
+
}).onConflictDoUpdate({
|
|
60
|
+
target: [
|
|
61
|
+
table.form,
|
|
62
|
+
table.field,
|
|
63
|
+
table.value,
|
|
64
|
+
table.shard
|
|
65
|
+
],
|
|
66
|
+
set: { count: sql`${table.count} + ${by}` }
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
//#endregion
|
|
70
|
+
export { bumpPollVote };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=bumpPollVote.js.map
|