@10x-media/form-builder 0.1.0-beta.8 → 4.0.0-alpha.1
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 +185 -0
- package/README.md +11 -3
- package/dist/actions/assertNoBlockCollision.js +18 -0
- package/dist/actions/assertNoBlockCollision.js.map +1 -0
- package/dist/actions/body/serializeBody.d.ts +16 -14
- package/dist/actions/body/serializeBody.js +5 -8
- package/dist/actions/body/serializeBody.js.map +1 -1
- package/dist/actions/builtin/confirmation.js +2 -1
- package/dist/actions/builtin/confirmation.js.map +1 -1
- package/dist/actions/builtin/emailAction.d.ts +15 -3
- package/dist/actions/builtin/emailAction.js +72 -20
- 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 +37 -6
- package/dist/actions/defineAction.js +14 -1
- package/dist/actions/defineAction.js.map +1 -1
- package/dist/actions/dispatch.d.ts +12 -0
- package/dist/actions/dispatch.js +103 -30
- package/dist/actions/dispatch.js.map +1 -1
- package/dist/actions/dispatchContext.js +19 -0
- package/dist/actions/dispatchContext.js.map +1 -0
- package/dist/actions/emailRecipients.js +38 -8
- package/dist/actions/emailRecipients.js.map +1 -1
- package/dist/actions/emailRender.d.ts +27 -0
- package/dist/actions/fromAddresses.d.ts +19 -1
- package/dist/actions/fromAddresses.js +66 -9
- package/dist/actions/fromAddresses.js.map +1 -1
- package/dist/actions/recipientSources.d.ts +23 -0
- package/dist/actions/recipientSources.js +11 -0
- package/dist/actions/recipientSources.js.map +1 -0
- package/dist/actions/registry.js +3 -1
- package/dist/actions/registry.js.map +1 -1
- package/dist/actions/runActions.d.ts +2 -0
- package/dist/actions/runActions.js +13 -8
- package/dist/actions/runActions.js.map +1 -1
- package/dist/actions/sign.js.map +1 -1
- package/dist/actions/submissionContext.d.ts +34 -0
- package/dist/actions/task.js +43 -16
- package/dist/actions/task.js.map +1 -1
- package/dist/aggregation/aggregateResponses.js +3 -4
- package/dist/aggregation/aggregateResponses.js.map +1 -1
- package/dist/aggregation/resolveResultsRequest.d.ts +6 -0
- package/dist/aggregation/resolveResultsRequest.js +69 -26
- 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 +19 -4
- package/dist/calc/types.js +3 -2
- package/dist/calc/types.js.map +1 -1
- package/dist/client/ByteSizeField.js +11 -8
- package/dist/client/ByteSizeField.js.map +1 -1
- package/dist/client/CalcExpressionBuilder.d.ts +20 -0
- package/dist/client/CalcExpressionBuilder.js +888 -0
- package/dist/client/CalcExpressionBuilder.js.map +1 -0
- package/dist/client/ClosePollButton.js +3 -3
- package/dist/client/ClosePollButton.js.map +1 -1
- package/dist/client/CondensedArray.d.ts +2 -2
- package/dist/client/CondensedArray.js +5 -7
- package/dist/client/CondensedArray.js.map +1 -1
- package/dist/client/ConditionBuilder.js +5 -7
- package/dist/client/ConditionBuilder.js.map +1 -1
- package/dist/client/ConditionRow.js +3 -3
- package/dist/client/ConditionRow.js.map +1 -1
- package/dist/client/ConsentBlockLabel.js +2 -2
- package/dist/client/ConsentBlockLabel.js.map +1 -1
- package/dist/client/ConsentRetentionNotice.d.ts +11 -0
- package/dist/client/ConsentRetentionNotice.js +23 -0
- package/dist/client/ConsentRetentionNotice.js.map +1 -0
- package/dist/client/EndpointOptionsSelect.d.ts +17 -7
- package/dist/client/EndpointOptionsSelect.js +18 -14
- package/dist/client/EndpointOptionsSelect.js.map +1 -1
- package/dist/client/FieldBlockLabel.js +2 -2
- package/dist/client/FieldBlockLabel.js.map +1 -1
- package/dist/client/FieldNameSelect.d.ts +1 -0
- package/dist/client/FieldNameSelect.js +2 -4
- package/dist/client/FieldNameSelect.js.map +1 -1
- package/dist/client/FlowBuilder.js +31 -23
- package/dist/client/FlowBuilder.js.map +1 -1
- package/dist/client/FormConditionField.js +0 -1
- package/dist/client/FormConditionField.js.map +1 -1
- package/dist/client/RecipientsSelect.d.ts +9 -2
- package/dist/client/RecipientsSelect.js +31 -10
- package/dist/client/RecipientsSelect.js.map +1 -1
- package/dist/client/admin.css +345 -72
- package/dist/client/endpointOptions.d.ts +11 -0
- package/dist/client/endpointOptions.js +17 -8
- package/dist/client/endpointOptions.js.map +1 -1
- package/dist/collections/formSubmissions.js +145 -51
- package/dist/collections/formSubmissions.js.map +1 -1
- package/dist/collections/forms.js +170 -65
- package/dist/collections/forms.js.map +1 -1
- package/dist/collections/formsEndpoints.js +31 -26
- package/dist/collections/formsEndpoints.js.map +1 -1
- package/dist/collections/settingsFields.d.ts +32 -0
- package/dist/collections/settingsFields.js +55 -0
- package/dist/collections/settingsFields.js.map +1 -0
- package/dist/consent/captureConsent.d.ts +2 -1
- package/dist/consent/captureConsent.js +4 -1
- package/dist/consent/captureConsent.js.map +1 -1
- package/dist/consent/consentSourcesField.d.ts +7 -1
- package/dist/consent/consentSourcesField.js +15 -1
- package/dist/consent/consentSourcesField.js.map +1 -1
- package/dist/consent/effectiveStatement.js +16 -0
- package/dist/consent/effectiveStatement.js.map +1 -0
- package/dist/consent/resolveConsentSourcesRequest.js +2 -2
- package/dist/consent/resolveConsentSourcesRequest.js.map +1 -1
- package/dist/consent/resolveConsentStatements.js +3 -1
- package/dist/consent/resolveConsentStatements.js.map +1 -1
- package/dist/consent/resolvePublishedVersionRef.js +1 -0
- package/dist/consent/resolvePublishedVersionRef.js.map +1 -1
- package/dist/consent/types.d.ts +8 -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/email/departmentsField.d.ts +6 -1
- package/dist/email/departmentsField.js +6 -1
- package/dist/email/departmentsField.js.map +1 -1
- package/dist/exports/client.d.ts +3 -1
- package/dist/exports/client.js +3 -1
- package/dist/exports/i18n.d.ts +14 -2
- package/dist/exports/i18n.js +14 -2
- package/dist/exports/react.d.ts +23 -5
- package/dist/exports/react.js +17 -1
- package/dist/exports/rsc.d.ts +4 -1
- package/dist/exports/rsc.js +7 -4
- package/dist/exports/types.d.ts +4 -3
- 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 +70 -127
- 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/consent.js +21 -1
- package/dist/fields/builtin/consent.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/findFormAtLocale.d.ts +30 -0
- package/dist/form/findFormAtLocale.js +88 -0
- package/dist/form/findFormAtLocale.js.map +1 -0
- package/dist/form/pollState.d.ts +2 -1
- package/dist/form/pollState.js.map +1 -1
- package/dist/form/toFormDocument.d.ts +8 -0
- package/dist/form/toFormDocument.js +3 -1
- package/dist/form/toFormDocument.js.map +1 -1
- package/dist/form/types.d.ts +9 -1
- package/dist/index.d.ts +22 -6
- package/dist/index.js +63 -17
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +113 -4
- package/dist/plugin/collectionSlugs.d.ts +28 -0
- package/dist/plugin/collectionSlugs.js +65 -0
- package/dist/plugin/collectionSlugs.js.map +1 -0
- package/dist/plugin/customState.js +1 -1
- package/dist/plugin/customState.js.map +1 -1
- package/dist/plugin/registerCollections.js +38 -21
- package/dist/plugin/registerCollections.js.map +1 -1
- package/dist/poll/closeJob.d.ts +4 -3
- package/dist/poll/closeJob.js +13 -10
- package/dist/poll/closeJob.js.map +1 -1
- package/dist/poll/outcomeBeforeChange.js +2 -2
- package/dist/poll/outcomeBeforeChange.js.map +1 -1
- package/dist/poll/pollTypeRegistry.js +1 -1
- package/dist/poll/resolvePollCloseRequest.js +5 -4
- package/dist/poll/resolvePollCloseRequest.js.map +1 -1
- package/dist/poll/resolvePollOptionsRequest.js +2 -2
- package/dist/poll/resolvePollOptionsRequest.js.map +1 -1
- package/dist/poll/resolvePollOutcome.d.ts +6 -0
- package/dist/poll/resolvePollOutcome.js +20 -6
- package/dist/poll/resolvePollOutcome.js.map +1 -1
- package/dist/poll/votes/aggregateFromVotes.d.ts +27 -0
- package/dist/poll/votes/aggregateFromVotes.js +55 -0
- package/dist/poll/votes/aggregateFromVotes.js.map +1 -0
- package/dist/poll/votes/answerValues.js +16 -0
- package/dist/poll/votes/answerValues.js.map +1 -0
- package/dist/poll/votes/bumpPollVote.js +91 -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 +76 -0
- package/dist/poll/votes/voteTallyHook.js.map +1 -0
- package/dist/poll/votes/votesCollection.d.ts +23 -0
- package/dist/poll/votes/votesCollection.js +96 -0
- package/dist/poll/votes/votesCollection.js.map +1 -0
- package/dist/react/Form.d.ts +49 -7
- package/dist/react/Form.js +183 -37
- package/dist/react/Form.js.map +1 -1
- package/dist/react/FormContext.d.ts +10 -2
- package/dist/react/FormContext.js.map +1 -1
- package/dist/react/FormResults.d.ts +4 -2
- package/dist/react/FormResults.js +21 -8
- package/dist/react/FormResults.js.map +1 -1
- package/dist/react/Poll.d.ts +25 -2
- package/dist/react/Poll.js +76 -25
- package/dist/react/Poll.js.map +1 -1
- package/dist/react/adapters.d.ts +35 -0
- package/dist/react/adapters.js +11 -0
- package/dist/react/adapters.js.map +1 -0
- package/dist/react/captcha/HcaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/HcaptchaCaptcha.js +2 -2
- package/dist/react/captcha/HcaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/RecaptchaCaptcha.d.ts +4 -1
- package/dist/react/captcha/RecaptchaCaptcha.js +2 -2
- package/dist/react/captcha/RecaptchaCaptcha.js.map +1 -1
- package/dist/react/captcha/TurnstileCaptcha.d.ts +4 -1
- package/dist/react/captcha/TurnstileCaptcha.js +2 -2
- package/dist/react/captcha/TurnstileCaptcha.js.map +1 -1
- package/dist/react/captcha/useCaptchaScript.js +23 -5
- package/dist/react/captcha/useCaptchaScript.js.map +1 -1
- package/dist/react/fetchResults.d.ts +6 -3
- package/dist/react/fetchResults.js +10 -5
- package/dist/react/fetchResults.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/consent.js +8 -3
- package/dist/react/renderers/consent.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/repeater.js +5 -0
- package/dist/react/renderers/repeater.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/state.d.ts +20 -1
- package/dist/react/state.js +57 -4
- package/dist/react/state.js.map +1 -1
- package/dist/react/submitForm.d.ts +20 -3
- package/dist/react/submitForm.js +8 -4
- package/dist/react/submitForm.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/react/useField.js +7 -5
- package/dist/react/useField.js.map +1 -1
- 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/spam/spamGuard.js +2 -1
- package/dist/spam/spamGuard.js.map +1 -1
- package/dist/submissions/SubmissionAnswersClient.js +14 -14
- package/dist/submissions/SubmissionAnswersClient.js.map +1 -1
- package/dist/submissions/createSubmission.d.ts +7 -1
- package/dist/submissions/createSubmission.js +10 -5
- package/dist/submissions/createSubmission.js.map +1 -1
- package/dist/submissions/formIdOf.js +13 -0
- package/dist/submissions/formIdOf.js.map +1 -0
- package/dist/submissions/resolveVotedSubmission.d.ts +27 -0
- package/dist/submissions/resolveVotedSubmission.js +51 -0
- package/dist/submissions/resolveVotedSubmission.js.map +1 -0
- package/dist/submissions/runSubmission.js +6 -5
- package/dist/submissions/runSubmission.js.map +1 -1
- package/dist/submissions/submissionLocale.js +39 -0
- package/dist/submissions/submissionLocale.js.map +1 -0
- package/dist/submissions/validateSubmission.js +125 -79
- 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/submissions/voteChange.js +21 -0
- package/dist/submissions/voteChange.js.map +1 -0
- package/dist/submissions/voteChangeEndpoint.js +110 -0
- package/dist/submissions/voteChangeEndpoint.js.map +1 -0
- package/dist/submissions/votedCookie.d.ts +10 -4
- package/dist/submissions/votedCookie.js +49 -11
- package/dist/submissions/votedCookie.js.map +1 -1
- package/dist/translations/ar.d.ts +7 -0
- package/dist/translations/ar.js +379 -0
- package/dist/translations/ar.js.map +1 -0
- package/dist/translations/clientRuntimeKeys.d.ts +17 -0
- package/dist/translations/clientRuntimeKeys.js +48 -0
- package/dist/translations/clientRuntimeKeys.js.map +1 -0
- package/dist/translations/de.d.ts +12 -0
- package/dist/translations/de.js +80 -3
- package/dist/translations/de.js.map +1 -1
- package/dist/translations/en.js +80 -3
- package/dist/translations/en.js.map +1 -1
- package/dist/translations/es.d.ts +7 -0
- package/dist/translations/es.js +379 -0
- package/dist/translations/es.js.map +1 -0
- package/dist/translations/fr.d.ts +7 -0
- package/dist/translations/fr.js +379 -0
- package/dist/translations/fr.js.map +1 -0
- package/dist/translations/id.d.ts +7 -0
- package/dist/translations/id.js +379 -0
- package/dist/translations/id.js.map +1 -0
- package/dist/translations/index.d.ts +23 -6
- package/dist/translations/index.js +31 -6
- package/dist/translations/index.js.map +1 -1
- package/dist/translations/keys.d.ts +78 -1
- package/dist/translations/keys.js +78 -1
- package/dist/translations/keys.js.map +1 -1
- package/dist/translations/ko.d.ts +7 -0
- package/dist/translations/ko.js +379 -0
- package/dist/translations/ko.js.map +1 -0
- package/dist/translations/makeTranslate.d.ts +7 -3
- package/dist/translations/makeTranslate.js +12 -3
- package/dist/translations/makeTranslate.js.map +1 -1
- package/dist/translations/pt.d.ts +7 -0
- package/dist/translations/pt.js +379 -0
- package/dist/translations/pt.js.map +1 -0
- package/dist/translations/ru.d.ts +7 -0
- package/dist/translations/ru.js +379 -0
- package/dist/translations/ru.js.map +1 -0
- package/dist/translations/uk.d.ts +7 -0
- package/dist/translations/uk.js +379 -0
- package/dist/translations/uk.js.map +1 -0
- package/dist/translations/zh.d.ts +7 -0
- package/dist/translations/zh.js +379 -0
- package/dist/translations/zh.js.map +1 -0
- 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/dist/validation/builtin/notAlreadySubmitted.js +5 -3
- package/dist/validation/builtin/notAlreadySubmitted.js.map +1 -1
- package/package.json +23 -15
- package/styles/form-builder.css +84 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outcomeBeforeChange.js","names":[],"sources":["../../src/poll/outcomeBeforeChange.ts"],"sourcesContent":["import { type CollectionBeforeChangeHook, ValidationError } from 'payload'\nimport {
|
|
1
|
+
{"version":3,"file":"outcomeBeforeChange.js","names":[],"sources":["../../src/poll/outcomeBeforeChange.ts"],"sourcesContent":["import { type CollectionBeforeChangeHook, ValidationError } from 'payload'\nimport { pollConfigOf } from '../form/pollState'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\nimport { keys } from '../translations/keys'\nimport { asTranslate } from '../translations/server'\nimport type { PollOption } from './definePollOptionSource'\nimport { resolveEffectivePollOptions } from './effectivePollOptions'\n\nconst WINNING_VALUES_PATH = 'poll.outcome.winningValues'\n\n/** The winning set as a deduped array of non-empty strings, ready to store and to compare. */\nconst normalizeWinning = (value: unknown): string[] => {\n\tif (!Array.isArray(value)) {\n\t\treturn []\n\t}\n\tconst seen = new Set<string>()\n\tfor (const entry of value) {\n\t\tif (typeof entry === 'string' && entry.length > 0) {\n\t\t\tseen.add(entry)\n\t\t}\n\t}\n\treturn [...seen]\n}\n\n/** Set equality on two already-deduped winner arrays: order-insensitive membership. */\nconst sameWinners = (a: string[], b: string[]): boolean => {\n\tif (a.length !== b.length) {\n\t\treturn false\n\t}\n\tconst set = new Set(a)\n\treturn b.every((value) => set.has(value))\n}\n\n/**\n * Owns the poll outcome lifecycle for every create and update, admin and API alike. When the save\n * writes `poll.outcome.winningValues` it validates a set or changed winner set against the poll's\n * effective options (source-resolved or authored, over a merged view of the doc so partial updates\n * validate against stored config) and requires the poll to be enabled; clearing is always allowed.\n * A tie is a set with more than one winner; every value must be a member of the effective options.\n *\n * It is also the single `resolvedAt` stamping point: stamped when the winner set is set or changed,\n * cleared with the set, untouched when the set is unchanged (order-insensitive). Callers can never\n * write `resolvedAt` themselves (field-level access strips it during the beforeValidate traversal,\n * before this hook runs), while values this hook sets survive to the database, so the stamp always\n * reflects the actual transition regardless of the write path.\n */\nexport const pollOutcomeBeforeChange: CollectionBeforeChangeHook = async ({\n\tdata,\n\toriginalDoc,\n\treq,\n}) => {\n\tconst incomingPoll =\n\t\tdata?.poll != null && typeof data.poll === 'object'\n\t\t\t? (data.poll as Record<string, unknown>)\n\t\t\t: undefined\n\tconst outcome =\n\t\tincomingPoll?.outcome != null && typeof incomingPoll.outcome === 'object'\n\t\t\t? (incomingPoll.outcome as Record<string, unknown>)\n\t\t\t: undefined\n\tif (!outcome || !('winningValues' in outcome)) {\n\t\treturn data\n\t}\n\tconst next = normalizeWinning(outcome.winningValues)\n\toutcome.winningValues = next\n\tconst previous = normalizeWinning(pollConfigOf(originalDoc?.poll)?.outcome?.winningValues)\n\tif (sameWinners(next, previous)) {\n\t\treturn data\n\t}\n\tif (next.length === 0) {\n\t\toutcome.resolvedAt = null\n\t\treturn data\n\t}\n\n\tconst t = asTranslate(req.t)\n\tconst fail = (message: string): never => {\n\t\tthrow new ValidationError(\n\t\t\t{\n\t\t\t\tcollection: pluginSlugsOf(req.payload).forms,\n\t\t\t\terrors: [{ path: WINNING_VALUES_PATH, message }],\n\t\t\t},\n\t\t\treq.t\n\t\t)\n\t}\n\tconst originalPoll =\n\t\toriginalDoc?.poll != null && typeof originalDoc.poll === 'object'\n\t\t\t? (originalDoc.poll as Record<string, unknown>)\n\t\t\t: undefined\n\tconst mergedPoll = { ...(originalPoll ?? {}), ...incomingPoll }\n\t// The poll-enable flag lives at the document root now; merge the incoming partial over the stored\n\t// doc so a partial update that omits it still validates against the persisted value.\n\tconst mergedPollEnabled = { ...(originalDoc ?? {}), ...data }.pollEnabled === true\n\tif (!mergedPollEnabled) {\n\t\tfail(t(keys.validationWinningValueDisabled))\n\t}\n\tconst id = (originalDoc?.id ?? data?.id) as number | string | undefined\n\tconst form = {\n\t\tid: id ?? '',\n\t\ttitle:\n\t\t\ttypeof data?.title === 'string' ? data.title : (originalDoc?.title as string | undefined),\n\t\tpollEnabled: mergedPollEnabled,\n\t\tpoll: mergedPoll,\n\t\tfields: data?.fields ?? originalDoc?.fields,\n\t}\n\tlet options: PollOption[]\n\ttry {\n\t\t// Without a doc id (create) the per-request options cache would key on '', so skip it.\n\t\toptions = await resolveEffectivePollOptions({\n\t\t\tpayload: req.payload,\n\t\t\treq: id != null ? req : undefined,\n\t\t\tform,\n\t\t})\n\t} catch {\n\t\treturn fail(t(keys.pollOptionsUnavailable))\n\t}\n\tconst allowed = new Set(options.map((option) => option.value))\n\tif (!next.every((value) => allowed.has(value))) {\n\t\tfail(t(keys.validationWinningValueUnknown))\n\t}\n\toutcome.resolvedAt = new Date().toISOString()\n\treturn data\n}\n"],"mappings":";;;;;;;AAQA,MAAM,sBAAsB;;AAG5B,MAAM,oBAAoB,UAA6B;CACtD,IAAI,CAAC,MAAM,QAAQ,KAAK,GACvB,OAAO,CAAC;CAET,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,SAAS,OACnB,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,GAC/C,KAAK,IAAI,KAAK;CAGhB,OAAO,CAAC,GAAG,IAAI;AAChB;;AAGA,MAAM,eAAe,GAAa,MAAyB;CAC1D,IAAI,EAAE,WAAW,EAAE,QAClB,OAAO;CAER,MAAM,MAAM,IAAI,IAAI,CAAC;CACrB,OAAO,EAAE,OAAO,UAAU,IAAI,IAAI,KAAK,CAAC;AACzC;;;;;;;;;;;;;;AAeA,MAAa,0BAAsD,OAAO,EACzE,MACA,aACA,UACK;CACL,MAAM,eACL,MAAM,QAAQ,QAAQ,OAAO,KAAK,SAAS,WACvC,KAAK,OACN,KAAA;CACJ,MAAM,UACL,cAAc,WAAW,QAAQ,OAAO,aAAa,YAAY,WAC7D,aAAa,UACd,KAAA;CACJ,IAAI,CAAC,WAAW,EAAE,mBAAmB,UACpC,OAAO;CAER,MAAM,OAAO,iBAAiB,QAAQ,aAAa;CACnD,QAAQ,gBAAgB;CAExB,IAAI,YAAY,MADC,iBAAiB,aAAa,aAAa,IAAI,GAAG,SAAS,aAC/C,CAAC,GAC7B,OAAO;CAER,IAAI,KAAK,WAAW,GAAG;EACtB,QAAQ,aAAa;EACrB,OAAO;CACR;CAEA,MAAM,IAAI,YAAY,IAAI,CAAC;CAC3B,MAAM,QAAQ,YAA2B;EACxC,MAAM,IAAI,gBACT;GACC,YAAY,cAAc,IAAI,OAAO,EAAE;GACvC,QAAQ,CAAC;IAAE,MAAM;IAAqB;GAAQ,CAAC;EAChD,GACA,IAAI,CACL;CACD;CAKA,MAAM,aAAa;EAAE,IAHpB,aAAa,QAAQ,QAAQ,OAAO,YAAY,SAAS,WACrD,YAAY,OACb,KAAA,MACqC,CAAC;EAAI,GAAG;CAAa;CAG9D,MAAM,oBAAoB;EAAE,GAAI,eAAe,CAAC;EAAI,GAAG;CAAK,EAAE,gBAAgB;CAC9E,IAAI,CAAC,mBACJ,KAAK,EAAE,KAAK,8BAA8B,CAAC;CAE5C,MAAM,KAAM,aAAa,MAAM,MAAM;CACrC,MAAM,OAAO;EACZ,IAAI,MAAM;EACV,OACC,OAAO,MAAM,UAAU,WAAW,KAAK,QAAS,aAAa;EAC9D,aAAa;EACb,MAAM;EACN,QAAQ,MAAM,UAAU,aAAa;CACtC;CACA,IAAI;CACJ,IAAI;EAEH,UAAU,MAAM,4BAA4B;GAC3C,SAAS,IAAI;GACb,KAAK,MAAM,OAAO,MAAM,KAAA;GACxB;EACD,CAAC;CACF,QAAQ;EACP,OAAO,KAAK,EAAE,KAAK,sBAAsB,CAAC;CAC3C;CACA,MAAM,UAAU,IAAI,IAAI,QAAQ,KAAK,WAAW,OAAO,KAAK,CAAC;CAC7D,IAAI,CAAC,KAAK,OAAO,UAAU,QAAQ,IAAI,KAAK,CAAC,GAC5C,KAAK,EAAE,KAAK,6BAA6B,CAAC;CAE3C,QAAQ,8BAAa,IAAI,KAAK,GAAE,YAAY;CAC5C,OAAO;AACR"}
|
|
@@ -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({
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { keys } from "../translations/keys.js";
|
|
2
2
|
import { asTranslate } from "../translations/server.js";
|
|
3
|
+
import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
|
|
3
4
|
import { isPollClosed, pollConfigOf } from "../form/pollState.js";
|
|
4
5
|
import { resolvePollOutcome } from "./resolvePollOutcome.js";
|
|
5
|
-
import { FORMS_SLUG } from "../collections/forms.js";
|
|
6
6
|
//#region src/poll/resolvePollCloseRequest.ts
|
|
7
7
|
/** The recorded winning set as non-empty strings; empty means no winner has been set yet. */
|
|
8
8
|
const winnersOf = (poll) => {
|
|
@@ -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" }] }
|
|
@@ -57,7 +57,7 @@ const resolvePollCloseRequest = async (args) => {
|
|
|
57
57
|
body: { errors: [{ message: "Missing form id" }] }
|
|
58
58
|
};
|
|
59
59
|
const form = await payload.findByID({
|
|
60
|
-
collection:
|
|
60
|
+
collection: pluginSlugsOf(payload).forms,
|
|
61
61
|
id: formId,
|
|
62
62
|
depth: 0,
|
|
63
63
|
overrideAccess: true,
|
|
@@ -80,7 +80,7 @@ const resolvePollCloseRequest = async (args) => {
|
|
|
80
80
|
}
|
|
81
81
|
const closesAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
82
82
|
await payload.update({
|
|
83
|
-
collection:
|
|
83
|
+
collection: pluginSlugsOf(payload).forms,
|
|
84
84
|
id: formId,
|
|
85
85
|
data: { poll: { closesAt } },
|
|
86
86
|
depth: 0,
|
|
@@ -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 {
|
|
1
|
+
{"version":3,"file":"resolvePollCloseRequest.js","names":[],"sources":["../../src/poll/resolvePollCloseRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { isPollClosed, type PollConfigLike, pollConfigOf } from '../form/pollState'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\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({\n\t\t\tcollection: pluginSlugsOf(payload).forms,\n\t\t\tid: formId,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\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: pluginSlugsOf(payload).forms,\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;EACT,YAAY,cAAc,OAAO,EAAE;EACnC,IAAI;EACJ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC,EACA,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,cAAc,OAAO,EAAE;EACnC,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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
|
|
1
2
|
import { resolveEffectivePollOptions } from "./effectivePollOptions.js";
|
|
2
|
-
import { FORMS_SLUG } from "../collections/forms.js";
|
|
3
3
|
//#region src/poll/resolvePollOptionsRequest.ts
|
|
4
4
|
/**
|
|
5
5
|
* Authorize and resolve the `GET /:id/poll-options` request backing the admin winner select:
|
|
@@ -19,7 +19,7 @@ const resolvePollOptionsRequest = async (args) => {
|
|
|
19
19
|
body: { errors: [{ message: "Missing form id" }] }
|
|
20
20
|
};
|
|
21
21
|
const form = await payload.findByID({
|
|
22
|
-
collection:
|
|
22
|
+
collection: pluginSlugsOf(payload).forms,
|
|
23
23
|
id: formId,
|
|
24
24
|
depth: 0,
|
|
25
25
|
req
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolvePollOptionsRequest.js","names":[],"sources":["../../src/poll/resolvePollOptionsRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport {
|
|
1
|
+
{"version":3,"file":"resolvePollOptionsRequest.js","names":[],"sources":["../../src/poll/resolvePollOptionsRequest.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\nimport type { PollOption } from './definePollOptionSource'\nimport { resolveEffectivePollOptions } from './effectivePollOptions'\n\nexport type ResolvePollOptionsRequestArgs = {\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 ResolvePollOptionsRequestResult = {\n\tstatus: number\n\tbody: { options: PollOption[] } | { errors: { message: string }[] }\n}\n\n/**\n * Authorize and resolve the `GET /:id/poll-options` request backing the admin winner select:\n * authenticated callers get the poll's effective options (source-resolved or authored, exactly the\n * set outcome validation accepts), anonymous callers are always refused. Statuses mirror the\n * results endpoint: 400 missing id, 403 unauthenticated, 404 unknown form, 503 when the option\n * source fails (fail closed).\n */\nexport const resolvePollOptionsRequest = async (\n\targs: ResolvePollOptionsRequestArgs\n): Promise<ResolvePollOptionsRequestResult> => {\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\t// Load under the caller's own read access (no overrideAccess): a tenant-scoped `forms.access.read`\n\t// then refuses a cross-tenant form id (null -> 404), so an authed user cannot read another tenant's\n\t// poll options.\n\tconst form = await payload\n\t\t.findByID({ collection: pluginSlugsOf(payload).forms, id: formId, depth: 0, req })\n\t\t.catch(() => null)\n\tif (!form) {\n\t\treturn { status: 404, body: { errors: [{ message: 'Not found' }] } }\n\t}\n\ttry {\n\t\tconst options = await resolveEffectivePollOptions({ payload, req, form })\n\t\treturn { status: 200, body: { options } }\n\t} catch {\n\t\treturn { status: 503, body: { errors: [{ message: 'Poll options unavailable' }] } }\n\t}\n}\n"],"mappings":";;;;;;;;;;AAyBA,MAAa,4BAA4B,OACxC,SAC8C;CAC9C,MAAM,EAAE,SAAS,QAAQ,UAAU,QAAQ;CAC3C,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;CAK1E,MAAM,OAAO,MAAM,QACjB,SAAS;EAAE,YAAY,cAAc,OAAO,EAAE;EAAO,IAAI;EAAQ,OAAO;EAAG;CAAI,CAAC,EAChF,YAAY,IAAI;CAClB,IAAI,CAAC,MACJ,OAAO;EAAE,QAAQ;EAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,YAAY,CAAC,EAAE;CAAE;CAEpE,IAAI;EAEH,OAAO;GAAE,QAAQ;GAAK,MAAM,EAAE,SAAA,MADR,4BAA4B;IAAE;IAAS;IAAK;GAAK,CAAC,EAClC;EAAE;CACzC,QAAQ;EACP,OAAO;GAAE,QAAQ;GAAK,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,2BAA2B,CAAC,EAAE;EAAE;CACnF;AACD"}
|
|
@@ -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,7 +1,9 @@
|
|
|
1
|
+
import { pluginSlugsOf } from "../plugin/collectionSlugs.js";
|
|
1
2
|
import { pollConfigOf } from "../form/pollState.js";
|
|
3
|
+
import { resolveEffectivePollOptions } from "./effectivePollOptions.js";
|
|
2
4
|
import { aggregateFieldResponses } from "../aggregation/aggregateResponses.js";
|
|
3
5
|
import { pollTypesOf } from "./pollTypeRegistry.js";
|
|
4
|
-
import {
|
|
6
|
+
import { aggregateFromVotes } from "./votes/aggregateFromVotes.js";
|
|
5
7
|
//#region src/poll/resolvePollOutcome.ts
|
|
6
8
|
/** A strategy result narrowed to a deduped set of non-empty strings. */
|
|
7
9
|
const cleanWinners = (value) => value === void 0 ? [] : [...new Set(value.filter((entry) => typeof entry === "string" && entry.length > 0))];
|
|
@@ -22,9 +24,9 @@ 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
|
-
collection:
|
|
29
|
+
collection: pluginSlugsOf(payload).forms,
|
|
28
30
|
id: formId,
|
|
29
31
|
depth: 0,
|
|
30
32
|
overrideAccess: true,
|
|
@@ -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
|
};
|
|
@@ -61,7 +75,7 @@ const resolvePollOutcome = async (args) => {
|
|
|
61
75
|
if (winningValues.length === 0) return [];
|
|
62
76
|
}
|
|
63
77
|
await payload.update({
|
|
64
|
-
collection:
|
|
78
|
+
collection: pluginSlugsOf(payload).forms,
|
|
65
79
|
id: formId,
|
|
66
80
|
data: { poll: { outcome: { winningValues } } },
|
|
67
81
|
depth: 0,
|
|
@@ -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 {
|
|
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 { pollConfigOf } from '../form/pollState'\nimport { pluginSlugsOf } from '../plugin/collectionSlugs'\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: pluginSlugsOf(payload).forms,\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: pluginSlugsOf(payload).forms,\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,cAAc,OAAO,EAAE;EACnC,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,cAAc,OAAO,EAAE;EACnC,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,55 @@
|
|
|
1
|
+
import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
|
|
2
|
+
import "./votesCollection.js";
|
|
3
|
+
//#region src/poll/votes/aggregateFromVotes.ts
|
|
4
|
+
const round1 = (n) => Math.round(n * 10) / 10;
|
|
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
|
+
const aggregateFromVotes = async (args) => {
|
|
12
|
+
const { payload, formId, field, meta, options, req } = args;
|
|
13
|
+
const { docs } = await payload.find({
|
|
14
|
+
collection: pluginSlugsOf(payload).pollVotes,
|
|
15
|
+
where: { and: [{ form: { equals: String(formId) } }, { field: { equals: field } }] },
|
|
16
|
+
limit: 1e5,
|
|
17
|
+
pagination: false,
|
|
18
|
+
depth: 0,
|
|
19
|
+
overrideAccess: true,
|
|
20
|
+
req
|
|
21
|
+
});
|
|
22
|
+
const counts = /* @__PURE__ */ new Map();
|
|
23
|
+
let total = 0;
|
|
24
|
+
for (const doc of docs) {
|
|
25
|
+
const value = doc.value == null ? "" : String(doc.value);
|
|
26
|
+
const count = typeof doc.count === "number" ? doc.count : 0;
|
|
27
|
+
if (value === "") total += count;
|
|
28
|
+
else counts.set(value, (counts.get(value) ?? 0) + count);
|
|
29
|
+
}
|
|
30
|
+
total = Math.max(0, total);
|
|
31
|
+
const optionValues = new Set(options.map((option) => option.value));
|
|
32
|
+
const leftovers = [...counts.keys()].filter((value) => !optionValues.has(value)).sort((a, b) => (counts.get(b) ?? 0) - (counts.get(a) ?? 0));
|
|
33
|
+
const labelByValue = new Map(options.map((option) => [option.value, option.label]));
|
|
34
|
+
const buckets = [...options.map((option) => option.value), ...leftovers].map((value) => {
|
|
35
|
+
const count = Math.max(0, counts.get(value) ?? 0);
|
|
36
|
+
return {
|
|
37
|
+
value,
|
|
38
|
+
label: labelByValue.get(value) ?? value,
|
|
39
|
+
count,
|
|
40
|
+
percentage: total > 0 ? round1(count / total * 100) : 0
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
return {
|
|
44
|
+
field,
|
|
45
|
+
label: meta?.label,
|
|
46
|
+
fieldType: meta?.fieldType,
|
|
47
|
+
total,
|
|
48
|
+
buckets,
|
|
49
|
+
truncated: false
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
export { aggregateFromVotes };
|
|
54
|
+
|
|
55
|
+
//# 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 { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { 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: pluginSlugsOf(payload).pollVotes,\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\t// Clamp at read: a concurrent double-change can transiently double-decrement one value (see\n\t// the tally hook's drift note), and a negative bucket count must never surface to a reader.\n\ttotal = Math.max(0, total)\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 = Math.max(0, 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":";;;AAOA,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,cAAc,OAAO,EAAE;EACnC,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;CAIA,QAAQ,KAAK,IAAI,GAAG,KAAK;CAEzB,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,KAAK,IAAI,GAAG,OAAO,IAAI,KAAK,KAAK,CAAC;EAChD,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,16 @@
|
|
|
1
|
+
//#region src/poll/votes/answerValues.ts
|
|
2
|
+
/**
|
|
3
|
+
* A submission's answer(s) for one field as normalized non-empty strings: the shape both the vote
|
|
4
|
+
* tally and the voted-pick resolver count by (a multi-select answer contributes one entry per
|
|
5
|
+
* selected value).
|
|
6
|
+
*/
|
|
7
|
+
const answerValues = (values, field) => {
|
|
8
|
+
if (!Array.isArray(values)) return [];
|
|
9
|
+
const entry = values.find((row) => row.field === field);
|
|
10
|
+
if (entry == null) return [];
|
|
11
|
+
return (Array.isArray(entry.value) ? entry.value : [entry.value]).filter((value) => value != null && value !== "").map((value) => String(value));
|
|
12
|
+
};
|
|
13
|
+
//#endregion
|
|
14
|
+
export { answerValues };
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=answerValues.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"answerValues.js","names":[],"sources":["../../../src/poll/votes/answerValues.ts"],"sourcesContent":["import type { SubmissionValue } from '../../submissions/types'\n\n/**\n * A submission's answer(s) for one field as normalized non-empty strings: the shape both the vote\n * tally and the voted-pick resolver count by (a multi-select answer contributes one entry per\n * selected value).\n */\nexport const answerValues = (values: unknown, field: string): string[] => {\n\tif (!Array.isArray(values)) return []\n\tconst entry = (values as SubmissionValue[]).find((row) => row.field === field)\n\tif (entry == null) return []\n\tconst raw = Array.isArray(entry.value) ? entry.value : [entry.value]\n\treturn raw.filter((value) => value != null && value !== '').map((value) => String(value))\n}\n"],"mappings":";;;;;;AAOA,MAAa,gBAAgB,QAAiB,UAA4B;CACzE,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,OAAO,CAAC;CACpC,MAAM,QAAS,OAA6B,MAAM,QAAQ,IAAI,UAAU,KAAK;CAC7E,IAAI,SAAS,MAAM,OAAO,CAAC;CAE3B,QADY,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAC,MAAM,KAAK,GACxD,QAAQ,UAAU,SAAS,QAAQ,UAAU,EAAE,EAAE,KAAK,UAAU,OAAO,KAAK,CAAC;AACzF"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
|
|
2
|
+
import "./votesCollection.js";
|
|
3
|
+
import toSnakeCase from "to-snake-case";
|
|
4
|
+
//#region src/poll/votes/bumpPollVote.ts
|
|
5
|
+
/**
|
|
6
|
+
* Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,
|
|
7
|
+
* Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even
|
|
8
|
+
* though this branch is unreachable there. The function-built specifier is opaque to their
|
|
9
|
+
* analyzers, the ignore comments cover bundlers that would still warn, and the type-only
|
|
10
|
+
* reference above erases at compile time, so the package is touched only when the Postgres
|
|
11
|
+
* branch actually runs.
|
|
12
|
+
*/
|
|
13
|
+
const importPostgresSql = () => {
|
|
14
|
+
return import(
|
|
15
|
+
/* webpackIgnore: true */
|
|
16
|
+
/* turbopackIgnore: true */
|
|
17
|
+
/* @vite-ignore */
|
|
18
|
+
["@payloadcms", "db-postgres"].join("/")
|
|
19
|
+
);
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Atomically bumps one (form, field, value) tally by `by` in a single upsert-increment
|
|
23
|
+
* statement (Mongo `$inc` + upsert, Postgres `INSERT ... ON CONFLICT DO UPDATE`); the unique
|
|
24
|
+
* compound index makes concurrent bumps for the same key safe without read-modify-write races.
|
|
25
|
+
* The shard column is internal: transactional Mongo bumps pick a random shard in
|
|
26
|
+
* [0, VOTE_SHARDS) so concurrent transactions rarely write the same document (see VOTE_SHARDS);
|
|
27
|
+
* Postgres and non-transactional Mongo always bump shard 0. Readers sum across shards.
|
|
28
|
+
*
|
|
29
|
+
* When `transactionID` names an open Payload transaction, the write joins it: a bump failure
|
|
30
|
+
* thrown from the submission hook rolls back the submission create (no undercount), and an
|
|
31
|
+
* aborted create rolls back the joined bump (no overcount). Residual risk on transactional
|
|
32
|
+
* Mongo: two concurrent bumps that land on the same shard still abort one transaction
|
|
33
|
+
* (WriteConflict, labelled TransientTransactionError); the losing submission rolls back whole,
|
|
34
|
+
* so counts stay consistent and the client can safely resubmit. Without a transaction (e.g.
|
|
35
|
+
* Mongo with transactions disabled) the write lands on the root handle immediately; a later
|
|
36
|
+
* recount from stored submissions is the healer for any drift that window allows.
|
|
37
|
+
*/
|
|
38
|
+
async function bumpPollVote(payload, key, by, transactionID) {
|
|
39
|
+
const slug = pluginSlugsOf(payload).pollVotes;
|
|
40
|
+
if (payload.db.name === "mongoose") {
|
|
41
|
+
const db = payload.db;
|
|
42
|
+
const model = db.collections[slug];
|
|
43
|
+
if (!model) throw new Error(`form-builder: mongoose collection "${slug}" not found`);
|
|
44
|
+
const session = transactionID !== void 0 ? db.sessions?.[transactionID] : void 0;
|
|
45
|
+
const shard = session ? Math.floor(Math.random() * 8) : 0;
|
|
46
|
+
const shardedKey = {
|
|
47
|
+
...key,
|
|
48
|
+
shard
|
|
49
|
+
};
|
|
50
|
+
const update = {
|
|
51
|
+
$inc: { count: by },
|
|
52
|
+
$setOnInsert: shardedKey
|
|
53
|
+
};
|
|
54
|
+
const options = session ? {
|
|
55
|
+
upsert: true,
|
|
56
|
+
session
|
|
57
|
+
} : { upsert: true };
|
|
58
|
+
try {
|
|
59
|
+
await model.collection.updateOne(shardedKey, update, options);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
const duplicate = error?.code === 11e3;
|
|
62
|
+
if (session || !duplicate) throw error;
|
|
63
|
+
await model.collection.updateOne(shardedKey, update, options);
|
|
64
|
+
}
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const { sql } = await importPostgresSql();
|
|
68
|
+
const db = payload.db;
|
|
69
|
+
const tableKey = toSnakeCase(slug);
|
|
70
|
+
const tableName = db.tableNameMap.get(tableKey);
|
|
71
|
+
if (!tableName) throw new Error(`form-builder: drizzle table "${tableKey}" not found`);
|
|
72
|
+
const table = db.tables[tableName];
|
|
73
|
+
if (!table) throw new Error(`form-builder: drizzle table object for "${tableName}" not found`);
|
|
74
|
+
await ((transactionID !== void 0 ? db.sessions?.[transactionID]?.db : void 0) ?? db.drizzle).insert(table).values({
|
|
75
|
+
...key,
|
|
76
|
+
shard: 0,
|
|
77
|
+
count: by
|
|
78
|
+
}).onConflictDoUpdate({
|
|
79
|
+
target: [
|
|
80
|
+
table.form,
|
|
81
|
+
table.field,
|
|
82
|
+
table.value,
|
|
83
|
+
table.shard
|
|
84
|
+
],
|
|
85
|
+
set: { count: sql`${table.count} + ${by}` }
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
//#endregion
|
|
89
|
+
export { bumpPollVote };
|
|
90
|
+
|
|
91
|
+
//# sourceMappingURL=bumpPollVote.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bumpPollVote.js","names":[],"sources":["../../../src/poll/votes/bumpPollVote.ts"],"sourcesContent":["import type { Payload } from 'payload'\nimport toSnakeCase from 'to-snake-case'\nimport { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { VOTE_SHARDS } from './votesCollection'\n\ntype PostgresSqlModule = { sql: typeof import('@payloadcms/db-postgres')['sql'] }\n\n/**\n * Loads the optional Postgres peer without a literal specifier: bundlers (Turbopack, webpack,\n * Vite) resolve literal dynamic imports at build time, which fails a Mongo host's build even\n * though this branch is unreachable there. The function-built specifier is opaque to their\n * analyzers, the ignore comments cover bundlers that would still warn, and the type-only\n * reference above erases at compile time, so the package is touched only when the Postgres\n * branch actually runs.\n */\nconst importPostgresSql = (): Promise<PostgresSqlModule> => {\n\tconst specifier = ['@payloadcms', 'db-postgres'].join('/')\n\treturn import(\n\t\t/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier\n\t) as Promise<PostgresSqlModule>\n}\n\n// payload.db raw-access shapes are intentionally loose; these narrow casts reach the\n// Mongoose driver collection / Drizzle instance for atomic upserts (no public typed API).\ntype MongoDb = {\n\tname: 'mongoose'\n\tcollections: Record<\n\t\tstring,\n\t\t{ collection: { updateOne: (f: object, u: object, o: object) => Promise<unknown> } }\n\t>\n\tsessions?: Record<number | string, unknown>\n}\ntype PgInsert = {\n\tinsert: (t: unknown) => {\n\t\tvalues: (v: unknown) => { onConflictDoUpdate: (c: unknown) => Promise<unknown> }\n\t}\n}\ntype PgDb = {\n\tname: 'postgres'\n\tdrizzle: PgInsert\n\tsessions?: Record<number | string, { db: PgInsert }>\n\ttables: Record<string, Record<string, unknown>>\n\ttableNameMap: Map<string, string>\n}\n\n/**\n * Atomically bumps one (form, field, value) tally by `by` in a single upsert-increment\n * statement (Mongo `$inc` + upsert, Postgres `INSERT ... ON CONFLICT DO UPDATE`); the unique\n * compound index makes concurrent bumps for the same key safe without read-modify-write races.\n * The shard column is internal: transactional Mongo bumps pick a random shard in\n * [0, VOTE_SHARDS) so concurrent transactions rarely write the same document (see VOTE_SHARDS);\n * Postgres and non-transactional Mongo always bump shard 0. Readers sum across shards.\n *\n * When `transactionID` names an open Payload transaction, the write joins it: a bump failure\n * thrown from the submission hook rolls back the submission create (no undercount), and an\n * aborted create rolls back the joined bump (no overcount). Residual risk on transactional\n * Mongo: two concurrent bumps that land on the same shard still abort one transaction\n * (WriteConflict, labelled TransientTransactionError); the losing submission rolls back whole,\n * so counts stay consistent and the client can safely resubmit. Without a transaction (e.g.\n * Mongo with transactions disabled) the write lands on the root handle immediately; a later\n * recount from stored submissions is the healer for any drift that window allows.\n */\n// biome-ignore lint/complexity/useMaxParams: write primitive signature (payload, key, by, transactionID)\nexport async function bumpPollVote(\n\tpayload: Payload,\n\tkey: { form: string; field: string; value: string },\n\tby: number,\n\ttransactionID?: number | string\n): Promise<void> {\n\tconst slug = pluginSlugsOf(payload).pollVotes\n\tif (payload.db.name === 'mongoose') {\n\t\tconst db = payload.db as unknown as MongoDb\n\t\tconst model = db.collections[slug]\n\t\tif (!model) throw new Error(`form-builder: mongoose collection \"${slug}\" not found`)\n\t\tconst session = transactionID !== undefined ? db.sessions?.[transactionID] : undefined\n\t\tconst shard = session ? Math.floor(Math.random() * VOTE_SHARDS) : 0\n\t\tconst shardedKey = { ...key, shard }\n\t\tconst update = { $inc: { count: by }, $setOnInsert: shardedKey }\n\t\tconst options = session ? { upsert: true, session } : { upsert: true }\n\t\ttry {\n\t\t\tawait model.collection.updateOne(shardedKey, update, options)\n\t\t} catch (error) {\n\t\t\t// Concurrent first inserts for a new key can race the upsert into E11000; outside a\n\t\t\t// transaction the row now exists, so one retry takes the $inc branch. Inside a\n\t\t\t// transaction the error propagates and Payload's rollback/retry semantics apply.\n\t\t\tconst duplicate = (error as { code?: unknown } | null)?.code === 11000\n\t\t\tif (session || !duplicate) throw error\n\t\t\tawait model.collection.updateOne(shardedKey, update, options)\n\t\t}\n\t\treturn\n\t}\n\tconst { sql } = await importPostgresSql()\n\tconst db = payload.db as unknown as PgDb\n\t// Payload keys every collection's table by its snake-cased slug, whatever `dbName` renames it to.\n\tconst tableKey = toSnakeCase(slug)\n\tconst tableName = db.tableNameMap.get(tableKey)\n\tif (!tableName) throw new Error(`form-builder: drizzle table \"${tableKey}\" not found`)\n\tconst table = db.tables[tableName]\n\tif (!table) throw new Error(`form-builder: drizzle table object for \"${tableName}\" not found`)\n\tconst txn = transactionID !== undefined ? db.sessions?.[transactionID]?.db : undefined\n\tawait (txn ?? db.drizzle)\n\t\t.insert(table)\n\t\t.values({ ...key, shard: 0, count: by })\n\t\t.onConflictDoUpdate({\n\t\t\ttarget: [table.form, table.field, table.value, table.shard],\n\t\t\tset: { count: sql`${table.count} + ${by}` },\n\t\t})\n}\n"],"mappings":";;;;;;;;;;;;AAeA,MAAM,0BAAsD;CAE3D,OAAO;;;;EADW,CAAC,eAAe,aAAa,EAAE,KAAK,GAE4B;;AAEnF;;;;;;;;;;;;;;;;;;AA2CA,eAAsB,aACrB,SACA,KACA,IACA,eACgB;CAChB,MAAM,OAAO,cAAc,OAAO,EAAE;CACpC,IAAI,QAAQ,GAAG,SAAS,YAAY;EACnC,MAAM,KAAK,QAAQ;EACnB,MAAM,QAAQ,GAAG,YAAY;EAC7B,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,sCAAsC,KAAK,YAAY;EACnF,MAAM,UAAU,kBAAkB,KAAA,IAAY,GAAG,WAAW,iBAAiB,KAAA;EAC7E,MAAM,QAAQ,UAAU,KAAK,MAAM,KAAK,OAAO,IAAA,CAAe,IAAI;EAClE,MAAM,aAAa;GAAE,GAAG;GAAK;EAAM;EACnC,MAAM,SAAS;GAAE,MAAM,EAAE,OAAO,GAAG;GAAG,cAAc;EAAW;EAC/D,MAAM,UAAU,UAAU;GAAE,QAAQ;GAAM;EAAQ,IAAI,EAAE,QAAQ,KAAK;EACrE,IAAI;GACH,MAAM,MAAM,WAAW,UAAU,YAAY,QAAQ,OAAO;EAC7D,SAAS,OAAO;GAIf,MAAM,YAAa,OAAqC,SAAS;GACjE,IAAI,WAAW,CAAC,WAAW,MAAM;GACjC,MAAM,MAAM,WAAW,UAAU,YAAY,QAAQ,OAAO;EAC7D;EACA;CACD;CACA,MAAM,EAAE,QAAQ,MAAM,kBAAkB;CACxC,MAAM,KAAK,QAAQ;CAEnB,MAAM,WAAW,YAAY,IAAI;CACjC,MAAM,YAAY,GAAG,aAAa,IAAI,QAAQ;CAC9C,IAAI,CAAC,WAAW,MAAM,IAAI,MAAM,gCAAgC,SAAS,YAAY;CACrF,MAAM,QAAQ,GAAG,OAAO;CACxB,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,2CAA2C,UAAU,YAAY;CAE7F,QADY,kBAAkB,KAAA,IAAY,GAAG,WAAW,gBAAgB,KAAK,KAAA,MAC/D,GAAG,SACf,OAAO,KAAK,EACZ,OAAO;EAAE,GAAG;EAAK,OAAO;EAAG,OAAO;CAAG,CAAC,EACtC,mBAAmB;EACnB,QAAQ;GAAC,MAAM;GAAM,MAAM;GAAO,MAAM;GAAO,MAAM;EAAK;EAC1D,KAAK,EAAE,OAAO,GAAG,GAAG,MAAM,MAAM,KAAK,KAAK;CAC3C,CAAC;AACH"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { Payload, PayloadRequest } from "payload";
|
|
2
|
+
|
|
3
|
+
//#region src/poll/votes/recountPollVotes.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB
|
|
6
|
+
* changes, or backfill after enabling a poll late). Scans first and refuses a truncated
|
|
7
|
+
* aggregation, then deletes the form's tally rows for the results field and replays the scan
|
|
8
|
+
* into fresh rows, so the store is never left holding a knowingly partial count. Writes join
|
|
9
|
+
* the request's transaction when one is open. Refuses a form with `persistSubmissions` off:
|
|
10
|
+
* its submissions are pruned, so the tally store is the only record of its votes and a rebuild
|
|
11
|
+
* would wipe them.
|
|
12
|
+
*/
|
|
13
|
+
declare const recountPollVotes: (args: {
|
|
14
|
+
payload: Payload;
|
|
15
|
+
formId: number | string;
|
|
16
|
+
req?: PayloadRequest;
|
|
17
|
+
}) => Promise<void>;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { recountPollVotes };
|
|
20
|
+
//# sourceMappingURL=recountPollVotes.d.ts.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { pluginSlugsOf } from "../../plugin/collectionSlugs.js";
|
|
2
|
+
import { pollConfigOf } from "../../form/pollState.js";
|
|
3
|
+
import "./votesCollection.js";
|
|
4
|
+
import { bumpPollVote } from "./bumpPollVote.js";
|
|
5
|
+
import { transactionIDOf } from "./voteTallyHook.js";
|
|
6
|
+
import { aggregateFieldResponses } from "../../aggregation/aggregateResponses.js";
|
|
7
|
+
//#region src/poll/votes/recountPollVotes.ts
|
|
8
|
+
const RECOUNT_MAX_SUBMISSIONS = 1e5;
|
|
9
|
+
/**
|
|
10
|
+
* Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB
|
|
11
|
+
* changes, or backfill after enabling a poll late). Scans first and refuses a truncated
|
|
12
|
+
* aggregation, then deletes the form's tally rows for the results field and replays the scan
|
|
13
|
+
* into fresh rows, so the store is never left holding a knowingly partial count. Writes join
|
|
14
|
+
* the request's transaction when one is open. Refuses a form with `persistSubmissions` off:
|
|
15
|
+
* its submissions are pruned, so the tally store is the only record of its votes and a rebuild
|
|
16
|
+
* would wipe them.
|
|
17
|
+
*/
|
|
18
|
+
const recountPollVotes = async (args) => {
|
|
19
|
+
const { payload, formId, req } = args;
|
|
20
|
+
const form = await payload.findByID({
|
|
21
|
+
collection: pluginSlugsOf(payload).forms,
|
|
22
|
+
id: formId,
|
|
23
|
+
depth: 0,
|
|
24
|
+
overrideAccess: true,
|
|
25
|
+
req
|
|
26
|
+
}).catch(() => null);
|
|
27
|
+
const poll = form ? pollConfigOf(form.poll) : void 0;
|
|
28
|
+
const resultsField = typeof poll?.resultsField === "string" && poll.resultsField.length > 0 ? poll.resultsField : void 0;
|
|
29
|
+
if (!resultsField) return;
|
|
30
|
+
if (form?.persistSubmissions === false) throw new Error(`form-builder: recountPollVotes cannot rebuild form "${String(formId)}": it does not persist submissions, so the tally store is the only record of its votes.`);
|
|
31
|
+
const aggregation = await aggregateFieldResponses({
|
|
32
|
+
payload,
|
|
33
|
+
formId,
|
|
34
|
+
field: resultsField,
|
|
35
|
+
req,
|
|
36
|
+
maxSubmissions: RECOUNT_MAX_SUBMISSIONS
|
|
37
|
+
});
|
|
38
|
+
if (aggregation?.truncated) throw new Error(`form-builder: recount for form ${String(formId)} aborted: more than ${RECOUNT_MAX_SUBMISSIONS} submissions, the scan was truncated and a rebuilt tally would be partial.`);
|
|
39
|
+
await payload.delete({
|
|
40
|
+
collection: pluginSlugsOf(payload).pollVotes,
|
|
41
|
+
where: { and: [{ form: { equals: String(formId) } }, { field: { equals: resultsField } }] },
|
|
42
|
+
overrideAccess: true,
|
|
43
|
+
req
|
|
44
|
+
});
|
|
45
|
+
if (!aggregation) return;
|
|
46
|
+
const transactionID = transactionIDOf(req?.transactionID);
|
|
47
|
+
const base = {
|
|
48
|
+
form: String(formId),
|
|
49
|
+
field: resultsField
|
|
50
|
+
};
|
|
51
|
+
for (const bucket of aggregation.buckets) if (bucket.count > 0) await bumpPollVote(payload, {
|
|
52
|
+
...base,
|
|
53
|
+
value: bucket.value
|
|
54
|
+
}, bucket.count, transactionID);
|
|
55
|
+
if (aggregation.total > 0) await bumpPollVote(payload, {
|
|
56
|
+
...base,
|
|
57
|
+
value: ""
|
|
58
|
+
}, aggregation.total, transactionID);
|
|
59
|
+
};
|
|
60
|
+
//#endregion
|
|
61
|
+
export { recountPollVotes };
|
|
62
|
+
|
|
63
|
+
//# sourceMappingURL=recountPollVotes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"recountPollVotes.js","names":[],"sources":["../../../src/poll/votes/recountPollVotes.ts"],"sourcesContent":["import type { Payload, PayloadRequest } from 'payload'\nimport { aggregateFieldResponses } from '../../aggregation/aggregateResponses'\nimport { pollConfigOf } from '../../form/pollState'\nimport { pluginSlugsOf } from '../../plugin/collectionSlugs'\nimport { bumpPollVote } from './bumpPollVote'\nimport { RESPONDENTS_VALUE } from './votesCollection'\nimport { transactionIDOf } from './voteTallyHook'\n\nconst RECOUNT_MAX_SUBMISSIONS = 100_000\n\n/**\n * Rebuild a form's tally rows from persisted submissions (drift healing after out-of-band DB\n * changes, or backfill after enabling a poll late). Scans first and refuses a truncated\n * aggregation, then deletes the form's tally rows for the results field and replays the scan\n * into fresh rows, so the store is never left holding a knowingly partial count. Writes join\n * the request's transaction when one is open. Refuses a form with `persistSubmissions` off:\n * its submissions are pruned, so the tally store is the only record of its votes and a rebuild\n * would wipe them.\n */\nexport const recountPollVotes = async (args: {\n\tpayload: Payload\n\tformId: number | string\n\treq?: PayloadRequest\n}): Promise<void> => {\n\tconst { payload, formId, req } = args\n\tconst form = await payload\n\t\t.findByID({\n\t\t\tcollection: pluginSlugsOf(payload).forms,\n\t\t\tid: formId,\n\t\t\tdepth: 0,\n\t\t\toverrideAccess: true,\n\t\t\treq,\n\t\t})\n\t\t.catch(() => null)\n\tconst poll = form ? pollConfigOf(form.poll) : undefined\n\tconst resultsField =\n\t\ttypeof poll?.resultsField === 'string' && poll.resultsField.length > 0\n\t\t\t? poll.resultsField\n\t\t\t: undefined\n\tif (!resultsField) {\n\t\treturn\n\t}\n\tif (form?.persistSubmissions === false) {\n\t\tthrow new Error(\n\t\t\t`form-builder: recountPollVotes cannot rebuild form \"${String(formId)}\": it does not persist submissions, so the tally store is the only record of its votes.`\n\t\t)\n\t}\n\tconst aggregation = await aggregateFieldResponses({\n\t\tpayload,\n\t\tformId,\n\t\tfield: resultsField,\n\t\treq,\n\t\tmaxSubmissions: RECOUNT_MAX_SUBMISSIONS,\n\t})\n\tif (aggregation?.truncated) {\n\t\tthrow new Error(\n\t\t\t`form-builder: recount for form ${String(formId)} aborted: more than ${RECOUNT_MAX_SUBMISSIONS} submissions, the scan was truncated and a rebuilt tally would be partial.`\n\t\t)\n\t}\n\tawait payload.delete({\n\t\tcollection: pluginSlugsOf(payload).pollVotes,\n\t\twhere: {\n\t\t\tand: [{ form: { equals: String(formId) } }, { field: { equals: resultsField } }],\n\t\t},\n\t\toverrideAccess: true,\n\t\treq,\n\t})\n\tif (!aggregation) {\n\t\treturn\n\t}\n\tconst transactionID = transactionIDOf(req?.transactionID)\n\tconst base = { form: String(formId), field: resultsField }\n\tfor (const bucket of aggregation.buckets) {\n\t\tif (bucket.count > 0) {\n\t\t\tawait bumpPollVote(payload, { ...base, value: bucket.value }, bucket.count, transactionID)\n\t\t}\n\t}\n\tif (aggregation.total > 0) {\n\t\tawait bumpPollVote(\n\t\t\tpayload,\n\t\t\t{ ...base, value: RESPONDENTS_VALUE },\n\t\t\taggregation.total,\n\t\t\ttransactionID\n\t\t)\n\t}\n}\n"],"mappings":";;;;;;;AAQA,MAAM,0BAA0B;;;;;;;;;;AAWhC,MAAa,mBAAmB,OAAO,SAIlB;CACpB,MAAM,EAAE,SAAS,QAAQ,QAAQ;CACjC,MAAM,OAAO,MAAM,QACjB,SAAS;EACT,YAAY,cAAc,OAAO,EAAE;EACnC,IAAI;EACJ,OAAO;EACP,gBAAgB;EAChB;CACD,CAAC,EACA,YAAY,IAAI;CAClB,MAAM,OAAO,OAAO,aAAa,KAAK,IAAI,IAAI,KAAA;CAC9C,MAAM,eACL,OAAO,MAAM,iBAAiB,YAAY,KAAK,aAAa,SAAS,IAClE,KAAK,eACL,KAAA;CACJ,IAAI,CAAC,cACJ;CAED,IAAI,MAAM,uBAAuB,OAChC,MAAM,IAAI,MACT,uDAAuD,OAAO,MAAM,EAAE,wFACvE;CAED,MAAM,cAAc,MAAM,wBAAwB;EACjD;EACA;EACA,OAAO;EACP;EACA,gBAAgB;CACjB,CAAC;CACD,IAAI,aAAa,WAChB,MAAM,IAAI,MACT,kCAAkC,OAAO,MAAM,EAAE,sBAAsB,wBAAwB,2EAChG;CAED,MAAM,QAAQ,OAAO;EACpB,YAAY,cAAc,OAAO,EAAE;EACnC,OAAO,EACN,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,OAAO,MAAM,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,aAAa,EAAE,CAAC,EAChF;EACA,gBAAgB;EAChB;CACD,CAAC;CACD,IAAI,CAAC,aACJ;CAED,MAAM,gBAAgB,gBAAgB,KAAK,aAAa;CACxD,MAAM,OAAO;EAAE,MAAM,OAAO,MAAM;EAAG,OAAO;CAAa;CACzD,KAAK,MAAM,UAAU,YAAY,SAChC,IAAI,OAAO,QAAQ,GAClB,MAAM,aAAa,SAAS;EAAE,GAAG;EAAM,OAAO,OAAO;CAAM,GAAG,OAAO,OAAO,aAAa;CAG3F,IAAI,YAAY,QAAQ,GACvB,MAAM,aACL,SACA;EAAE,GAAG;EAAM,OAAA;CAAyB,GACpC,YAAY,OACZ,aACD;AAEF"}
|