@processfocus/runtime-local 0.1.0-next.1 → 0.1.0-next.3
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/README.md +48 -253
- package/dist/authentication-server.mjs +52 -84
- package/dist/{chunk-fn7b5pxw.js → chunk-04r0t2mb.js} +19364 -34104
- package/dist/chunk-727y6qkb.js +156 -0
- package/dist/chunk-bg5r4wpv.js +4755 -0
- package/dist/chunk-cbd36jq1.js +512 -0
- package/dist/chunk-d4ctj079.js +241 -0
- package/dist/{chunk-cq9xscgb.js → chunk-r5s2v669.js} +49079 -33564
- package/dist/dashboard-source/apps/frontend/app/(protected)/act-on-behalf/actions.ts +12 -12
- package/dist/dashboard-source/apps/frontend/app/(protected)/act-on-behalf/delegations-client.tsx +31 -21
- package/dist/dashboard-source/apps/frontend/app/(protected)/act-on-behalf/page.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/client-index.tsx +1 -12
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/(.)[executionId]/client.tsx +1 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/(.)[executionId]/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/(.)[executionId]/process-state/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/@modal/default.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/[executionId]/page.tsx +3 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/[executionId]/process-state/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/client-layout.tsx +19 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/default.tsx +6 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/executions-client.tsx +1637 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/layout.tsx +5 -7
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/page.tsx +4 -1589
- package/dist/dashboard-source/apps/frontend/app/(protected)/executions/process-state-page-client.tsx +1 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/layout.tsx +41 -33
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/@modal/(.)item/[id]/client.tsx +11 -17
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/@modal/(.)item/[id]/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/@modal/default.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/list-page-client.tsx +153 -16
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/[...listPath]/page.tsx +10 -2
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-create-form.tsx +29 -13
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-item-edit-form.tsx +22 -28
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-item-load-error.tsx +49 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/components/list-schema-form.tsx +28 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/default.tsx +6 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/hooks/metric-control-url-state.ts +7 -16
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/hooks/use-list-deleted-callback.ts +4 -6
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/hooks/use-list-item-detail.ts +45 -142
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/item/[id]/client.tsx +10 -20
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/item/[id]/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/layout.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/lib/list-process-dialog.tsx +72 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/lib/list-refresh-provider.tsx +65 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/lib/list-refresh.ts +162 -16
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/utils.tsx +19 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/org-chart/page.tsx +4 -9
- package/dist/dashboard-source/apps/frontend/app/(protected)/page.tsx +4 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/passkeys/actions.ts +15 -18
- package/dist/dashboard-source/apps/frontend/app/(protected)/passkeys/page.tsx +12 -6
- package/dist/dashboard-source/apps/frontend/app/(protected)/passkeys/passkeys-client.tsx +7 -16
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/@modal/(.)start/[...startStepPath]/client.tsx +26 -48
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/@modal/(.)start/[...startStepPath]/page.tsx +4 -7
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/@modal/default.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/client-layout.tsx +28 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/client.tsx +1 -3
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/components/start-process-form.tsx +193 -117
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/default.tsx +6 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/layout.tsx +7 -9
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/page.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/processes-client.tsx +60 -204
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/start/[...startStepPath]/client.tsx +12 -51
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/start/[...startStepPath]/page.tsx +27 -4
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/page.tsx +5 -4
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/workflow-flow.tsx +0 -5
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/workflow/[...processPath]/workflow-form-preview-sheet.tsx +26 -19
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/[[...tab]]/page.tsx +5 -2
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/cedar-authorize.ts +85 -9
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/cedar-types.ts +12 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/explorer.tsx +66 -4
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/layout.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/cedar/load-handbook.ts +41 -13
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/[invitationId]/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/invitation-detail-client.tsx +442 -365
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/new/page.tsx +8 -2
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations/page.tsx +7 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/invitations-table.tsx +61 -43
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/page.tsx +6 -67
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/providers/page.tsx +7 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/roles/page.tsx +7 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/settings-client.tsx +111 -189
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/settings-page.tsx +86 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/[userId]/client.tsx +141 -256
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/[userId]/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/[userId]/tokens/page.tsx +2 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users/page.tsx +7 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/settings/users-table.tsx +6 -4
- package/dist/dashboard-source/apps/frontend/app/(protected)/stats/[...statsPath]/page.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/@modal/(.)complete/[...stepPath]/client.tsx +30 -9
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/@modal/(.)complete/[...stepPath]/page.tsx +3 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/@modal/default.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/complete/[...stepPath]/client.tsx +2 -4
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/complete/[...stepPath]/page.tsx +3 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/components/complete-todo-form.tsx +47 -54
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/components/public-completion-correction-form.tsx +37 -54
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/components/todo-form-actions.tsx +1 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/correct/[...stepPath]/page.tsx +3 -1
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/default.tsx +6 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/layout.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/lib/mobile-todo-list.ts +4 -25
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/page.tsx +4 -1315
- package/dist/dashboard-source/apps/frontend/app/(protected)/to-dos/to-dos-client.tsx +1282 -0
- package/dist/dashboard-source/apps/frontend/app/api/auth/callback/route.ts +81 -65
- package/dist/dashboard-source/apps/frontend/app/api/auth/delegation/route.ts +8 -2
- package/dist/dashboard-source/apps/frontend/app/api/auth/login/route.ts +0 -1
- package/dist/dashboard-source/apps/frontend/app/api/auth/logout/route.ts +10 -5
- package/dist/dashboard-source/apps/frontend/app/api/auth/passkey/start/route.ts +1 -3
- package/dist/dashboard-source/apps/frontend/app/api/auth/refresh/route.ts +0 -1
- package/dist/dashboard-source/apps/frontend/app/api/auth/revalidate-google/route.ts +68 -0
- package/dist/dashboard-source/apps/frontend/app/api/auth/switch-role/route.ts +1 -3
- package/dist/dashboard-source/apps/frontend/app/api/embed/lookup/route.ts +25 -7
- package/dist/dashboard-source/apps/frontend/app/api/embed/submit/route.ts +1 -2
- package/dist/dashboard-source/apps/frontend/app/api/public/start/[address]/route.ts +49 -0
- package/dist/dashboard-source/apps/frontend/app/api/public/to-dos/lookup/route.ts +4 -3
- package/dist/dashboard-source/apps/frontend/app/api/revalidate/route.ts +15 -4
- package/dist/dashboard-source/apps/frontend/app/app-shell.tsx +11 -4
- package/dist/dashboard-source/apps/frontend/app/cli-auth/route.ts +2 -1
- package/dist/dashboard-source/apps/frontend/app/embed/[...startStepPath]/embed-client.tsx +31 -18
- package/dist/dashboard-source/apps/frontend/app/embed/[...startStepPath]/page.tsx +5 -1
- package/dist/dashboard-source/apps/frontend/app/login/page.tsx +4 -4
- package/dist/dashboard-source/apps/frontend/app/login/passkey-button.tsx +11 -6
- package/dist/dashboard-source/apps/frontend/app/login/passkey-help/page.tsx +67 -0
- package/dist/dashboard-source/apps/frontend/app/mcp/[[...endpoint]]/route.ts +47 -0
- package/dist/dashboard-source/apps/frontend/app/public/form/[token]/public-todo-client.tsx +44 -25
- package/dist/dashboard-source/apps/frontend/app/public/start/[address]/form/page.tsx +10 -0
- package/dist/dashboard-source/apps/frontend/app/public/start/[address]/layout.tsx +32 -0
- package/dist/dashboard-source/apps/frontend/app/public/start/[address]/page-client.tsx +319 -0
- package/dist/dashboard-source/apps/frontend/app/public/start/[address]/page-content.tsx +41 -0
- package/dist/dashboard-source/apps/frontend/app/public/start/[address]/page.tsx +10 -0
- package/dist/dashboard-source/apps/frontend/app/public.css +1 -1
- package/dist/dashboard-source/apps/frontend/app/register/passkey/register-passkey-client.tsx +17 -0
- package/dist/dashboard-source/apps/frontend/components/DashboardSection.tsx +9 -15
- package/dist/dashboard-source/apps/frontend/components/Header.tsx +4 -8
- package/dist/dashboard-source/apps/frontend/components/anonymous-page-link.tsx +57 -0
- package/dist/dashboard-source/apps/frontend/components/anonymous-start-form.tsx +24 -0
- package/dist/dashboard-source/apps/frontend/components/app-sidebar.tsx +21 -7
- package/dist/dashboard-source/apps/frontend/components/auth-provider.tsx +12 -7
- package/dist/dashboard-source/apps/frontend/components/browser-only.tsx +19 -0
- package/dist/dashboard-source/apps/frontend/components/config-provider.tsx +0 -1
- package/dist/dashboard-source/apps/frontend/components/delegation-expiry.tsx +24 -13
- package/dist/dashboard-source/apps/frontend/components/form-dialog-content.tsx +22 -2
- package/dist/dashboard-source/apps/frontend/components/journey-timeline.tsx +52 -45
- package/dist/dashboard-source/apps/frontend/components/notification-bell.tsx +0 -1
- package/dist/dashboard-source/apps/frontend/components/sidebar-lists.tsx +0 -1
- package/dist/dashboard-source/apps/frontend/components/token-refresh-scheduler.tsx +38 -11
- package/dist/dashboard-source/apps/frontend/components/ui/sidebar.tsx +0 -1
- package/dist/dashboard-source/apps/frontend/components/ui/tab-pill.tsx +26 -15
- package/dist/dashboard-source/apps/frontend/components/workflow/step-node.tsx +0 -1
- package/dist/dashboard-source/apps/frontend/components/workflow/workflow-edge.tsx +5 -0
- package/dist/dashboard-source/apps/frontend/hooks/use-form-metadata.ts +21 -10
- package/dist/dashboard-source/apps/frontend/hooks/use-process-draft.ts +173 -0
- package/dist/dashboard-source/apps/frontend/hooks/use-weekly-execution-stats.ts +1 -3
- package/dist/dashboard-source/apps/frontend/lib/anonymous-page-form-values.ts +6 -0
- package/dist/dashboard-source/apps/frontend/lib/anonymous-page-server.ts +65 -0
- package/dist/dashboard-source/apps/frontend/lib/appsync-events/adapter.ts +9 -3
- package/dist/dashboard-source/apps/frontend/lib/appsync-events/client.ts +7 -340
- package/dist/dashboard-source/apps/frontend/lib/auth/client-session.ts +2 -0
- package/dist/dashboard-source/apps/frontend/lib/auth/delegations.ts +9 -7
- package/dist/dashboard-source/apps/frontend/lib/auth/google-revalidation.ts +111 -0
- package/dist/dashboard-source/apps/frontend/lib/auth/logout.ts +1 -1
- package/dist/dashboard-source/apps/frontend/lib/auth/passkeys.ts +28 -30
- package/dist/dashboard-source/apps/frontend/lib/auth/providers.ts +10 -0
- package/dist/dashboard-source/apps/frontend/lib/auth/realtime-session-token.ts +1 -0
- package/dist/dashboard-source/apps/frontend/lib/auth/reauthentication-state.ts +4 -4
- package/dist/dashboard-source/apps/frontend/lib/auth/session-admission.ts +11 -7
- package/dist/dashboard-source/apps/frontend/lib/auth/session.ts +27 -10
- package/dist/dashboard-source/apps/frontend/lib/auth/ssr-session.ts +76 -9
- package/dist/dashboard-source/apps/frontend/lib/auth/verify-passkey.ts +25 -3
- package/dist/dashboard-source/apps/frontend/lib/collections/collection-provider-factory.tsx +112 -21
- package/dist/dashboard-source/apps/frontend/lib/collections/draft-process-execution.ts +1 -8
- package/dist/dashboard-source/apps/frontend/lib/collections/execution.ts +6 -2
- package/dist/dashboard-source/apps/frontend/lib/collections/process-collection-provider.tsx +3 -0
- package/dist/dashboard-source/apps/frontend/lib/collections/process.ts +8 -2
- package/dist/dashboard-source/apps/frontend/lib/collections/replication-factory.ts +16 -4
- package/dist/dashboard-source/apps/frontend/lib/collections/todo.ts +1 -1
- package/dist/dashboard-source/apps/frontend/lib/effect/navigation.ts +4 -0
- package/dist/dashboard-source/apps/frontend/lib/effect/page-runtime.ts +29 -0
- package/dist/dashboard-source/apps/frontend/lib/effect/params.ts +18 -12
- package/dist/dashboard-source/apps/frontend/lib/effect/run-effect.ts +1 -1
- package/dist/dashboard-source/apps/frontend/lib/effect/runtime.ts +19 -23
- package/dist/dashboard-source/apps/frontend/lib/effect/services/access-token.ts +9 -12
- package/dist/dashboard-source/apps/frontend/lib/effect/services/authorization.ts +12 -12
- package/dist/dashboard-source/apps/frontend/lib/effect/services/form-validation.ts +20 -18
- package/dist/dashboard-source/apps/frontend/lib/effect/services/graphql.ts +32 -16
- package/dist/dashboard-source/apps/frontend/lib/embed-form-server.ts +35 -0
- package/dist/dashboard-source/apps/frontend/lib/embed-manifest.ts +10 -103
- package/dist/dashboard-source/apps/frontend/lib/forms/invitation.ts +43 -0
- package/dist/dashboard-source/apps/frontend/lib/forms/provider-user.ts +64 -0
- package/dist/dashboard-source/apps/frontend/lib/frontend-form-loaders.ts +40 -0
- package/dist/dashboard-source/apps/frontend/lib/frontend-manifest.ts +1 -33
- package/dist/dashboard-source/apps/frontend/lib/generated/gql/gql.ts +123 -33
- package/dist/dashboard-source/apps/frontend/lib/generated/gql/graphql.ts +169 -30
- package/dist/dashboard-source/apps/frontend/lib/generated/gql/index.ts +1 -0
- package/dist/dashboard-source/apps/frontend/lib/graphql/anonymous-page.ts +27 -0
- package/dist/dashboard-source/apps/frontend/lib/graphql/dependent-lookup-query.ts +1 -0
- package/dist/dashboard-source/apps/frontend/lib/graphql/list-queries.ts +38 -29
- package/dist/dashboard-source/apps/frontend/lib/graphql/lookup-provider.tsx +82 -10
- package/dist/dashboard-source/apps/frontend/lib/graphql/org-chart-operations.ts +2 -5
- package/dist/dashboard-source/apps/frontend/lib/graphql/queries.ts +25 -4
- package/dist/dashboard-source/apps/frontend/lib/graphql/server-client.ts +11 -0
- package/dist/dashboard-source/apps/frontend/lib/graphql/settings-queries.ts +13 -104
- package/dist/dashboard-source/apps/frontend/lib/graphql/user-queries.ts +11 -4
- package/dist/dashboard-source/apps/frontend/lib/graphql/workflow-operations.ts +1 -3
- package/dist/dashboard-source/apps/frontend/lib/graphql/workflow-queries.ts +1 -0
- package/dist/dashboard-source/apps/frontend/lib/list-detail-selection.ts +54 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/executions.ts +110 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/list-writes.ts +395 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/lists.ts +263 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/oauth.ts +900 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/origin.ts +42 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/processes.ts +436 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/read-tool.ts +72 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/result.ts +4 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/server.ts +71 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/store.ts +193 -0
- package/dist/dashboard-source/apps/frontend/lib/mcp/todos.ts +237 -0
- package/dist/dashboard-source/apps/frontend/lib/notifications/notification-preference.ts +0 -1
- package/dist/dashboard-source/apps/frontend/lib/notifications/todo-notification-observer.ts +0 -5
- package/dist/dashboard-source/apps/frontend/lib/org-chart-data.ts +0 -2
- package/dist/dashboard-source/apps/frontend/lib/org-identity.ts +6 -4
- package/dist/dashboard-source/apps/frontend/lib/organisation-form-loaders.ts +4 -0
- package/dist/dashboard-source/apps/frontend/lib/public-todo-form-runtime.ts +0 -1
- package/dist/dashboard-source/apps/frontend/lib/public-todo-model.ts +39 -139
- package/dist/dashboard-source/apps/frontend/lib/public-todo-server.ts +17 -16
- package/dist/dashboard-source/apps/frontend/lib/query-client.ts +0 -1
- package/dist/dashboard-source/apps/frontend/lib/todo-utils.ts +1 -77
- package/dist/dashboard-source/apps/frontend/lib/workflow/layout.ts +3 -7
- package/dist/dashboard-source/apps/frontend/next.config.ts +33 -13
- package/dist/dashboard-source/apps/frontend/package.json +48 -47
- package/dist/dashboard-source/apps/frontend/proxy.ts +72 -14
- package/dist/dashboard-source/modules/auth-local-cedar/src/index.ts +0 -3
- package/dist/dashboard-source/modules/auth-local-cedar/src/lib/auth-local-cedar.ts +165 -233
- package/dist/dashboard-source/modules/auth-local-cedar/src/lib/cedar-reload-notifier.ts +4 -3
- package/dist/dashboard-source/modules/auth-local-cedar/src/lib/config-base.ts +111 -75
- package/dist/dashboard-source/modules/auth-local-cedar/src/lib/policy-watcher.ts +14 -18
- package/dist/dashboard-source/modules/auth-policy/src/index.ts +1 -0
- package/dist/dashboard-source/modules/auth-policy/src/lib/auth-policy.ts +19 -37
- package/dist/dashboard-source/modules/auth-policy/src/lib/current-principal.ts +33 -29
- package/dist/dashboard-source/modules/auth-policy/src/lib/policy-revision.ts +23 -0
- package/dist/dashboard-source/modules/auth-policy/src/lib/types.ts +24 -49
- package/dist/dashboard-source/modules/auth-session/src/index.ts +4 -0
- package/dist/dashboard-source/modules/auth-session/src/lib/project-subscription.ts +13 -0
- package/dist/dashboard-source/modules/auth-session/src/lib/realtime-recipient.ts +10 -2
- package/dist/dashboard-source/modules/auth-session/src/lib/subjects.ts +82 -8
- package/dist/dashboard-source/modules/auth-session/src/lib/workload-access.ts +48 -0
- package/dist/dashboard-source/modules/auth-session/src/lib/workload-audit.ts +52 -0
- package/dist/dashboard-source/modules/aws-common/src/index.ts +0 -1
- package/dist/dashboard-source/modules/effect-json-logger/src/lib/effect-json-logger.ts +6 -9
- package/dist/dashboard-source/modules/form/src/hooks/use-local-storage.ts +5 -3
- package/dist/dashboard-source/modules/form/src/index.ts +1 -10
- package/dist/dashboard-source/modules/form/src/lib/effect-schema-form.tsx +1271 -0
- package/dist/dashboard-source/modules/form/src/lib/form-actions.ts +26 -0
- package/dist/dashboard-source/modules/form/src/lib/form-prefill.tsx +79 -0
- package/dist/dashboard-source/modules/form/src/lib/initial-focus.ts +31 -0
- package/dist/dashboard-source/modules/form/src/lib/lookup-context.tsx +18 -0
- package/dist/dashboard-source/modules/form/src/lib/plugin-registry.ts +4 -0
- package/dist/dashboard-source/modules/form/src/lib/plugin-scripts.ts +26 -0
- package/dist/dashboard-source/modules/form/src/lib/registered-plugin-field.tsx +57 -0
- package/dist/dashboard-source/modules/form/src/lib/schema-lookup.tsx +124 -0
- package/dist/dashboard-source/modules/form/src/lib/schema-typeahead.tsx +522 -0
- package/dist/dashboard-source/modules/form/src/lib/validation-logic.ts +172 -0
- package/dist/dashboard-source/modules/form-schema/src/index.ts +4 -1
- package/dist/dashboard-source/modules/form-schema/src/lib/annotation-helpers.ts +19 -14
- package/dist/dashboard-source/modules/form-schema/src/lib/email.ts +13 -11
- package/dist/dashboard-source/modules/form-schema/src/lib/field-count.ts +15 -13
- package/dist/dashboard-source/modules/form-schema/src/lib/form-annotations.ts +14 -0
- package/dist/dashboard-source/modules/form-schema/src/lib/form-presentation.ts +33 -0
- package/dist/dashboard-source/modules/form-schema/src/lib/form-schema.ts +186 -80
- package/dist/dashboard-source/modules/form-schema/src/lib/number-from-string.ts +26 -0
- package/dist/dashboard-source/modules/form-schema/src/lib/phone.ts +8 -7
- package/dist/dashboard-source/modules/form-schema/src/lib/public-completion-correction.ts +7 -0
- package/dist/dashboard-source/modules/form-schema/src/lib/search-lookup-items.ts +27 -0
- package/dist/dashboard-source/modules/form-submission-schema/src/index.ts +5 -0
- package/dist/dashboard-source/modules/form-submission-schema/src/lib/executable-rules.ts +379 -0
- package/dist/dashboard-source/modules/form-submission-schema/src/lib/form-submission-schema.ts +475 -0
- package/dist/dashboard-source/modules/form-submission-schema/src/lib/json-schema.ts +58 -0
- package/dist/dashboard-source/modules/form-submission-schema/src/lib/schema-defaults.ts +158 -0
- package/dist/dashboard-source/modules/form-submission-schema/src/lib/submission-utils.ts +75 -0
- package/dist/dashboard-source/modules/frontend-manifest/src/lib/browser-plugin-artifact.ts +46 -0
- package/dist/dashboard-source/modules/frontend-manifest/src/lib/frontend-manifest.ts +37 -30
- package/dist/dashboard-source/modules/frontend-plugin-host/src/lib/frontend-plugin-host.ts +9 -1
- package/dist/dashboard-source/modules/openauth/src/client.ts +25 -17
- package/dist/dashboard-source/modules/openauth/src/util.ts +16 -0
- package/dist/dashboard-source/modules/{aws-common/src/lib/project-balance-admission.ts → project-accounting/src/admission.ts} +4 -8
- package/dist/dashboard-source/modules/realtime-client/src/appsync-client.ts +377 -0
- package/dist/dashboard-source/modules/realtime-client/src/index.ts +5 -0
- package/dist/dashboard-source/modules/realtime-client/src/subscription-presence.ts +163 -0
- package/dist/dashboard-source/modules/request-time/src/lib/request-time.ts +6 -24
- package/dist/dashboard-source/modules/rxdb-collections/generated/execution-schema.json +28 -21
- package/dist/dashboard-source/modules/rxdb-collections/src/lib/rxdb-collections.ts +25 -18
- package/dist/dashboard-source/modules/rxdb-collections/src/lib/to-rxdb-schema.ts +60 -10
- package/dist/dashboard-source/modules/shadcn-components/src/index.ts +18 -2
- package/dist/dashboard-source/modules/shadcn-components/src/lib/date-calendar.tsx +93 -0
- package/dist/dashboard-source/modules/shadcn-components/src/lib/date-field.tsx +147 -48
- package/dist/dashboard-source/modules/shadcn-components/src/lib/date-time-display.tsx +272 -0
- package/dist/dashboard-source/modules/shadcn-components/src/lib/local-date-time-input.tsx +108 -0
- package/dist/dashboard-source/modules/shadcn-components/src/lib/lookup-field.tsx +237 -351
- package/dist/dashboard-source/modules/shadcn-components/src/lib/ui/popover.tsx +2 -1
- package/dist/dashboard-source.json +48 -47
- package/dist/graphql-server.mjs +245 -200
- package/dist/job-worker-supervisor.mjs +262 -0
- package/dist/job-worker.mjs +234 -133
- package/dist/main.mjs +23 -4
- package/dist/prepare-dashboard.mjs +8 -8
- package/dist/resources/cedar/policies.cedar +80 -38
- package/dist/resources/cedar/schema.cedarschema +39 -21
- package/dist/resources/graphql-schema/rxdb.graphql +2 -0
- package/dist/resources/graphql-schema/system.graphql +204 -51
- package/package.json +64 -62
- package/dist/chunk-6b6t8tyq.js +0 -85
- package/dist/dashboard-source/apps/frontend/app/(protected)/lists/utils.ts +0 -20
- package/dist/dashboard-source/apps/frontend/app/(protected)/processes/components/process-form-actions.tsx +0 -105
- package/dist/dashboard-source/apps/frontend/hooks/use-draft-process-save.ts +0 -189
- package/dist/dashboard-source/apps/frontend/hooks/use-draft-state.ts +0 -79
- package/dist/dashboard-source/apps/frontend/hooks/use-processes-query.ts +0 -56
- package/dist/dashboard-source/modules/form/src/lib/ajv-standard-schema.ts +0 -152
- package/dist/dashboard-source/modules/form/src/lib/client-components-to-form.tsx +0 -1421
- package/dist/dashboard-source/modules/form/src/lib/friendly-validation-message.ts +0 -85
- package/dist/dashboard-source/modules/form/src/lib/walker.tsx +0 -1549
- package/dist/dashboard-source/modules/form-client-representation/src/lib/client-form-definition.ts +0 -440
- package/dist/dashboard-source/modules/form-client-representation/src/lib/plugin-registry.ts +0 -13
- package/dist/dashboard-source/modules/form-client-representation/src/lib/types.ts +0 -336
- package/dist/dashboard-source/modules/form-rule/src/index.ts +0 -21
- package/dist/dashboard-source/modules/form-rule/src/lib/evaluator.ts +0 -531
- package/dist/dashboard-source/modules/form-rule/src/lib/paths.ts +0 -102
- package/dist/dashboard-source/modules/form-rule/src/lib/types.ts +0 -121
- package/dist/dashboard-source/modules/form-schema/src/lib/property-signature.ts +0 -45
|
@@ -0,0 +1,4755 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import {
|
|
3
|
+
QueueStatsError,
|
|
4
|
+
EnqueueError,
|
|
5
|
+
ClaimError,
|
|
6
|
+
AcknowledgeError,
|
|
7
|
+
JobNotFoundError,
|
|
8
|
+
StaleJobClaimError,
|
|
9
|
+
DEFAULT_VISIBILITY_TIMEOUT,
|
|
10
|
+
DEFAULT_MAX_RETRIES,
|
|
11
|
+
validateQueueName,
|
|
12
|
+
closeQueue,
|
|
13
|
+
QueueService,
|
|
14
|
+
formatSqlError,
|
|
15
|
+
getTursoHttpStatus,
|
|
16
|
+
TransactionCommitCallbacks,
|
|
17
|
+
sql,
|
|
18
|
+
TableAliasProxyHandler,
|
|
19
|
+
aliasedTable,
|
|
20
|
+
eq,
|
|
21
|
+
ne,
|
|
22
|
+
and,
|
|
23
|
+
or,
|
|
24
|
+
not,
|
|
25
|
+
gt,
|
|
26
|
+
lt,
|
|
27
|
+
lte,
|
|
28
|
+
inArray,
|
|
29
|
+
notInArray,
|
|
30
|
+
isNull,
|
|
31
|
+
isNotNull,
|
|
32
|
+
notExists,
|
|
33
|
+
like,
|
|
34
|
+
asc,
|
|
35
|
+
desc,
|
|
36
|
+
batchSqliteReads,
|
|
37
|
+
count,
|
|
38
|
+
countDistinct,
|
|
39
|
+
max,
|
|
40
|
+
auditEvent,
|
|
41
|
+
orgUnit,
|
|
42
|
+
process2,
|
|
43
|
+
processVisibility,
|
|
44
|
+
role,
|
|
45
|
+
phase,
|
|
46
|
+
roleResponsibility,
|
|
47
|
+
step,
|
|
48
|
+
stepSupportingRole,
|
|
49
|
+
flow,
|
|
50
|
+
externalParticipant,
|
|
51
|
+
processState,
|
|
52
|
+
processExecution,
|
|
53
|
+
toDo,
|
|
54
|
+
publicCompletionInvitationAttempt,
|
|
55
|
+
scheduledFlow,
|
|
56
|
+
taskDeadline,
|
|
57
|
+
user,
|
|
58
|
+
providerUser,
|
|
59
|
+
providerUserRole,
|
|
60
|
+
userSettings,
|
|
61
|
+
permittedRole,
|
|
62
|
+
permittedClientRole,
|
|
63
|
+
invitation,
|
|
64
|
+
invitationRole,
|
|
65
|
+
oauthStorage,
|
|
66
|
+
oauthProvider,
|
|
67
|
+
oauthClient,
|
|
68
|
+
jobQueue,
|
|
69
|
+
completedJob,
|
|
70
|
+
weeklySchedule,
|
|
71
|
+
calendarPeriod,
|
|
72
|
+
dateException,
|
|
73
|
+
holidayInstance,
|
|
74
|
+
documentStore,
|
|
75
|
+
file,
|
|
76
|
+
stepDocumentStore,
|
|
77
|
+
stepItsCanStartProcess,
|
|
78
|
+
TypedSqliteDrizzle,
|
|
79
|
+
UpdateDeletedDocumentError,
|
|
80
|
+
AwsRoleProofStore,
|
|
81
|
+
BusinessCalendarQueries,
|
|
82
|
+
CleanupOperations,
|
|
83
|
+
CompletedJobOperations,
|
|
84
|
+
DraftProcessExecutionQueries,
|
|
85
|
+
ExecutionDurationQueries,
|
|
86
|
+
ExecutionQueries,
|
|
87
|
+
InvalidExternalParticipantEmail,
|
|
88
|
+
normalizeExternalParticipantEmail,
|
|
89
|
+
ExternalParticipantOperations,
|
|
90
|
+
FileOperations,
|
|
91
|
+
InvitationLifecycleStatus,
|
|
92
|
+
InvitationSource,
|
|
93
|
+
RegistrationLinkStatus,
|
|
94
|
+
defaultNotificationPreferences,
|
|
95
|
+
parseNotificationPreferences,
|
|
96
|
+
serializeNotificationPreferences,
|
|
97
|
+
SettingsQueries,
|
|
98
|
+
normalizeTaggedErrors,
|
|
99
|
+
mapNotificationRecipientRow,
|
|
100
|
+
FlowExecutionOperations,
|
|
101
|
+
calculateFormComplexity,
|
|
102
|
+
StepNotFoundError,
|
|
103
|
+
ProcessExecutionOperations,
|
|
104
|
+
FlowQueries,
|
|
105
|
+
OAuthClientQueries,
|
|
106
|
+
OrgQueries,
|
|
107
|
+
ProcessQueries,
|
|
108
|
+
ProcessCollectionQueries,
|
|
109
|
+
ProviderUserQueries,
|
|
110
|
+
ProcessNotFoundError,
|
|
111
|
+
WorkflowQueries,
|
|
112
|
+
PROCESS_IMPORT_OUTBOX_QUEUE,
|
|
113
|
+
returnedRow,
|
|
114
|
+
ScheduledFlowOperations,
|
|
115
|
+
InvalidProcessStateError,
|
|
116
|
+
StepCompletionOperations,
|
|
117
|
+
StepRoleQueries,
|
|
118
|
+
SystemUserOperations,
|
|
119
|
+
TodoQueries,
|
|
120
|
+
getUserDetails,
|
|
121
|
+
retryTransientSqliteError
|
|
122
|
+
} from "./chunk-04r0t2mb.js";
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
import { Context } from "effect";
|
|
126
|
+
|
|
127
|
+
class RequestTime extends Context.Service()("processfocus:internal-tag/request-time/RequestTime") {
|
|
128
|
+
}
|
|
129
|
+
var getRequestTime = () => RequestTime;
|
|
130
|
+
|
|
131
|
+
function alias(table, alias) {
|
|
132
|
+
return new Proxy(table, new TableAliasProxyHandler(alias, false));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
import { Effect, Layer } from "effect";
|
|
136
|
+
var SqliteBusinessCalendarQueriesLive = Layer.effect(BusinessCalendarQueries, Effect.gen(function* () {
|
|
137
|
+
const db = yield* TypedSqliteDrizzle;
|
|
138
|
+
return {
|
|
139
|
+
getCalendarData: (orgUnitIds) => Effect.gen(function* () {
|
|
140
|
+
if (orgUnitIds.length === 0) {
|
|
141
|
+
return new Map;
|
|
142
|
+
}
|
|
143
|
+
const [orgUnits, weeklySchedules, dateExceptions, holidays, periods] = yield* batchSqliteReads(db, [
|
|
144
|
+
db.select({
|
|
145
|
+
id: orgUnit.id,
|
|
146
|
+
timezone: orgUnit.timezone
|
|
147
|
+
}).from(orgUnit).where(and(inArray(orgUnit.id, orgUnitIds), eq(orgUnit._deleted, false))),
|
|
148
|
+
db.select({
|
|
149
|
+
orgUnitId: weeklySchedule.orgUnitId,
|
|
150
|
+
dayOfWeek: weeklySchedule.dayOfWeek,
|
|
151
|
+
timeRanges: weeklySchedule.timeRanges
|
|
152
|
+
}).from(weeklySchedule).where(and(inArray(weeklySchedule.orgUnitId, orgUnitIds), eq(weeklySchedule._deleted, false))),
|
|
153
|
+
db.select({
|
|
154
|
+
orgUnitId: dateException.orgUnitId,
|
|
155
|
+
exceptionDate: sql`(${dateException.exceptionDate} - 2440587.5) * 86400000`.as("exception_date_ms"),
|
|
156
|
+
exceptionSlots: dateException.exceptionSlots,
|
|
157
|
+
exceptionNote: dateException.exceptionNote
|
|
158
|
+
}).from(dateException).where(and(inArray(dateException.orgUnitId, orgUnitIds), eq(dateException._deleted, false))),
|
|
159
|
+
db.select({
|
|
160
|
+
orgUnitId: holidayInstance.orgUnitId,
|
|
161
|
+
holidayTitle: holidayInstance.holidayTitle,
|
|
162
|
+
holidayRule: holidayInstance.holidayRule,
|
|
163
|
+
holidayDate: sql`CASE WHEN ${holidayInstance.holidayDate} IS NOT NULL THEN (${holidayInstance.holidayDate} - 2440587.5) * 86400000 ELSE NULL END`.as("holiday_date_ms")
|
|
164
|
+
}).from(holidayInstance).where(and(inArray(holidayInstance.orgUnitId, orgUnitIds), eq(holidayInstance._deleted, false))),
|
|
165
|
+
db.select({
|
|
166
|
+
orgUnitId: calendarPeriod.orgUnitId,
|
|
167
|
+
periodKind: calendarPeriod.periodKind,
|
|
168
|
+
periodTitle: calendarPeriod.periodTitle,
|
|
169
|
+
periodStart: sql`(${calendarPeriod.periodStart} - 2440587.5) * 86400000`.as("period_start_ms"),
|
|
170
|
+
periodEnd: sql`(${calendarPeriod.periodEnd} - 2440587.5) * 86400000`.as("period_end_ms"),
|
|
171
|
+
periodActive: calendarPeriod.periodActive,
|
|
172
|
+
periodSchedule: calendarPeriod.periodSchedule
|
|
173
|
+
}).from(calendarPeriod).where(and(inArray(calendarPeriod.orgUnitId, orgUnitIds), eq(calendarPeriod._deleted, false)))
|
|
174
|
+
]);
|
|
175
|
+
const timezoneMap = new Map;
|
|
176
|
+
for (const row of orgUnits) {
|
|
177
|
+
timezoneMap.set(row.id, row.timezone);
|
|
178
|
+
}
|
|
179
|
+
const result = new Map;
|
|
180
|
+
for (const orgUnitId of orgUnitIds) {
|
|
181
|
+
result.set(orgUnitId, {
|
|
182
|
+
orgUnitId,
|
|
183
|
+
timezone: timezoneMap.get(orgUnitId) ?? "UTC",
|
|
184
|
+
weeklySchedule: [],
|
|
185
|
+
dateExceptions: [],
|
|
186
|
+
holidays: [],
|
|
187
|
+
periods: []
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
for (const row of weeklySchedules) {
|
|
191
|
+
const data = result.get(row.orgUnitId);
|
|
192
|
+
if (data) {
|
|
193
|
+
const scheduleRow = {
|
|
194
|
+
orgUnitId: row.orgUnitId,
|
|
195
|
+
dayOfWeek: row.dayOfWeek,
|
|
196
|
+
timeRanges: row.timeRanges
|
|
197
|
+
};
|
|
198
|
+
data.weeklySchedule.push(scheduleRow);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
for (const row of dateExceptions) {
|
|
202
|
+
const data = result.get(row.orgUnitId);
|
|
203
|
+
if (data) {
|
|
204
|
+
const exceptionRow = {
|
|
205
|
+
orgUnitId: row.orgUnitId,
|
|
206
|
+
exceptionDate: row.exceptionDate,
|
|
207
|
+
exceptionSlots: row.exceptionSlots
|
|
208
|
+
};
|
|
209
|
+
if (row.exceptionNote !== null) {
|
|
210
|
+
exceptionRow.exceptionNote = row.exceptionNote;
|
|
211
|
+
}
|
|
212
|
+
data.dateExceptions.push(exceptionRow);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
for (const row of holidays) {
|
|
216
|
+
const data = result.get(row.orgUnitId);
|
|
217
|
+
if (data) {
|
|
218
|
+
const holidayRow = {
|
|
219
|
+
orgUnitId: row.orgUnitId,
|
|
220
|
+
holidayTitle: row.holidayTitle,
|
|
221
|
+
holidayRule: row.holidayRule
|
|
222
|
+
};
|
|
223
|
+
if (row.holidayDate !== null) {
|
|
224
|
+
holidayRow.holidayDate = row.holidayDate;
|
|
225
|
+
}
|
|
226
|
+
data.holidays.push(holidayRow);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
for (const row of periods) {
|
|
230
|
+
const data = result.get(row.orgUnitId);
|
|
231
|
+
if (data) {
|
|
232
|
+
const periodRow = {
|
|
233
|
+
orgUnitId: row.orgUnitId,
|
|
234
|
+
periodKind: row.periodKind,
|
|
235
|
+
periodTitle: row.periodTitle,
|
|
236
|
+
periodStart: row.periodStart,
|
|
237
|
+
periodEnd: row.periodEnd,
|
|
238
|
+
periodActive: row.periodActive
|
|
239
|
+
};
|
|
240
|
+
if (row.periodSchedule !== null) {
|
|
241
|
+
periodRow.periodSchedule = row.periodSchedule;
|
|
242
|
+
}
|
|
243
|
+
data.periods.push(periodRow);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return result;
|
|
247
|
+
}),
|
|
248
|
+
getRootOrgUnit: () => Effect.gen(function* () {
|
|
249
|
+
const rows = yield* db.select({ id: orgUnit.id }).from(orgUnit).where(isNull(orgUnit.parentOrgUnitId)).limit(1);
|
|
250
|
+
return rows[0]?.id ?? null;
|
|
251
|
+
})
|
|
252
|
+
};
|
|
253
|
+
}));
|
|
254
|
+
|
|
255
|
+
import { Effect as Effect2, Layer as Layer2 } from "effect";
|
|
256
|
+
var SqliteCompletedJobOperationsLive = Layer2.effect(CompletedJobOperations, Effect2.gen(function* () {
|
|
257
|
+
const db = yield* TypedSqliteDrizzle;
|
|
258
|
+
return {
|
|
259
|
+
isJobCompleted: (queue, jobId) => Effect2.gen(function* () {
|
|
260
|
+
const result = yield* db.select({ id: completedJob.id }).from(completedJob).where(and(eq(completedJob.queue, queue), eq(completedJob.jobId, jobId), eq(completedJob._deleted, sql`0`))).limit(1);
|
|
261
|
+
return result.length > 0;
|
|
262
|
+
}),
|
|
263
|
+
markJobCompleted: (queue, jobId) => db.insert(completedJob).values({
|
|
264
|
+
queue,
|
|
265
|
+
jobId
|
|
266
|
+
}),
|
|
267
|
+
clearJobCompleted: (queue, jobId) => Effect2.gen(function* () {
|
|
268
|
+
const requestTime = yield* getRequestTime();
|
|
269
|
+
const userDetails = yield* getUserDetails();
|
|
270
|
+
yield* db.update(completedJob).set({
|
|
271
|
+
_deleted: true,
|
|
272
|
+
updatedAt: requestTime,
|
|
273
|
+
updatedBy: userDetails.by
|
|
274
|
+
}).where(and(eq(completedJob.queue, queue), eq(completedJob.jobId, jobId), eq(completedJob._deleted, sql`0`)));
|
|
275
|
+
})
|
|
276
|
+
};
|
|
277
|
+
}));
|
|
278
|
+
|
|
279
|
+
import { Effect as Effect3, Layer as Layer3 } from "effect";
|
|
280
|
+
var SqliteExecutionDurationQueriesLive = Layer3.effect(ExecutionDurationQueries, Effect3.gen(function* () {
|
|
281
|
+
const db = yield* TypedSqliteDrizzle;
|
|
282
|
+
return {
|
|
283
|
+
getExecutionTimestamps: (processIds, sampleSize) => Effect3.gen(function* () {
|
|
284
|
+
if (processIds.length === 0) {
|
|
285
|
+
return [];
|
|
286
|
+
}
|
|
287
|
+
const rankedExecutions = db.$with("ranked_executions").as(db.select({
|
|
288
|
+
processId: processState.processId,
|
|
289
|
+
orgUnitId: process2.orgUnitId,
|
|
290
|
+
createdAt: sql`(${processExecution.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),
|
|
291
|
+
finishedAt: sql`(${processExecution.finishedAt} - 2440587.5) * 86400000`.as("finished_at_ms"),
|
|
292
|
+
rowNum: sql`ROW_NUMBER() OVER (PARTITION BY ${processState.processId} ORDER BY ${processExecution.finishedAt} DESC)`.as("row_num")
|
|
293
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(process2, eq(processState.processId, process2.id)).where(and(isNotNull(processExecution.finishedAt), eq(processExecution._deleted, sql`0`), eq(processState._deleted, false), eq(process2._deleted, false), inArray(processState.processId, processIds))));
|
|
294
|
+
const rows = yield* db.with(rankedExecutions).select({
|
|
295
|
+
processId: rankedExecutions.processId,
|
|
296
|
+
orgUnitId: rankedExecutions.orgUnitId,
|
|
297
|
+
createdAt: rankedExecutions.createdAt,
|
|
298
|
+
finishedAt: rankedExecutions.finishedAt
|
|
299
|
+
}).from(rankedExecutions).where(lte(rankedExecutions.rowNum, sampleSize));
|
|
300
|
+
return rows.map((row) => ({
|
|
301
|
+
processId: row.processId,
|
|
302
|
+
orgUnitId: row.orgUnitId,
|
|
303
|
+
createdAt: row.createdAt,
|
|
304
|
+
finishedAt: row.finishedAt
|
|
305
|
+
}));
|
|
306
|
+
})
|
|
307
|
+
};
|
|
308
|
+
}));
|
|
309
|
+
|
|
310
|
+
import { DateTime, Effect as Effect4, Layer as Layer4 } from "effect";
|
|
311
|
+
var SqliteExecutionQueriesLive = Layer4.effect(ExecutionQueries, Effect4.gen(function* () {
|
|
312
|
+
const db = yield* TypedSqliteDrizzle;
|
|
313
|
+
const roleOrgUnit = alias(orgUnit, "role_org_unit");
|
|
314
|
+
const completingRole = alias(role, "completing_role");
|
|
315
|
+
const assignedProviderUser = alias(providerUser, "assigned_provider_user");
|
|
316
|
+
const queryTodosForExecutions = (executionIds) => Effect4.gen(function* () {
|
|
317
|
+
if (executionIds.length === 0)
|
|
318
|
+
return [];
|
|
319
|
+
const rows = yield* db.select({
|
|
320
|
+
executionId: toDo.processExecutionId,
|
|
321
|
+
updatedBy: toDo.updatedBy,
|
|
322
|
+
todoId: toDo.id,
|
|
323
|
+
stepId: step.id,
|
|
324
|
+
stepName: step.name,
|
|
325
|
+
stepPath: step.path,
|
|
326
|
+
completed: toDo._deleted,
|
|
327
|
+
interruptedAt: toDo.interruptedAt,
|
|
328
|
+
failureReason: toDo.failureReason,
|
|
329
|
+
notStartedReason: toDo.notStartedReason,
|
|
330
|
+
correctionRequiredAt: sql`CASE WHEN ${toDo.correctionRequiredAt} IS NULL THEN NULL ELSE (${toDo.correctionRequiredAt} - 2440587.5) * 86400000 END`.as("correction_required_at_millis"),
|
|
331
|
+
correctionFailureReason: toDo.correctionFailureReason,
|
|
332
|
+
completedByUserId: toDo.completedByUserId,
|
|
333
|
+
providerUserId: providerUser.id,
|
|
334
|
+
providerUserFirstName: providerUser.firstName,
|
|
335
|
+
providerUserLastName: providerUser.lastName,
|
|
336
|
+
providerUserEmail: providerUser.email,
|
|
337
|
+
providerUserPicture: providerUser.picture,
|
|
338
|
+
providerUserOrgUnit: orgUnit.name,
|
|
339
|
+
assignedProviderUserEmail: assignedProviderUser.email,
|
|
340
|
+
externalParticipantId: externalParticipant.id,
|
|
341
|
+
externalParticipantEmail: externalParticipant.email,
|
|
342
|
+
roleId: role.id,
|
|
343
|
+
roleName: role.name,
|
|
344
|
+
roleOrgUnitPath: roleOrgUnit.path,
|
|
345
|
+
completingRoleId: completingRole.id,
|
|
346
|
+
completingRoleName: completingRole.name,
|
|
347
|
+
completingRolePath: completingRole.path,
|
|
348
|
+
itemData: toDo.itemData,
|
|
349
|
+
createdAt: sql`(${toDo.createdAt} - 2440587.5) * 86400000`.as("created_at_millis"),
|
|
350
|
+
updatedAt: sql`(${toDo.updatedAt} - 2440587.5) * 86400000`.as("updated_at_millis")
|
|
351
|
+
}).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).leftJoin(role, eq(step.roleId, role.id)).leftJoin(roleOrgUnit, eq(role.orgUnitId, roleOrgUnit.id)).leftJoin(completingRole, eq(toDo.completedByRoleId, completingRole.id)).leftJoin(user, eq(toDo.completedByUserId, user.id)).leftJoin(providerUser, and(eq(user.id, providerUser.userId), eq(providerUser._deleted, false))).leftJoin(orgUnit, eq(providerUser.orgUnitId, orgUnit.id)).leftJoin(assignedProviderUser, eq(toDo.assignedToProviderUserId, assignedProviderUser.id)).leftJoin(externalParticipant, eq(toDo.completedByExternalParticipantId, externalParticipant.id)).where(inArray(toDo.processExecutionId, executionIds)).orderBy(toDo.updatedAt);
|
|
352
|
+
const deadlines = yield* db.select({
|
|
353
|
+
id: taskDeadline.id,
|
|
354
|
+
ownerTodoId: taskDeadline.ownerToDoId,
|
|
355
|
+
name: taskDeadline.deadlineName,
|
|
356
|
+
dueAt: taskDeadline.scheduledAt,
|
|
357
|
+
triggeredAt: taskDeadline.triggeredAt,
|
|
358
|
+
disarmedAt: taskDeadline.disarmedAt
|
|
359
|
+
}).from(taskDeadline).innerJoin(toDo, eq(taskDeadline.ownerToDoId, toDo.id)).where(inArray(toDo.processExecutionId, executionIds));
|
|
360
|
+
return rows.map((row) => ({
|
|
361
|
+
deadlines: deadlines.filter((deadline) => deadline.ownerTodoId === row.todoId).map((deadline) => ({
|
|
362
|
+
id: deadline.id,
|
|
363
|
+
name: deadline.name,
|
|
364
|
+
dueAt: DateTime.formatIso(deadline.dueAt),
|
|
365
|
+
triggeredAt: deadline.triggeredAt ? DateTime.formatIso(deadline.triggeredAt) : null,
|
|
366
|
+
disarmedAt: deadline.disarmedAt ? DateTime.formatIso(deadline.disarmedAt) : null
|
|
367
|
+
})),
|
|
368
|
+
executionId: row.executionId,
|
|
369
|
+
updatedBy: row.updatedBy,
|
|
370
|
+
todoId: row.todoId,
|
|
371
|
+
stepId: row.stepId,
|
|
372
|
+
stepName: row.stepName,
|
|
373
|
+
stepPath: row.stepPath,
|
|
374
|
+
completed: row.completed,
|
|
375
|
+
interrupted: row.interruptedAt !== null,
|
|
376
|
+
failureReason: row.failureReason,
|
|
377
|
+
notStartedReason: row.notStartedReason,
|
|
378
|
+
correctionRequiredAt: row.correctionRequiredAt,
|
|
379
|
+
correctionFailureReason: row.correctionFailureReason,
|
|
380
|
+
completedByUserId: row.completedByUserId,
|
|
381
|
+
providerUserId: row.providerUserId,
|
|
382
|
+
providerUserFirstName: row.providerUserFirstName,
|
|
383
|
+
providerUserLastName: row.providerUserLastName,
|
|
384
|
+
providerUserEmail: row.providerUserEmail,
|
|
385
|
+
providerUserPicture: row.providerUserPicture,
|
|
386
|
+
providerUserOrgUnit: row.providerUserOrgUnit,
|
|
387
|
+
assignedProviderUserEmail: row.assignedProviderUserEmail,
|
|
388
|
+
externalParticipantId: row.externalParticipantId,
|
|
389
|
+
externalParticipantEmail: row.externalParticipantEmail,
|
|
390
|
+
roleId: row.roleId,
|
|
391
|
+
roleName: row.roleName,
|
|
392
|
+
roleOrgUnitPath: row.roleOrgUnitPath,
|
|
393
|
+
completingRoleId: row.completingRoleId,
|
|
394
|
+
completingRoleName: row.completingRoleName,
|
|
395
|
+
completingRolePath: row.completingRolePath,
|
|
396
|
+
itemData: row.itemData,
|
|
397
|
+
createdAt: row.createdAt,
|
|
398
|
+
updatedAt: row.updatedAt
|
|
399
|
+
}));
|
|
400
|
+
});
|
|
401
|
+
const startStep = alias(step, "start_step");
|
|
402
|
+
const startStepRole = alias(role, "start_step_role");
|
|
403
|
+
const startStepRoleOrgUnit = alias(orgUnit, "start_step_role_org_unit");
|
|
404
|
+
const startedByRole = alias(role, "started_by_role");
|
|
405
|
+
const startExternalParticipant = alias(externalParticipant, "start_external_participant");
|
|
406
|
+
const queryExecutions = (options) => Effect4.gen(function* () {
|
|
407
|
+
const executionIdFilter = options.executionIds === undefined ? undefined : inArray(processExecution.id, options.executionIds);
|
|
408
|
+
const requestedProcessIds = executionIdFilter === undefined ? undefined : db.select({ processId: processState.processId }).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).where(executionIdFilter);
|
|
409
|
+
const durationStats = db.$with("duration_stats").as(db.select({
|
|
410
|
+
processId: processState.processId,
|
|
411
|
+
minDurationMs: sql`MIN(${processExecution.businessDuration})`.as("min_duration_ms"),
|
|
412
|
+
maxDurationMs: sql`MAX(${processExecution.businessDuration})`.as("max_duration_ms")
|
|
413
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).where(and(isNotNull(processExecution.finishedAt), isNotNull(processExecution.businessDuration), eq(processExecution._deleted, sql`0`), eq(processState._deleted, sql`0`), requestedProcessIds === undefined ? undefined : inArray(processState.processId, requestedProcessIds))).groupBy(processState.processId));
|
|
414
|
+
const baseQuery = db.with(durationStats).select({
|
|
415
|
+
id: processExecution.id,
|
|
416
|
+
processStateId: processExecution.processStateId,
|
|
417
|
+
withoutWaiting: processExecution.withoutWaiting,
|
|
418
|
+
processName: process2.name,
|
|
419
|
+
processPath: process2.path,
|
|
420
|
+
finishedAt: sql`CASE WHEN ${processExecution.finishedAt} IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%SZ', ${processExecution.finishedAt}) END`.as("finished_at_iso"),
|
|
421
|
+
abandonedAt: sql`CASE WHEN ${processExecution.abandonedAt} IS NULL THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%SZ', ${processExecution.abandonedAt}) END`.as("abandoned_at_iso"),
|
|
422
|
+
abandonedReason: processExecution.abandonedReason,
|
|
423
|
+
notStartedReason: processExecution.notStartedReason,
|
|
424
|
+
startedAt: sql`strftime('%Y-%m-%dT%H:%M:%SZ', ${processExecution.createdAt})`.as("started_at_iso"),
|
|
425
|
+
updatedAt: sql`CAST(ROUND((${processExecution.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),
|
|
426
|
+
deleted: processExecution._deleted,
|
|
427
|
+
startedAtMs: sql`(${processExecution.createdAt} - 2440587.5) * 86400000`.as("started_at_millis"),
|
|
428
|
+
finishedAtMs: sql`CASE WHEN ${processExecution.finishedAt} IS NULL THEN NULL ELSE (${processExecution.finishedAt} - 2440587.5) * 86400000 END`.as("finished_at_millis"),
|
|
429
|
+
startStepId: startStep.id,
|
|
430
|
+
startStepName: startStep.name,
|
|
431
|
+
startStepPath: startStep.path,
|
|
432
|
+
startStepRoleId: startStepRole.id,
|
|
433
|
+
systemStartCompleted: sql`EXISTS (SELECT 1 FROM ${completedJob} WHERE ${completedJob.queue} = 'system-step-execution' AND ${completedJob.jobId} = 'start-' || ${processExecution.id} AND ${completedJob._deleted} = 0)`.mapWith(Boolean),
|
|
434
|
+
startStepRoleName: startStepRole.name,
|
|
435
|
+
startStepRoleOrgUnitPath: startStepRoleOrgUnit.path,
|
|
436
|
+
startedByRoleId: startedByRole.id,
|
|
437
|
+
startedByRoleName: startedByRole.name,
|
|
438
|
+
startedByRolePath: startedByRole.path,
|
|
439
|
+
startStepEmbedded: startStep.embedded,
|
|
440
|
+
startStepExternalParticipantId: startExternalParticipant.id,
|
|
441
|
+
startStepExternalParticipantEmail: startExternalParticipant.email,
|
|
442
|
+
processStateCreatedAt: sql`strftime('%Y-%m-%dT%H:%M:%SZ', ${processState.createdAt})`.as("process_state_created_at_iso"),
|
|
443
|
+
startedByEmail: providerUser.email,
|
|
444
|
+
startedByProvider: user.provider,
|
|
445
|
+
startedBySubject: user.sub,
|
|
446
|
+
createdBy: processExecution.createdBy,
|
|
447
|
+
startedById: providerUser.id,
|
|
448
|
+
startedByFirstName: providerUser.firstName,
|
|
449
|
+
startedByLastName: providerUser.lastName,
|
|
450
|
+
startedByPicture: providerUser.picture,
|
|
451
|
+
startedByOrgUnit: orgUnit.name,
|
|
452
|
+
processSlaValue: process2.slaValue,
|
|
453
|
+
processSlaUnit: process2.slaUnit,
|
|
454
|
+
processSlaWarning: process2.slaWarning,
|
|
455
|
+
typicalDurationMinMs: durationStats.minDurationMs,
|
|
456
|
+
typicalDurationMaxMs: durationStats.maxDurationMs,
|
|
457
|
+
processOrgUnitId: process2.orgUnitId
|
|
458
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(process2, eq(processState.processId, process2.id)).innerJoin(startStep, eq(processState.startStepId, startStep.id)).leftJoin(startStepRole, eq(startStep.roleId, startStepRole.id)).leftJoin(startStepRoleOrgUnit, eq(startStepRole.orgUnitId, startStepRoleOrgUnit.id)).leftJoin(startedByRole, eq(processState.startedByRoleId, startedByRole.id)).leftJoin(user, eq(processState.startedByUserId, user.id)).leftJoin(providerUser, and(eq(user.id, providerUser.userId), eq(providerUser._deleted, sql`0`))).leftJoin(orgUnit, eq(providerUser.orgUnitId, orgUnit.id)).leftJoin(startExternalParticipant, eq(processState.startedByExternalParticipantId, startExternalParticipant.id)).leftJoin(durationStats, eq(processState.processId, durationStats.processId)).where(and(executionIdFilter, options.whereClause));
|
|
459
|
+
const orderedQuery = options.newestFirst ? baseQuery.orderBy(desc(processExecution.createdAt), processExecution.id) : baseQuery.orderBy(processExecution.updatedAt, processExecution.id);
|
|
460
|
+
const limitedQuery = options.limit !== undefined ? orderedQuery.limit(options.limit) : orderedQuery;
|
|
461
|
+
const query = options.offset !== undefined ? limitedQuery.offset(options.offset) : limitedQuery;
|
|
462
|
+
const rows = yield* query;
|
|
463
|
+
return rows.map((row) => ({
|
|
464
|
+
id: row.id,
|
|
465
|
+
processStateId: row.processStateId,
|
|
466
|
+
withoutWaiting: row.withoutWaiting,
|
|
467
|
+
processName: row.processName,
|
|
468
|
+
processPath: row.processPath,
|
|
469
|
+
status: row.notStartedReason != null ? "Not started" : row.abandonedAt != null ? "Abandoned" : row.abandonedReason != null ? "Failed" : row.finishedAt != null ? "Completed" : "Running",
|
|
470
|
+
startedAt: row.startedAt,
|
|
471
|
+
finishedAt: row.finishedAt,
|
|
472
|
+
durationMs: row.finishedAtMs != null ? Math.round(row.finishedAtMs - row.startedAtMs) : null,
|
|
473
|
+
updatedAt: row.updatedAt,
|
|
474
|
+
deleted: row.deleted,
|
|
475
|
+
startStepId: row.startStepId,
|
|
476
|
+
startStepName: row.startStepName,
|
|
477
|
+
startStepPath: row.startStepPath,
|
|
478
|
+
startStepRoleId: row.startStepRoleId,
|
|
479
|
+
systemStartCompleted: row.systemStartCompleted,
|
|
480
|
+
startStepRoleName: row.startStepRoleName,
|
|
481
|
+
startStepRoleOrgUnitPath: row.startStepRoleOrgUnitPath,
|
|
482
|
+
startedByRoleId: row.startedByRoleId,
|
|
483
|
+
startedByRoleName: row.startedByRoleName,
|
|
484
|
+
startedByRolePath: row.startedByRolePath,
|
|
485
|
+
startStepEmbedded: row.startStepEmbedded,
|
|
486
|
+
startStepExternalParticipantId: row.startStepExternalParticipantId,
|
|
487
|
+
startStepExternalParticipantEmail: row.startStepExternalParticipantEmail,
|
|
488
|
+
processStateCreatedAt: row.processStateCreatedAt,
|
|
489
|
+
startedByEmail: row.startedByEmail,
|
|
490
|
+
startedByServiceAccountId: row.startedByProvider === "client_credentials" ? row.startedBySubject : null,
|
|
491
|
+
createdBy: row.createdBy,
|
|
492
|
+
startedById: row.startedById,
|
|
493
|
+
startedByFirstName: row.startedByFirstName,
|
|
494
|
+
startedByLastName: row.startedByLastName,
|
|
495
|
+
startedByPicture: row.startedByPicture,
|
|
496
|
+
startedByOrgUnit: row.startedByOrgUnit,
|
|
497
|
+
processSlaValue: row.processSlaValue,
|
|
498
|
+
processSlaUnit: row.processSlaUnit,
|
|
499
|
+
processSlaWarning: row.processSlaWarning,
|
|
500
|
+
typicalDurationMinMs: row.typicalDurationMinMs,
|
|
501
|
+
typicalDurationMaxMs: row.typicalDurationMaxMs,
|
|
502
|
+
processOrgUnitId: row.processOrgUnitId,
|
|
503
|
+
abandonedReason: row.abandonedReason,
|
|
504
|
+
notStartedReason: row.notStartedReason
|
|
505
|
+
}));
|
|
506
|
+
});
|
|
507
|
+
const buildCheckpointFilter = (checkpoint) => {
|
|
508
|
+
if (!checkpoint)
|
|
509
|
+
return;
|
|
510
|
+
const updatedAtMillis = sql`CAST(ROUND((${processExecution.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;
|
|
511
|
+
return or(gt(updatedAtMillis, checkpoint.updatedAt), and(eq(updatedAtMillis, checkpoint.updatedAt), gt(processExecution.id, checkpoint.id)));
|
|
512
|
+
};
|
|
513
|
+
const getProcessStateByExecutionId = (executionId) => Effect4.gen(function* () {
|
|
514
|
+
const rows = yield* db.select({
|
|
515
|
+
state: processState.state
|
|
516
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).where(eq(processExecution.id, executionId)).limit(1);
|
|
517
|
+
const row = rows[0];
|
|
518
|
+
if (!row)
|
|
519
|
+
return null;
|
|
520
|
+
return row.state;
|
|
521
|
+
});
|
|
522
|
+
const runningFilter = and(isNull(processExecution.finishedAt), isNull(processExecution.abandonedAt), isNull(processExecution.abandonedReason));
|
|
523
|
+
return {
|
|
524
|
+
pullExecution: (checkpoint, limit, includeRunning = false, historySince) => queryExecutions({
|
|
525
|
+
whereClause: and(historySince === undefined ? undefined : or(buildCheckpointFilter({ id: "", updatedAt: historySince }), runningFilter), includeRunning && checkpoint ? or(buildCheckpointFilter(checkpoint), runningFilter) : buildCheckpointFilter(checkpoint)),
|
|
526
|
+
limit
|
|
527
|
+
}),
|
|
528
|
+
getExecutions: (ids) => ids.length === 0 ? Effect4.succeed([]) : queryExecutions({ executionIds: ids }),
|
|
529
|
+
listExecutions: (query) => queryExecutions({
|
|
530
|
+
whereClause: and(eq(processExecution._deleted, sql`0`), query.processPath != null ? eq(process2.path, query.processPath) : undefined),
|
|
531
|
+
limit: query.limit,
|
|
532
|
+
offset: query.offset,
|
|
533
|
+
newestFirst: true
|
|
534
|
+
}),
|
|
535
|
+
getTodosForExecutions: queryTodosForExecutions,
|
|
536
|
+
getUnfinishedWorkForExecutions: (executionIds) => Effect4.gen(function* () {
|
|
537
|
+
if (executionIds.length === 0)
|
|
538
|
+
return { todos: [], scheduledFlows: [] };
|
|
539
|
+
const source = alias(step, "source_step");
|
|
540
|
+
const target = alias(step, "target_step");
|
|
541
|
+
const todos = yield* db.select({
|
|
542
|
+
executionId: toDo.processExecutionId,
|
|
543
|
+
stepPath: step.path,
|
|
544
|
+
failureReason: toDo.failureReason
|
|
545
|
+
}).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).where(and(inArray(toDo.processExecutionId, executionIds), eq(toDo._deleted, false)));
|
|
546
|
+
const scheduledFlows = yield* db.select({
|
|
547
|
+
executionId: scheduledFlow.processExecutionId,
|
|
548
|
+
sourceStepPath: source.path,
|
|
549
|
+
targetStepPath: target.path
|
|
550
|
+
}).from(scheduledFlow).innerJoin(source, and(eq(scheduledFlow.sourceStepId, source.id), eq(source._deleted, false))).leftJoin(target, and(eq(scheduledFlow.targetStepId, target.id), eq(target._deleted, false))).where(and(inArray(scheduledFlow.processExecutionId, executionIds), eq(scheduledFlow._deleted, false)));
|
|
551
|
+
return { todos, scheduledFlows };
|
|
552
|
+
}),
|
|
553
|
+
getProcessStateByExecutionId
|
|
554
|
+
};
|
|
555
|
+
}));
|
|
556
|
+
|
|
557
|
+
import { Effect as Effect5, Layer as Layer5 } from "effect";
|
|
558
|
+
var SqliteExternalParticipantOperationsLive = Layer5.effect(ExternalParticipantOperations, Effect5.gen(function* () {
|
|
559
|
+
const db = yield* TypedSqliteDrizzle;
|
|
560
|
+
return {
|
|
561
|
+
upsertByEmail: (email) => Effect5.gen(function* () {
|
|
562
|
+
const normalizedEmail = normalizeExternalParticipantEmail(email);
|
|
563
|
+
if (normalizedEmail === null) {
|
|
564
|
+
return yield* new InvalidExternalParticipantEmail({
|
|
565
|
+
email,
|
|
566
|
+
message: "External participant email must be a valid email address"
|
|
567
|
+
});
|
|
568
|
+
}
|
|
569
|
+
const requestTime = yield* getRequestTime();
|
|
570
|
+
const userDetails = yield* getUserDetails();
|
|
571
|
+
const rows = yield* db.insert(externalParticipant).values({
|
|
572
|
+
email: normalizedEmail,
|
|
573
|
+
createdAt: requestTime,
|
|
574
|
+
updatedAt: requestTime,
|
|
575
|
+
createdBy: userDetails.by,
|
|
576
|
+
updatedBy: userDetails.by
|
|
577
|
+
}).onConflictDoUpdate({
|
|
578
|
+
target: externalParticipant.email,
|
|
579
|
+
targetWhere: sql`_deleted = 0`,
|
|
580
|
+
set: {
|
|
581
|
+
updatedAt: requestTime,
|
|
582
|
+
updatedBy: userDetails.by
|
|
583
|
+
}
|
|
584
|
+
}).returning({ id: externalParticipant.id });
|
|
585
|
+
return (yield* returnedRow(rows)).id;
|
|
586
|
+
})
|
|
587
|
+
};
|
|
588
|
+
}));
|
|
589
|
+
|
|
590
|
+
import { Effect as Effect6, Layer as Layer6 } from "effect";
|
|
591
|
+
var SqliteFileOperationsLive = Layer6.effect(FileOperations, Effect6.gen(function* () {
|
|
592
|
+
const db = yield* TypedSqliteDrizzle;
|
|
593
|
+
return {
|
|
594
|
+
createFile: (documentStoreId, mimeType, createdBy) => Effect6.gen(function* () {
|
|
595
|
+
const requestTime = yield* getRequestTime();
|
|
596
|
+
const result = yield* db.insert(file).values({
|
|
597
|
+
documentStoreId,
|
|
598
|
+
mediaKind: mimeType ?? null,
|
|
599
|
+
uploadPending: true,
|
|
600
|
+
createdBy,
|
|
601
|
+
createdAt: requestTime,
|
|
602
|
+
updatedAt: requestTime
|
|
603
|
+
}).returning({ id: file.id });
|
|
604
|
+
return (yield* returnedRow(result)).id;
|
|
605
|
+
}),
|
|
606
|
+
getFileWithStore: (fileId) => Effect6.gen(function* () {
|
|
607
|
+
const rows = yield* db.select({
|
|
608
|
+
id: file.id,
|
|
609
|
+
documentStoreId: file.documentStoreId,
|
|
610
|
+
fileSize: file.fileSize,
|
|
611
|
+
uploadPending: file.uploadPending,
|
|
612
|
+
storeName: documentStore.name,
|
|
613
|
+
acceptedTypes: documentStore.acceptedTypes,
|
|
614
|
+
sizeLimit: documentStore.sizeLimit
|
|
615
|
+
}).from(file).innerJoin(documentStore, eq(file.documentStoreId, documentStore.id)).where(eq(file.id, fileId)).limit(1);
|
|
616
|
+
const row = rows[0];
|
|
617
|
+
if (!row)
|
|
618
|
+
return null;
|
|
619
|
+
return {
|
|
620
|
+
...row,
|
|
621
|
+
acceptedTypes: row.acceptedTypes ?? null
|
|
622
|
+
};
|
|
623
|
+
}),
|
|
624
|
+
markFileUploaded: (fileId, fileSize, mimeType) => Effect6.gen(function* () {
|
|
625
|
+
const requestTime = yield* getRequestTime();
|
|
626
|
+
const updateSet = {
|
|
627
|
+
uploadPending: false,
|
|
628
|
+
updatedAt: requestTime
|
|
629
|
+
};
|
|
630
|
+
if (fileSize !== undefined) {
|
|
631
|
+
updateSet["fileSize"] = fileSize;
|
|
632
|
+
}
|
|
633
|
+
if (mimeType !== undefined) {
|
|
634
|
+
updateSet["mediaKind"] = mimeType;
|
|
635
|
+
}
|
|
636
|
+
yield* db.update(file).set(updateSet).where(eq(file.id, fileId));
|
|
637
|
+
}),
|
|
638
|
+
getDocumentStoreByPath: (path) => Effect6.gen(function* () {
|
|
639
|
+
const rows = yield* db.select({
|
|
640
|
+
id: documentStore.id,
|
|
641
|
+
name: documentStore.name
|
|
642
|
+
}).from(documentStore).where(eq(documentStore.path, path)).limit(1);
|
|
643
|
+
return rows[0] ?? null;
|
|
644
|
+
}),
|
|
645
|
+
isStepLinkedToDocumentStore: (stepPath, documentStorePath) => Effect6.gen(function* () {
|
|
646
|
+
const rows = yield* db.select({ count: sql`count(*)` }).from(stepDocumentStore).innerJoin(step, eq(stepDocumentStore.stepId, step.id)).innerJoin(documentStore, eq(stepDocumentStore.documentStoreId, documentStore.id)).where(and(eq(step.path, stepPath), eq(documentStore.path, documentStorePath), eq(stepDocumentStore._deleted, false))).limit(1);
|
|
647
|
+
return (rows[0]?.count ?? 0) > 0;
|
|
648
|
+
}),
|
|
649
|
+
getFileOwnerInfo: (fileId) => Effect6.gen(function* () {
|
|
650
|
+
const rows = yield* db.select({
|
|
651
|
+
createdBy: file.createdBy,
|
|
652
|
+
orgUnitPath: orgUnit.path,
|
|
653
|
+
documentStorePath: documentStore.path
|
|
654
|
+
}).from(file).innerJoin(documentStore, eq(file.documentStoreId, documentStore.id)).innerJoin(orgUnit, eq(documentStore.orgUnitId, orgUnit.id)).where(eq(file.id, fileId)).limit(1);
|
|
655
|
+
const row = rows[0];
|
|
656
|
+
if (!row?.createdBy)
|
|
657
|
+
return null;
|
|
658
|
+
return {
|
|
659
|
+
createdBy: row.createdBy,
|
|
660
|
+
orgUnitPath: row.orgUnitPath,
|
|
661
|
+
documentStorePath: row.documentStorePath
|
|
662
|
+
};
|
|
663
|
+
}),
|
|
664
|
+
deleteFile: (fileId) => Effect6.gen(function* () {
|
|
665
|
+
const result = yield* db.delete(file).where(eq(file.id, fileId)).returning({ id: file.id });
|
|
666
|
+
return result.length > 0;
|
|
667
|
+
})
|
|
668
|
+
};
|
|
669
|
+
}));
|
|
670
|
+
|
|
671
|
+
import { Effect as Effect7, Layer as Layer7 } from "effect";
|
|
672
|
+
var SqliteFlowExecutionOperationsLive = Layer7.effect(FlowExecutionOperations, Effect7.gen(function* () {
|
|
673
|
+
const db = yield* TypedSqliteDrizzle;
|
|
674
|
+
const sourceStep = aliasedTable(step, "source_step");
|
|
675
|
+
const targetStep = aliasedTable(step, "target_step");
|
|
676
|
+
const operations = {
|
|
677
|
+
queryFlowById: (flowId) => Effect7.gen(function* () {
|
|
678
|
+
const result = yield* db.select({
|
|
679
|
+
id: flow.id,
|
|
680
|
+
condition: flow.condition,
|
|
681
|
+
schedule: flow.schedule,
|
|
682
|
+
sourceStepPath: sourceStep.path,
|
|
683
|
+
targetStepId: targetStep.id,
|
|
684
|
+
targetStepPath: targetStep.path,
|
|
685
|
+
fallbackBranch: flow.fallbackBranch,
|
|
686
|
+
isOnError: flow.errorBranch,
|
|
687
|
+
deadlineName: flow.deadlineName,
|
|
688
|
+
taggedErrors: flow.errorTags
|
|
689
|
+
}).from(flow).innerJoin(sourceStep, eq(flow.sourceStepId, sourceStep.id)).innerJoin(targetStep, eq(flow.targetStepId, targetStep.id)).where(and(eq(flow.id, flowId), eq(flow._deleted, false))).limit(1);
|
|
690
|
+
const flow2 = result[0];
|
|
691
|
+
if (!flow2) {
|
|
692
|
+
return null;
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
...flow2,
|
|
696
|
+
taggedErrors: normalizeTaggedErrors(flow2.taggedErrors)
|
|
697
|
+
};
|
|
698
|
+
}),
|
|
699
|
+
getProcessStateByExecutionId: (processExecutionId) => Effect7.gen(function* () {
|
|
700
|
+
const result = yield* db.select({
|
|
701
|
+
processStateId: processState.id,
|
|
702
|
+
withoutWaiting: processExecution.withoutWaiting,
|
|
703
|
+
createdBy: processExecution.createdBy,
|
|
704
|
+
state: processState.state
|
|
705
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).where(eq(processExecution.id, processExecutionId)).limit(1);
|
|
706
|
+
if (!result[0]) {
|
|
707
|
+
return null;
|
|
708
|
+
}
|
|
709
|
+
return {
|
|
710
|
+
processStateId: result[0].processStateId,
|
|
711
|
+
withoutWaiting: result[0].withoutWaiting,
|
|
712
|
+
createdBy: result[0].createdBy,
|
|
713
|
+
state: result[0].state
|
|
714
|
+
};
|
|
715
|
+
}),
|
|
716
|
+
isProcessExecutionOpen: (processExecutionId) => Effect7.gen(function* () {
|
|
717
|
+
const result = yield* db.select({ id: processExecution.id }).from(processExecution).where(and(eq(processExecution.id, processExecutionId), isNull(processExecution.finishedAt), isNull(processExecution.abandonedAt))).limit(1);
|
|
718
|
+
return result.length > 0;
|
|
719
|
+
}),
|
|
720
|
+
queryTodoNotificationInfo: (todoIds) => Effect7.gen(function* () {
|
|
721
|
+
if (todoIds.length === 0) {
|
|
722
|
+
return [];
|
|
723
|
+
}
|
|
724
|
+
return yield* db.select({
|
|
725
|
+
todoId: toDo.id,
|
|
726
|
+
processExecutionId: toDo.processExecutionId,
|
|
727
|
+
assignedToProviderUserId: toDo.assignedToProviderUserId,
|
|
728
|
+
roleId: step.roleId,
|
|
729
|
+
stepPath: step.path,
|
|
730
|
+
processName: process2.name,
|
|
731
|
+
stepName: step.name,
|
|
732
|
+
itemData: toDo.itemData
|
|
733
|
+
}).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).innerJoin(process2, eq(step.processId, process2.id)).where(and(inArray(toDo.id, todoIds), eq(toDo._deleted, false), eq(flow._deleted, false), eq(step._deleted, false), eq(process2._deleted, false)));
|
|
734
|
+
}),
|
|
735
|
+
insertToDo: ({
|
|
736
|
+
processExecutionId,
|
|
737
|
+
flowId,
|
|
738
|
+
assignedToProviderUserId,
|
|
739
|
+
slaTargetAt,
|
|
740
|
+
slaWarningAt,
|
|
741
|
+
itemData,
|
|
742
|
+
barrierScheduledFlowId
|
|
743
|
+
}) => Effect7.gen(function* () {
|
|
744
|
+
const requestTime = yield* getRequestTime();
|
|
745
|
+
const userDetails = yield* getUserDetails();
|
|
746
|
+
const insertResult = yield* db.insert(toDo).values({
|
|
747
|
+
processExecutionId,
|
|
748
|
+
flowId,
|
|
749
|
+
assignedToProviderUserId: assignedToProviderUserId ?? null,
|
|
750
|
+
slaTargetAt: slaTargetAt ?? null,
|
|
751
|
+
slaWarningAt: slaWarningAt ?? null,
|
|
752
|
+
itemData: itemData ?? null,
|
|
753
|
+
barrierScheduledFlowId: barrierScheduledFlowId ?? null,
|
|
754
|
+
createdAt: requestTime,
|
|
755
|
+
updatedAt: requestTime,
|
|
756
|
+
createdBy: userDetails.by,
|
|
757
|
+
updatedBy: userDetails.by
|
|
758
|
+
}).returning({ id: toDo.id });
|
|
759
|
+
return (yield* returnedRow(insertResult)).id;
|
|
760
|
+
}),
|
|
761
|
+
insertToDos: ({
|
|
762
|
+
processExecutionId,
|
|
763
|
+
flowId,
|
|
764
|
+
items,
|
|
765
|
+
slaTargetAt,
|
|
766
|
+
slaWarningAt,
|
|
767
|
+
barrierScheduledFlowId
|
|
768
|
+
}) => Effect7.gen(function* () {
|
|
769
|
+
const requestTime = yield* getRequestTime();
|
|
770
|
+
const userDetails = yield* getUserDetails();
|
|
771
|
+
const insertResult = yield* db.insert(toDo).values(items.map((itemData) => ({
|
|
772
|
+
processExecutionId,
|
|
773
|
+
flowId,
|
|
774
|
+
slaTargetAt: slaTargetAt ?? null,
|
|
775
|
+
slaWarningAt: slaWarningAt ?? null,
|
|
776
|
+
itemData,
|
|
777
|
+
barrierScheduledFlowId: barrierScheduledFlowId ?? null,
|
|
778
|
+
createdAt: requestTime,
|
|
779
|
+
updatedAt: requestTime,
|
|
780
|
+
createdBy: userDetails.by,
|
|
781
|
+
updatedBy: userDetails.by
|
|
782
|
+
}))).returning({ id: toDo.id });
|
|
783
|
+
return insertResult.map((row) => row.id);
|
|
784
|
+
}),
|
|
785
|
+
queryFlowsBySourceStepId: (sourceStepId) => Effect7.gen(function* () {
|
|
786
|
+
const result = yield* db.select({
|
|
787
|
+
id: flow.id,
|
|
788
|
+
condition: flow.condition,
|
|
789
|
+
schedule: flow.schedule,
|
|
790
|
+
sourceStepPath: sourceStep.path,
|
|
791
|
+
targetStepId: targetStep.id,
|
|
792
|
+
targetStepPath: targetStep.path,
|
|
793
|
+
fallbackBranch: flow.fallbackBranch,
|
|
794
|
+
isOnError: flow.errorBranch,
|
|
795
|
+
deadlineName: flow.deadlineName,
|
|
796
|
+
taggedErrors: flow.errorTags
|
|
797
|
+
}).from(flow).innerJoin(sourceStep, eq(flow.sourceStepId, sourceStep.id)).innerJoin(targetStep, eq(flow.targetStepId, targetStep.id)).where(and(eq(flow.sourceStepId, sourceStepId), eq(flow._deleted, false)));
|
|
798
|
+
return result.map((flow2) => ({
|
|
799
|
+
...flow2,
|
|
800
|
+
taggedErrors: normalizeTaggedErrors(flow2.taggedErrors)
|
|
801
|
+
}));
|
|
802
|
+
}),
|
|
803
|
+
countActiveTodos: (processExecutionId) => Effect7.gen(function* () {
|
|
804
|
+
const result = yield* db.select({ count: sql`COUNT(*)`.as("count") }).from(toDo).where(and(eq(toDo.processExecutionId, processExecutionId), eq(toDo._deleted, false)));
|
|
805
|
+
return Number(result[0]?.count ?? 0);
|
|
806
|
+
}),
|
|
807
|
+
countPendingFlowJobs: (processExecutionId, queueName) => Effect7.gen(function* () {
|
|
808
|
+
const result = yield* db.select({ count: sql`COUNT(*)`.as("count") }).from(jobQueue).where(and(eq(jobQueue.queue, queueName), eq(jobQueue._deleted, false), sql`(
|
|
809
|
+
(
|
|
810
|
+
json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId') IS NULL
|
|
811
|
+
AND json_extract(${jobQueue.jobPayload}, '$.processExecutionId') = ${processExecutionId}
|
|
812
|
+
)
|
|
813
|
+
OR
|
|
814
|
+
(
|
|
815
|
+
json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId') IS NOT NULL
|
|
816
|
+
AND json_extract(${jobQueue.jobPayload}, '$.processExecutionId') = ${processExecutionId}
|
|
817
|
+
AND EXISTS (
|
|
818
|
+
SELECT 1 FROM ${scheduledFlow}
|
|
819
|
+
WHERE ${scheduledFlow.id} = json_extract(${jobQueue.jobPayload}, '$.payload.scheduledFlowId')
|
|
820
|
+
AND ${scheduledFlow._deleted} = false
|
|
821
|
+
)
|
|
822
|
+
)
|
|
823
|
+
)`));
|
|
824
|
+
return Number(result[0]?.count ?? 0);
|
|
825
|
+
}),
|
|
826
|
+
insertFlowDispatchJobs: (jobs) => Effect7.gen(function* () {
|
|
827
|
+
if (jobs.length === 0)
|
|
828
|
+
return;
|
|
829
|
+
const requestTime = yield* getRequestTime();
|
|
830
|
+
const userDetails = yield* getUserDetails();
|
|
831
|
+
yield* db.insert(jobQueue).values(jobs.map(({
|
|
832
|
+
sourceScheduledFlowId,
|
|
833
|
+
processExecutionId,
|
|
834
|
+
storageQueue,
|
|
835
|
+
...job
|
|
836
|
+
}) => ({
|
|
837
|
+
queue: storageQueue ?? job.queue,
|
|
838
|
+
jobPayload: {
|
|
839
|
+
sourceScheduledFlowId,
|
|
840
|
+
...processExecutionId === undefined ? {} : { processExecutionId },
|
|
841
|
+
...job
|
|
842
|
+
},
|
|
843
|
+
createdAt: requestTime,
|
|
844
|
+
updatedAt: requestTime,
|
|
845
|
+
createdBy: userDetails.by,
|
|
846
|
+
updatedBy: userDetails.by
|
|
847
|
+
})));
|
|
848
|
+
}),
|
|
849
|
+
queryFlowDispatchJobs: (sourceScheduledFlowId) => Effect7.gen(function* () {
|
|
850
|
+
const rows = yield* db.select({
|
|
851
|
+
id: jobQueue.id,
|
|
852
|
+
payload: jobQueue.jobPayload
|
|
853
|
+
}).from(jobQueue).where(and(eq(jobQueue._deleted, false), sql`json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId') = ${sourceScheduledFlowId}`));
|
|
854
|
+
return rows.map(({ id, payload }) => ({
|
|
855
|
+
id,
|
|
856
|
+
...payload
|
|
857
|
+
})).sort((left, right) => left.sequence - right.sequence);
|
|
858
|
+
}),
|
|
859
|
+
queryFlowDispatchIdsByStorageQueue: (storageQueue, now, limit) => Effect7.gen(function* () {
|
|
860
|
+
const sourceScheduledFlowId = sql`json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId')`;
|
|
861
|
+
const rows = yield* db.select({ sourceScheduledFlowId }).from(jobQueue).where(and(eq(jobQueue._deleted, false), eq(jobQueue.queue, storageQueue), or(isNull(jobQueue.lockedUntil), lte(jobQueue.lockedUntil, now)))).groupBy(sourceScheduledFlowId).orderBy(sql`MIN(${jobQueue.createdAt})`, sourceScheduledFlowId).limit(limit);
|
|
862
|
+
return rows.map((row) => row.sourceScheduledFlowId);
|
|
863
|
+
}),
|
|
864
|
+
claimFlowDispatchJobs: (sourceScheduledFlowId, now, lockedUntil, receipt) => operations.claimFlowDispatchJobsBatch([sourceScheduledFlowId], now, lockedUntil, receipt),
|
|
865
|
+
claimFlowDispatchJobsBatch: (sourceScheduledFlowIds, now, lockedUntil, receipt) => Effect7.gen(function* () {
|
|
866
|
+
if (sourceScheduledFlowIds.length === 0)
|
|
867
|
+
return [];
|
|
868
|
+
const rows = yield* db.update(jobQueue).set({ lockedUntil, claimReceipt: receipt }).where(and(eq(jobQueue._deleted, false), inArray(sql`json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId')`, [...sourceScheduledFlowIds]), or(isNull(jobQueue.lockedUntil), lte(jobQueue.lockedUntil, now)))).returning({
|
|
869
|
+
id: jobQueue.id,
|
|
870
|
+
payload: jobQueue.jobPayload,
|
|
871
|
+
sourceScheduledFlowId: sql`json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId')`
|
|
872
|
+
});
|
|
873
|
+
return rows.map(({ id, payload, sourceScheduledFlowId }) => ({
|
|
874
|
+
id,
|
|
875
|
+
sourceScheduledFlowId,
|
|
876
|
+
...payload
|
|
877
|
+
})).sort((left, right) => sourceScheduledFlowIds.indexOf(left.sourceScheduledFlowId) - sourceScheduledFlowIds.indexOf(right.sourceScheduledFlowId) || left.sequence - right.sequence);
|
|
878
|
+
}),
|
|
879
|
+
deleteFlowDispatchJobs: (claims) => Effect7.gen(function* () {
|
|
880
|
+
if (claims.length === 0)
|
|
881
|
+
return [];
|
|
882
|
+
const rows = yield* db.delete(jobQueue).where(or(...claims.map(({ id, receipt }) => and(eq(jobQueue.id, id), eq(jobQueue.claimReceipt, receipt))))).returning({ id: jobQueue.id });
|
|
883
|
+
return rows.map((row) => row.id);
|
|
884
|
+
}),
|
|
885
|
+
releaseFlowDispatchJobs: (sourceScheduledFlowId, receipt) => db.update(jobQueue).set({ lockedUntil: null, claimReceipt: null }).where(and(eq(jobQueue._deleted, false), eq(jobQueue.claimReceipt, receipt), sql`json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId') = ${sourceScheduledFlowId}`)),
|
|
886
|
+
extendFlowDispatchClaim: (sourceScheduledFlowId, receipt, lockedUntil) => Effect7.gen(function* () {
|
|
887
|
+
const rows = yield* db.update(jobQueue).set({ lockedUntil }).where(and(eq(jobQueue._deleted, false), eq(jobQueue.claimReceipt, receipt), sql`json_extract(${jobQueue.jobPayload}, '$.sourceScheduledFlowId') = ${sourceScheduledFlowId}`)).returning({ id: jobQueue.id });
|
|
888
|
+
return rows.length > 0;
|
|
889
|
+
}),
|
|
890
|
+
ownsFlowDispatchJob: (id, receipt, now) => Effect7.gen(function* () {
|
|
891
|
+
const rows = yield* db.select({ id: jobQueue.id }).from(jobQueue).where(and(eq(jobQueue.id, id), eq(jobQueue._deleted, false), eq(jobQueue.claimReceipt, receipt), gt(jobQueue.lockedUntil, now))).limit(1);
|
|
892
|
+
return rows.length > 0;
|
|
893
|
+
}),
|
|
894
|
+
deleteFlowDispatchJob: (id, receipt) => Effect7.gen(function* () {
|
|
895
|
+
const rows = yield* db.delete(jobQueue).where(receipt === undefined ? eq(jobQueue.id, id) : and(eq(jobQueue.id, id), eq(jobQueue.claimReceipt, receipt))).returning({ id: jobQueue.id });
|
|
896
|
+
return rows.length > 0;
|
|
897
|
+
}),
|
|
898
|
+
setProcessExecutionFinished: (processExecutionId, businessDurationMs) => Effect7.gen(function* () {
|
|
899
|
+
const requestTime = yield* getRequestTime();
|
|
900
|
+
const userDetails = yield* getUserDetails();
|
|
901
|
+
yield* db.update(processExecution).set({
|
|
902
|
+
finishedAt: requestTime,
|
|
903
|
+
businessDuration: businessDurationMs,
|
|
904
|
+
updatedAt: requestTime,
|
|
905
|
+
updatedBy: userDetails.by
|
|
906
|
+
}).where(eq(processExecution.id, processExecutionId));
|
|
907
|
+
}),
|
|
908
|
+
setProcessExecutionFailed: (processExecutionId, failureReason) => Effect7.gen(function* () {
|
|
909
|
+
const requestTime = yield* getRequestTime();
|
|
910
|
+
const userDetails = yield* getUserDetails();
|
|
911
|
+
yield* db.update(processExecution).set({
|
|
912
|
+
finishedAt: requestTime,
|
|
913
|
+
abandonedReason: failureReason,
|
|
914
|
+
notStartedReason: null,
|
|
915
|
+
updatedAt: requestTime,
|
|
916
|
+
updatedBy: userDetails.by
|
|
917
|
+
}).where(and(eq(processExecution.id, processExecutionId), isNull(processExecution.finishedAt), isNull(processExecution.abandonedAt)));
|
|
918
|
+
}),
|
|
919
|
+
getProcessIdForExecution: (processExecutionId) => Effect7.gen(function* () {
|
|
920
|
+
const result = yield* db.select({
|
|
921
|
+
processId: processState.processId
|
|
922
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).where(eq(processExecution.id, processExecutionId)).limit(1);
|
|
923
|
+
return result[0]?.processId ?? null;
|
|
924
|
+
}),
|
|
925
|
+
getExecutionDetailsForCompletion: (processExecutionId) => Effect7.gen(function* () {
|
|
926
|
+
const result = yield* db.select({
|
|
927
|
+
restartAttemptId: processExecution.restartAttemptId,
|
|
928
|
+
createdAtMs: sql`(${processExecution.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),
|
|
929
|
+
orgUnitId: process2.orgUnitId
|
|
930
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(process2, eq(processState.processId, process2.id)).where(eq(processExecution.id, processExecutionId)).limit(1);
|
|
931
|
+
return result[0] ?? null;
|
|
932
|
+
}),
|
|
933
|
+
getTargetStepSlaInfo: (flowId) => Effect7.gen(function* () {
|
|
934
|
+
const result = yield* db.select({
|
|
935
|
+
slaValue: targetStep.slaValue,
|
|
936
|
+
slaUnit: targetStep.slaUnit,
|
|
937
|
+
slaWarning: targetStep.slaWarning,
|
|
938
|
+
orgUnitId: process2.orgUnitId
|
|
939
|
+
}).from(flow).innerJoin(targetStep, eq(flow.targetStepId, targetStep.id)).innerJoin(process2, eq(targetStep.processId, process2.id)).where(and(eq(flow.id, flowId), eq(flow._deleted, false))).limit(1);
|
|
940
|
+
return result[0] ?? null;
|
|
941
|
+
}),
|
|
942
|
+
targetStepHasRole: (flowId) => Effect7.gen(function* () {
|
|
943
|
+
const result = yield* db.select({
|
|
944
|
+
roleId: targetStep.roleId
|
|
945
|
+
}).from(flow).innerJoin(targetStep, eq(flow.targetStepId, targetStep.id)).where(and(eq(flow.id, flowId), eq(flow._deleted, false))).limit(1);
|
|
946
|
+
if (!result[0]) {
|
|
947
|
+
return null;
|
|
948
|
+
}
|
|
949
|
+
return result[0].roleId !== null;
|
|
950
|
+
}),
|
|
951
|
+
targetStepHasForEach: (flowId) => Effect7.gen(function* () {
|
|
952
|
+
const result = yield* db.select({
|
|
953
|
+
hasForEach: targetStep.hasForEach
|
|
954
|
+
}).from(flow).innerJoin(targetStep, eq(flow.targetStepId, targetStep.id)).where(and(eq(flow.id, flowId), eq(flow._deleted, false))).limit(1);
|
|
955
|
+
if (!result[0]) {
|
|
956
|
+
return null;
|
|
957
|
+
}
|
|
958
|
+
return result[0].hasForEach;
|
|
959
|
+
}),
|
|
960
|
+
countActiveTodosForStep: (processExecutionId, targetStepId) => Effect7.gen(function* () {
|
|
961
|
+
const result = yield* db.select({ count: sql`COUNT(*)`.as("count") }).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).where(and(eq(toDo.processExecutionId, processExecutionId), eq(flow.targetStepId, targetStepId), eq(toDo._deleted, false)));
|
|
962
|
+
return Number(result[0]?.count ?? 0);
|
|
963
|
+
}),
|
|
964
|
+
getStepRetryLimitByPath: (stepPath) => Effect7.gen(function* () {
|
|
965
|
+
const result = yield* db.select({ retryLimit: step.retryLimit }).from(step).where(and(eq(step.path, stepPath), eq(step._deleted, false))).limit(1);
|
|
966
|
+
if (!result[0]) {
|
|
967
|
+
yield* Effect7.logWarning("getStepRetryLimitByPath: step not found", {
|
|
968
|
+
stepPath
|
|
969
|
+
});
|
|
970
|
+
return null;
|
|
971
|
+
}
|
|
972
|
+
return result[0].retryLimit;
|
|
973
|
+
}),
|
|
974
|
+
queryNotificationRecipientByProviderUserId: (providerUserId) => Effect7.gen(function* () {
|
|
975
|
+
const result = yield* db.select({
|
|
976
|
+
providerUserId: providerUser.id,
|
|
977
|
+
userId: providerUser.userId,
|
|
978
|
+
email: providerUser.email,
|
|
979
|
+
name: providerUser.name,
|
|
980
|
+
firstName: providerUser.firstName,
|
|
981
|
+
lastName: providerUser.lastName,
|
|
982
|
+
notificationPreference: userSettings.notificationPreference
|
|
983
|
+
}).from(providerUser).leftJoin(userSettings, and(eq(userSettings.userId, providerUser.userId), eq(userSettings._deleted, false))).where(and(eq(providerUser.id, providerUserId), eq(providerUser._deleted, false))).limit(1);
|
|
984
|
+
const row = result[0];
|
|
985
|
+
return row ? mapNotificationRecipientRow(row) : null;
|
|
986
|
+
}),
|
|
987
|
+
queryNotificationRecipientsByRoleId: (roleId) => Effect7.gen(function* () {
|
|
988
|
+
const result = yield* db.select({
|
|
989
|
+
providerUserId: providerUser.id,
|
|
990
|
+
userId: providerUser.userId,
|
|
991
|
+
email: providerUser.email,
|
|
992
|
+
name: providerUser.name,
|
|
993
|
+
firstName: providerUser.firstName,
|
|
994
|
+
lastName: providerUser.lastName,
|
|
995
|
+
notificationPreference: userSettings.notificationPreference
|
|
996
|
+
}).from(providerUserRole).innerJoin(providerUser, eq(providerUserRole.providerUserId, providerUser.id)).leftJoin(userSettings, and(eq(userSettings.userId, providerUser.userId), eq(userSettings._deleted, false))).where(and(eq(providerUserRole.roleId, roleId), eq(providerUserRole._deleted, false), eq(providerUser._deleted, false)));
|
|
997
|
+
return result.map(mapNotificationRecipientRow);
|
|
998
|
+
}),
|
|
999
|
+
queryNotificationRecipientsByRolePath: (rolePath) => Effect7.gen(function* () {
|
|
1000
|
+
const result = yield* db.select({
|
|
1001
|
+
providerUserId: providerUser.id,
|
|
1002
|
+
userId: providerUser.userId,
|
|
1003
|
+
email: providerUser.email,
|
|
1004
|
+
name: providerUser.name,
|
|
1005
|
+
firstName: providerUser.firstName,
|
|
1006
|
+
lastName: providerUser.lastName,
|
|
1007
|
+
notificationPreference: userSettings.notificationPreference
|
|
1008
|
+
}).from(providerUserRole).innerJoin(providerUser, eq(providerUserRole.providerUserId, providerUser.id)).innerJoin(role, eq(providerUserRole.roleId, role.id)).leftJoin(userSettings, and(eq(userSettings.userId, providerUser.userId), eq(userSettings._deleted, false))).where(and(eq(role.path, rolePath), eq(providerUserRole._deleted, false), eq(providerUser._deleted, false), eq(role._deleted, false)));
|
|
1009
|
+
return result.map(mapNotificationRecipientRow);
|
|
1010
|
+
})
|
|
1011
|
+
};
|
|
1012
|
+
return operations;
|
|
1013
|
+
}));
|
|
1014
|
+
|
|
1015
|
+
import { Layer as Layer23 } from "effect";
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
import { Effect as Effect8, Layer as Layer8 } from "effect";
|
|
1019
|
+
var SqliteAwsRoleProofStoreLive = Layer8.effect(AwsRoleProofStore, Effect8.gen(function* () {
|
|
1020
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1021
|
+
return AwsRoleProofStore.of({
|
|
1022
|
+
clients: db.select({
|
|
1023
|
+
clientId: oauthClient.clientId,
|
|
1024
|
+
bindings: oauthClient.awsRoleBindings
|
|
1025
|
+
}).from(oauthClient).where(and(eq(oauthClient._deleted, false), eq(oauthClient.audience, "graphql-api"))),
|
|
1026
|
+
consume: (key, expiresAt) => db.insert(oauthStorage).values({
|
|
1027
|
+
oauthKey: key,
|
|
1028
|
+
keyKind: "aws-role-proof",
|
|
1029
|
+
keyValue: {},
|
|
1030
|
+
keyExpiry: expiresAt
|
|
1031
|
+
}).onConflictDoNothing({ target: oauthStorage.oauthKey }).returning({ id: oauthStorage.id }).pipe(Effect8.map((rows) => rows.length === 1)),
|
|
1032
|
+
cleanup: (now) => db.delete(oauthStorage).where(and(eq(oauthStorage.keyKind, "aws-role-proof"), lt(oauthStorage.keyExpiry, now))).pipe(Effect8.asVoid)
|
|
1033
|
+
});
|
|
1034
|
+
}));
|
|
1035
|
+
|
|
1036
|
+
|
|
1037
|
+
import { Effect as Effect9, Layer as Layer9 } from "effect";
|
|
1038
|
+
var SqliteCleanupOperationsLive = Layer9.effect(CleanupOperations, Effect9.gen(function* () {
|
|
1039
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1040
|
+
return {
|
|
1041
|
+
cleanupExecutions: () => Effect9.gen(function* () {
|
|
1042
|
+
yield* db.delete(publicCompletionInvitationAttempt);
|
|
1043
|
+
yield* db.delete(taskDeadline);
|
|
1044
|
+
const todos = yield* db.select({ id: toDo.id }).from(toDo);
|
|
1045
|
+
const todosDeleted = todos.length;
|
|
1046
|
+
yield* db.delete(toDo);
|
|
1047
|
+
const scheduledFlows = yield* db.select({ id: scheduledFlow.id }).from(scheduledFlow);
|
|
1048
|
+
const scheduledFlowsDeleted = scheduledFlows.length;
|
|
1049
|
+
yield* db.delete(scheduledFlow);
|
|
1050
|
+
const jobs = yield* db.select({ id: jobQueue.id }).from(jobQueue);
|
|
1051
|
+
const jobsDeleted = jobs.length;
|
|
1052
|
+
yield* db.delete(jobQueue);
|
|
1053
|
+
yield* db.delete(completedJob);
|
|
1054
|
+
const executions = yield* db.select({ id: processExecution.id }).from(processExecution);
|
|
1055
|
+
const executionsDeleted = executions.length;
|
|
1056
|
+
yield* db.delete(processExecution);
|
|
1057
|
+
const states = yield* db.select({ id: processState.id }).from(processState);
|
|
1058
|
+
const statesDeleted = states.length;
|
|
1059
|
+
yield* db.delete(processState);
|
|
1060
|
+
yield* Effect9.log("Cleanup completed").pipe(Effect9.annotateLogs({
|
|
1061
|
+
todosDeleted,
|
|
1062
|
+
scheduledFlowsDeleted,
|
|
1063
|
+
executionsDeleted,
|
|
1064
|
+
statesDeleted,
|
|
1065
|
+
jobsDeleted
|
|
1066
|
+
}));
|
|
1067
|
+
return {
|
|
1068
|
+
todosDeleted,
|
|
1069
|
+
scheduledFlowsDeleted,
|
|
1070
|
+
executionsDeleted,
|
|
1071
|
+
statesDeleted,
|
|
1072
|
+
jobsDeleted
|
|
1073
|
+
};
|
|
1074
|
+
})
|
|
1075
|
+
};
|
|
1076
|
+
}));
|
|
1077
|
+
|
|
1078
|
+
|
|
1079
|
+
import { Effect as Effect10, Layer as Layer10 } from "effect";
|
|
1080
|
+
var draftStateMatches = (state) => {
|
|
1081
|
+
const expectedJson = JSON.stringify(state);
|
|
1082
|
+
return sql`
|
|
1083
|
+
NOT EXISTS (
|
|
1084
|
+
SELECT 1 FROM json_tree(${processState.state}) AS actual
|
|
1085
|
+
WHERE NOT EXISTS (
|
|
1086
|
+
SELECT 1 FROM json_tree(${expectedJson}) AS expected
|
|
1087
|
+
WHERE expected.fullkey = actual.fullkey
|
|
1088
|
+
AND expected.type = actual.type
|
|
1089
|
+
AND expected.atom IS actual.atom
|
|
1090
|
+
)
|
|
1091
|
+
)
|
|
1092
|
+
AND NOT EXISTS (
|
|
1093
|
+
SELECT 1 FROM json_tree(${expectedJson}) AS expected
|
|
1094
|
+
WHERE NOT EXISTS (
|
|
1095
|
+
SELECT 1 FROM json_tree(${processState.state}) AS actual
|
|
1096
|
+
WHERE actual.fullkey = expected.fullkey
|
|
1097
|
+
AND actual.type = expected.type
|
|
1098
|
+
AND actual.atom IS expected.atom
|
|
1099
|
+
)
|
|
1100
|
+
)
|
|
1101
|
+
`;
|
|
1102
|
+
};
|
|
1103
|
+
var SqliteDraftProcessExecutionQueriesLive = Layer10.effect(DraftProcessExecutionQueries, Effect10.gen(function* () {
|
|
1104
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1105
|
+
const isDraft = notExists(db.select({ one: sql`1` }).from(processExecution).where(and(eq(processExecution.processStateId, processState.id), eq(processExecution._deleted, sql`0`))));
|
|
1106
|
+
return {
|
|
1107
|
+
pullDraftProcessExecution: (checkpoint, limit) => Effect10.gen(function* () {
|
|
1108
|
+
const userDetails = yield* getUserDetails();
|
|
1109
|
+
if (!userDetails.id)
|
|
1110
|
+
return [];
|
|
1111
|
+
const conditions = [
|
|
1112
|
+
isDraft,
|
|
1113
|
+
eq(processState.startedByUserId, userDetails.id)
|
|
1114
|
+
];
|
|
1115
|
+
if (checkpoint) {
|
|
1116
|
+
const updatedAtMillis = sql`CAST(ROUND((${processState.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;
|
|
1117
|
+
const checkpointFilter = or(gt(updatedAtMillis, checkpoint.updatedAt), and(eq(updatedAtMillis, checkpoint.updatedAt), gt(processState.id, checkpoint.id)));
|
|
1118
|
+
if (checkpointFilter) {
|
|
1119
|
+
conditions.push(checkpointFilter);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
const rows = yield* db.select({
|
|
1123
|
+
id: processState.id,
|
|
1124
|
+
processId: processState.processId,
|
|
1125
|
+
startStepId: processState.startStepId,
|
|
1126
|
+
startedByUserId: processState.startedByUserId,
|
|
1127
|
+
startedByEmail: providerUser.email,
|
|
1128
|
+
name: process2.name,
|
|
1129
|
+
startStepPath: step.path,
|
|
1130
|
+
state: processState.state,
|
|
1131
|
+
lastSaved: processState.updatedAt,
|
|
1132
|
+
updatedAt: sql`CAST(ROUND((${processState.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),
|
|
1133
|
+
deleted: processState._deleted
|
|
1134
|
+
}).from(processState).innerJoin(process2, eq(processState.processId, process2.id)).innerJoin(step, eq(processState.startStepId, step.id)).leftJoin(providerUser, and(eq(processState.startedByUserId, providerUser.userId), eq(providerUser._deleted, sql`0`))).where(and(...conditions)).orderBy(processState.updatedAt, processState.id).limit(limit);
|
|
1135
|
+
return rows.map((row) => ({
|
|
1136
|
+
...row,
|
|
1137
|
+
state: row.state
|
|
1138
|
+
}));
|
|
1139
|
+
}),
|
|
1140
|
+
insertProcessState: (processStateId, processId, startStepPath, state) => Effect10.gen(function* () {
|
|
1141
|
+
const requestTime = yield* getRequestTime();
|
|
1142
|
+
const userDetails = yield* getUserDetails();
|
|
1143
|
+
const stepResult = yield* db.select({ id: step.id }).from(step).where(and(eq(step.path, startStepPath), eq(step.processId, processId), eq(step._deleted, false))).limit(1);
|
|
1144
|
+
const stepRow = stepResult[0];
|
|
1145
|
+
if (!stepRow) {
|
|
1146
|
+
return yield* new StepNotFoundError({
|
|
1147
|
+
path: startStepPath,
|
|
1148
|
+
message: `Step not found for path: ${startStepPath}`
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
const inserted = yield* db.insert(processState).values({
|
|
1152
|
+
id: processStateId,
|
|
1153
|
+
processId,
|
|
1154
|
+
startStepId: stepRow.id,
|
|
1155
|
+
state,
|
|
1156
|
+
startedByUserId: userDetails.id,
|
|
1157
|
+
createdAt: requestTime,
|
|
1158
|
+
updatedAt: requestTime,
|
|
1159
|
+
createdBy: userDetails.by,
|
|
1160
|
+
updatedBy: userDetails.by
|
|
1161
|
+
}).onConflictDoNothing({ target: processState.id }).returning({ id: processState.id });
|
|
1162
|
+
if (inserted.length === 0) {
|
|
1163
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1164
|
+
processStateId,
|
|
1165
|
+
message: `Draft process execution already exists: ${processStateId}`
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
return processStateId;
|
|
1169
|
+
}),
|
|
1170
|
+
updateProcessState: (processStateId, state, assumedMasterState) => Effect10.gen(function* () {
|
|
1171
|
+
const requestTime = yield* getRequestTime();
|
|
1172
|
+
const userDetails = yield* getUserDetails();
|
|
1173
|
+
if (assumedMasterState.id !== processStateId) {
|
|
1174
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1175
|
+
processStateId,
|
|
1176
|
+
message: "Assumed master state targets a different document"
|
|
1177
|
+
});
|
|
1178
|
+
}
|
|
1179
|
+
const userId = userDetails.id;
|
|
1180
|
+
if (!userId) {
|
|
1181
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1182
|
+
processStateId,
|
|
1183
|
+
message: "Draft process execution requires a persisted user owner"
|
|
1184
|
+
});
|
|
1185
|
+
}
|
|
1186
|
+
if (assumedMasterState.deleted) {
|
|
1187
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1188
|
+
processStateId,
|
|
1189
|
+
message: `Cannot update deleted process execution state: ${processStateId}`
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
const persistedUpdatedAt = sql`CAST(ROUND((${processState.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;
|
|
1193
|
+
const result = yield* db.update(processState).set({
|
|
1194
|
+
state,
|
|
1195
|
+
updatedAt: requestTime,
|
|
1196
|
+
updatedBy: userDetails.by,
|
|
1197
|
+
_deleted: false
|
|
1198
|
+
}).where(and(eq(processState.id, processStateId), eq(processState.processId, assumedMasterState.processId), draftStateMatches(assumedMasterState.state), eq(processState._deleted, false), eq(persistedUpdatedAt, Math.round(assumedMasterState.updatedAt)), eq(processState.startedByUserId, userId), isDraft)).returning({ id: processState.id });
|
|
1199
|
+
if (result.length === 0) {
|
|
1200
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1201
|
+
processStateId,
|
|
1202
|
+
message: `Cannot update deleted process execution state: ${processStateId}`
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
return processStateId;
|
|
1206
|
+
}),
|
|
1207
|
+
deleteProcessState: (processStateId, assumedMasterState) => Effect10.gen(function* () {
|
|
1208
|
+
const requestTime = yield* getRequestTime();
|
|
1209
|
+
const userDetails = yield* getUserDetails();
|
|
1210
|
+
if (assumedMasterState.id !== processStateId) {
|
|
1211
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1212
|
+
processStateId,
|
|
1213
|
+
message: "Assumed master state targets a different document"
|
|
1214
|
+
});
|
|
1215
|
+
}
|
|
1216
|
+
const userId = userDetails.id;
|
|
1217
|
+
if (!userId) {
|
|
1218
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1219
|
+
processStateId,
|
|
1220
|
+
message: "Draft process execution requires a persisted user owner"
|
|
1221
|
+
});
|
|
1222
|
+
}
|
|
1223
|
+
if (assumedMasterState.deleted) {
|
|
1224
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1225
|
+
processStateId,
|
|
1226
|
+
message: `Cannot delete from a deleted assumed master state: ${processStateId}`
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
const persistedUpdatedAt = sql`CAST(ROUND((${processState.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;
|
|
1230
|
+
const result = yield* db.update(processState).set({
|
|
1231
|
+
_deleted: true,
|
|
1232
|
+
updatedAt: requestTime,
|
|
1233
|
+
updatedBy: userDetails.by
|
|
1234
|
+
}).where(and(eq(processState.id, processStateId), eq(processState.processId, assumedMasterState.processId), draftStateMatches(assumedMasterState.state), eq(processState._deleted, false), eq(persistedUpdatedAt, Math.round(assumedMasterState.updatedAt)), eq(processState.startedByUserId, userId), isDraft)).returning({ id: processState.id });
|
|
1235
|
+
if (result.length === 0) {
|
|
1236
|
+
return yield* new UpdateDeletedDocumentError({
|
|
1237
|
+
processStateId,
|
|
1238
|
+
message: `Cannot delete inaccessible, changed, or non-draft process execution state: ${processStateId}`
|
|
1239
|
+
});
|
|
1240
|
+
}
|
|
1241
|
+
return processStateId;
|
|
1242
|
+
}),
|
|
1243
|
+
getProcessStates: (processStateIds) => Effect10.gen(function* () {
|
|
1244
|
+
const userDetails = yield* getUserDetails();
|
|
1245
|
+
if (!userDetails.id || processStateIds.length === 0)
|
|
1246
|
+
return [];
|
|
1247
|
+
const rows = yield* db.select({
|
|
1248
|
+
id: processState.id,
|
|
1249
|
+
processId: processState.processId,
|
|
1250
|
+
startStepId: processState.startStepId,
|
|
1251
|
+
startedByUserId: processState.startedByUserId,
|
|
1252
|
+
startedByEmail: providerUser.email,
|
|
1253
|
+
name: process2.name,
|
|
1254
|
+
startStepPath: step.path,
|
|
1255
|
+
state: processState.state,
|
|
1256
|
+
lastSaved: processState.updatedAt,
|
|
1257
|
+
updatedAt: sql`CAST(ROUND((${processState.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),
|
|
1258
|
+
deleted: processState._deleted
|
|
1259
|
+
}).from(processState).innerJoin(process2, eq(processState.processId, process2.id)).innerJoin(step, eq(processState.startStepId, step.id)).leftJoin(providerUser, and(eq(processState.startedByUserId, providerUser.userId), eq(providerUser._deleted, sql`0`))).where(and(inArray(processState.id, processStateIds), isDraft, eq(processState.startedByUserId, userDetails.id))).orderBy(processState.updatedAt, processState.id);
|
|
1260
|
+
return rows.map((row) => ({
|
|
1261
|
+
...row,
|
|
1262
|
+
state: row.state
|
|
1263
|
+
}));
|
|
1264
|
+
})
|
|
1265
|
+
};
|
|
1266
|
+
}));
|
|
1267
|
+
|
|
1268
|
+
|
|
1269
|
+
import { Effect as Effect11, Layer as Layer11 } from "effect";
|
|
1270
|
+
var SqliteProcessExecutionOperationsLive = Layer11.effect(ProcessExecutionOperations, Effect11.gen(function* () {
|
|
1271
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1272
|
+
return {
|
|
1273
|
+
insertProcessState: (processId, startStepPath, state, startedByExternalParticipantId, startedByRoleId) => Effect11.gen(function* () {
|
|
1274
|
+
const requestTime = yield* getRequestTime();
|
|
1275
|
+
const userDetails = yield* getUserDetails();
|
|
1276
|
+
const stepResult = yield* db.select({ id: step.id }).from(step).where(and(eq(step.path, startStepPath), eq(step._deleted, false))).limit(1);
|
|
1277
|
+
const stepRow = stepResult[0];
|
|
1278
|
+
if (!stepRow) {
|
|
1279
|
+
return yield* new StepNotFoundError({
|
|
1280
|
+
path: startStepPath,
|
|
1281
|
+
message: `Step not found for path: ${startStepPath}`
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
const result = yield* db.insert(processState).values({
|
|
1285
|
+
processId,
|
|
1286
|
+
startStepId: stepRow.id,
|
|
1287
|
+
state,
|
|
1288
|
+
startedByUserId: startedByExternalParticipantId === undefined ? userDetails.id : null,
|
|
1289
|
+
...startedByExternalParticipantId !== undefined ? { startedByExternalParticipantId } : {},
|
|
1290
|
+
...startedByRoleId !== undefined ? { startedByRoleId } : {},
|
|
1291
|
+
createdAt: requestTime,
|
|
1292
|
+
updatedAt: requestTime,
|
|
1293
|
+
createdBy: userDetails.by,
|
|
1294
|
+
updatedBy: userDetails.by
|
|
1295
|
+
}).returning({ id: processState.id });
|
|
1296
|
+
const row = yield* returnedRow(result);
|
|
1297
|
+
return { processStateId: row.id, stepId: stepRow.id };
|
|
1298
|
+
}),
|
|
1299
|
+
insertProcessExecution: (processStateId, executionId, withoutWaiting = false) => Effect11.gen(function* () {
|
|
1300
|
+
const requestTime = yield* getRequestTime();
|
|
1301
|
+
const userDetails = yield* getUserDetails();
|
|
1302
|
+
const result = yield* db.insert(processExecution).values({
|
|
1303
|
+
...executionId !== undefined ? { id: executionId } : {},
|
|
1304
|
+
processStateId,
|
|
1305
|
+
withoutWaiting,
|
|
1306
|
+
createdAt: requestTime,
|
|
1307
|
+
updatedAt: requestTime,
|
|
1308
|
+
createdBy: userDetails.by,
|
|
1309
|
+
updatedBy: userDetails.by
|
|
1310
|
+
}).returning({ id: processExecution.id });
|
|
1311
|
+
return (yield* returnedRow(result)).id;
|
|
1312
|
+
}),
|
|
1313
|
+
getProcessExecutionStartInfo: (executionId) => Effect11.gen(function* () {
|
|
1314
|
+
const result = yield* db.select({
|
|
1315
|
+
executionId: processExecution.id,
|
|
1316
|
+
withoutWaiting: processExecution.withoutWaiting,
|
|
1317
|
+
processId: processState.processId,
|
|
1318
|
+
stepId: step.id,
|
|
1319
|
+
startStepPath: step.path,
|
|
1320
|
+
state: processState.state
|
|
1321
|
+
}).from(processExecution).innerJoin(processState, and(eq(processExecution.processStateId, processState.id), eq(processState._deleted, false))).innerJoin(step, and(eq(processState.startStepId, step.id), eq(step._deleted, false))).where(and(eq(processExecution.id, executionId), eq(processExecution._deleted, false))).limit(1);
|
|
1322
|
+
const row = result[0];
|
|
1323
|
+
if (!row) {
|
|
1324
|
+
return null;
|
|
1325
|
+
}
|
|
1326
|
+
return {
|
|
1327
|
+
executionId: row.executionId,
|
|
1328
|
+
withoutWaiting: row.withoutWaiting,
|
|
1329
|
+
processId: row.processId,
|
|
1330
|
+
stepId: row.stepId,
|
|
1331
|
+
startStepPath: row.startStepPath,
|
|
1332
|
+
state: row.state
|
|
1333
|
+
};
|
|
1334
|
+
})
|
|
1335
|
+
};
|
|
1336
|
+
}));
|
|
1337
|
+
|
|
1338
|
+
|
|
1339
|
+
import { Effect as Effect12, Layer as Layer12 } from "effect";
|
|
1340
|
+
var SqliteFlowQueriesLive = Layer12.effect(FlowQueries, Effect12.gen(function* () {
|
|
1341
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1342
|
+
return {
|
|
1343
|
+
queryFlowsBySourceStepId: (stepId) => db.select({
|
|
1344
|
+
id: flow.id,
|
|
1345
|
+
sourceStepId: flow.sourceStepId,
|
|
1346
|
+
targetStepId: flow.targetStepId
|
|
1347
|
+
}).from(flow).where(and(eq(flow.sourceStepId, stepId), eq(flow._deleted, false)))
|
|
1348
|
+
};
|
|
1349
|
+
}));
|
|
1350
|
+
|
|
1351
|
+
|
|
1352
|
+
import { Effect as Effect13, Layer as Layer13, Option } from "effect";
|
|
1353
|
+
var SqliteOAuthClientQueriesLive = Layer13.effect(OAuthClientQueries, Effect13.gen(function* () {
|
|
1354
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1355
|
+
return {
|
|
1356
|
+
queryOAuthClientByClientId: (clientId) => Effect13.gen(function* () {
|
|
1357
|
+
const results = yield* db.query.oauthClient.findMany({
|
|
1358
|
+
where: { clientId, _deleted: false }
|
|
1359
|
+
});
|
|
1360
|
+
if (results.length && results[0]) {
|
|
1361
|
+
const result = results[0];
|
|
1362
|
+
const row = {
|
|
1363
|
+
id: result.id,
|
|
1364
|
+
clientId: result.clientId
|
|
1365
|
+
};
|
|
1366
|
+
return Option.some(row);
|
|
1367
|
+
}
|
|
1368
|
+
return Option.none();
|
|
1369
|
+
}),
|
|
1370
|
+
addPermittedClientRole: (oauthClientId, roleId) => db.insert(permittedClientRole).values({
|
|
1371
|
+
oauthClientId,
|
|
1372
|
+
roleId
|
|
1373
|
+
}).onConflictDoUpdate({
|
|
1374
|
+
target: [
|
|
1375
|
+
permittedClientRole.oauthClientId,
|
|
1376
|
+
permittedClientRole.roleId
|
|
1377
|
+
],
|
|
1378
|
+
targetWhere: sql`_deleted = 0`,
|
|
1379
|
+
set: { updatedAt: sql`julianday('now')` }
|
|
1380
|
+
})
|
|
1381
|
+
};
|
|
1382
|
+
}));
|
|
1383
|
+
|
|
1384
|
+
|
|
1385
|
+
import { Effect as Effect14, Layer as Layer14 } from "effect";
|
|
1386
|
+
var computeOrgLevelsFromUnits = (units) => {
|
|
1387
|
+
const childrenByParentId = new Map;
|
|
1388
|
+
const roots = [];
|
|
1389
|
+
for (const unit of units) {
|
|
1390
|
+
if (unit.parentOrgUnitId === null) {
|
|
1391
|
+
roots.push(unit);
|
|
1392
|
+
continue;
|
|
1393
|
+
}
|
|
1394
|
+
const siblings = childrenByParentId.get(unit.parentOrgUnitId);
|
|
1395
|
+
if (siblings === undefined) {
|
|
1396
|
+
childrenByParentId.set(unit.parentOrgUnitId, [unit]);
|
|
1397
|
+
} else {
|
|
1398
|
+
siblings.push(unit);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
const maxDepthByLevel = new Map;
|
|
1402
|
+
const visited = new Set;
|
|
1403
|
+
const queue = [];
|
|
1404
|
+
for (const root of roots) {
|
|
1405
|
+
visited.add(root.id);
|
|
1406
|
+
queue.push({ unit: root, depth: 1 });
|
|
1407
|
+
}
|
|
1408
|
+
for (let index = 0;index < queue.length; index++) {
|
|
1409
|
+
const current = queue[index];
|
|
1410
|
+
if (current === undefined) {
|
|
1411
|
+
break;
|
|
1412
|
+
}
|
|
1413
|
+
const { unit, depth } = current;
|
|
1414
|
+
const previousMax = maxDepthByLevel.get(unit.orgUnitLevel);
|
|
1415
|
+
if (previousMax === undefined || depth > previousMax) {
|
|
1416
|
+
maxDepthByLevel.set(unit.orgUnitLevel, depth);
|
|
1417
|
+
}
|
|
1418
|
+
for (const child of childrenByParentId.get(unit.id) ?? []) {
|
|
1419
|
+
if (visited.has(child.id)) {
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
visited.add(child.id);
|
|
1423
|
+
queue.push({ unit: child, depth: depth + 1 });
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
return Array.from(maxDepthByLevel.entries()).map(([level, maxDepth]) => ({ level, maxDepth })).sort((a, b) => a.maxDepth - b.maxDepth);
|
|
1427
|
+
};
|
|
1428
|
+
var SqliteOrgQueriesLive = Layer14.effect(OrgQueries, Effect14.gen(function* () {
|
|
1429
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1430
|
+
return {
|
|
1431
|
+
queryRoot: Effect14.gen(function* () {
|
|
1432
|
+
const results = yield* db.select().from(orgUnit).where(and(isNull(orgUnit.parentOrgUnitId), not(orgUnit._deleted))).limit(1);
|
|
1433
|
+
return results[0] ?? null;
|
|
1434
|
+
}),
|
|
1435
|
+
queryChildren: (parentId) => db.select().from(orgUnit).where(and(eq(orgUnit.parentOrgUnitId, parentId), not(orgUnit._deleted))),
|
|
1436
|
+
queryProcesses: (orgUnitId) => db.select().from(process2).where(and(eq(process2.orgUnitId, orgUnitId), eq(process2._deleted, false))),
|
|
1437
|
+
queryRoles: (orgUnitId) => db.select().from(role).where(and(eq(role.orgUnitId, orgUnitId), eq(role._deleted, false))),
|
|
1438
|
+
queryOrgLevels: Effect14.gen(function* () {
|
|
1439
|
+
const units = yield* db.select({
|
|
1440
|
+
id: orgUnit.id,
|
|
1441
|
+
parentOrgUnitId: orgUnit.parentOrgUnitId,
|
|
1442
|
+
orgUnitLevel: orgUnit.orgUnitLevel
|
|
1443
|
+
}).from(orgUnit).where(not(orgUnit._deleted));
|
|
1444
|
+
return computeOrgLevelsFromUnits(units);
|
|
1445
|
+
})
|
|
1446
|
+
};
|
|
1447
|
+
}));
|
|
1448
|
+
|
|
1449
|
+
|
|
1450
|
+
import { DateTime as DateTime2, Effect as Effect15, Layer as Layer15 } from "effect";
|
|
1451
|
+
var queryStartStepId = (db) => {
|
|
1452
|
+
const startStep = alias(step, "start_step");
|
|
1453
|
+
return db.select({ id: startStep.id }).from(startStep).where(and(eq(startStep.processId, process2.id), eq(startStep._deleted, sql`0`), notExists(db.select({ id: flow.id }).from(flow).where(and(eq(flow.targetStepId, startStep.id), eq(flow._deleted, sql`0`)))))).limit(1);
|
|
1454
|
+
};
|
|
1455
|
+
var SqliteProcessQueriesLive = Layer15.effect(ProcessQueries, Effect15.gen(function* () {
|
|
1456
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1457
|
+
const startStepId = queryStartStepId(db);
|
|
1458
|
+
const activeInstanceCount = db.select({ count: countDistinct(toDo.id) }).from(processState).innerJoin(processExecution, eq(processExecution.processStateId, processState.id)).innerJoin(toDo, eq(toDo.processExecutionId, processExecution.id)).where(and(eq(processState.processId, process2.id), eq(processState._deleted, sql`0`), eq(processExecution._deleted, sql`0`), eq(toDo._deleted, sql`0`)));
|
|
1459
|
+
return {
|
|
1460
|
+
queryAllProcesses: Effect15.gen(function* () {
|
|
1461
|
+
const dbProcesses = yield* db.query.process.findMany({
|
|
1462
|
+
columns: {
|
|
1463
|
+
id: true,
|
|
1464
|
+
name: true,
|
|
1465
|
+
path: true,
|
|
1466
|
+
purpose: true,
|
|
1467
|
+
orgUnitId: true
|
|
1468
|
+
},
|
|
1469
|
+
where: { _deleted: false },
|
|
1470
|
+
with: {
|
|
1471
|
+
orgUnit: {
|
|
1472
|
+
columns: {
|
|
1473
|
+
id: true,
|
|
1474
|
+
name: true,
|
|
1475
|
+
orgUnitLevel: true
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
}).pipe(retryTransientSqliteError);
|
|
1480
|
+
return dbProcesses;
|
|
1481
|
+
}),
|
|
1482
|
+
listProcesses: (query) => Effect15.gen(function* () {
|
|
1483
|
+
const conditions = [eq(process2._deleted, sql`0`)];
|
|
1484
|
+
if (query.processPath != null) {
|
|
1485
|
+
conditions.push(eq(process2.path, query.processPath));
|
|
1486
|
+
}
|
|
1487
|
+
const rows = yield* db.select({
|
|
1488
|
+
id: process2.id,
|
|
1489
|
+
path: process2.path,
|
|
1490
|
+
name: process2.name,
|
|
1491
|
+
category: orgUnit.name,
|
|
1492
|
+
purpose: process2.purpose,
|
|
1493
|
+
startStepPath: step.path,
|
|
1494
|
+
activeInstances: sql`(${activeInstanceCount})`.mapWith(Number)
|
|
1495
|
+
}).from(process2).innerJoin(orgUnit, eq(process2.orgUnitId, orgUnit.id)).innerJoin(step, eq(step.id, startStepId)).where(and(...conditions)).orderBy(process2.path, process2.id).limit(query.limit).offset(query.offset);
|
|
1496
|
+
return rows.map((row) => ({
|
|
1497
|
+
...row,
|
|
1498
|
+
activeInstances: row.activeInstances ?? 0
|
|
1499
|
+
}));
|
|
1500
|
+
}).pipe(retryTransientSqliteError)
|
|
1501
|
+
};
|
|
1502
|
+
}));
|
|
1503
|
+
var SqliteProcessCollectionQueriesLive = Layer15.effect(ProcessCollectionQueries, Effect15.gen(function* () {
|
|
1504
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1505
|
+
const startStepId = queryStartStepId(db);
|
|
1506
|
+
const metadataFields = {
|
|
1507
|
+
id: process2.id,
|
|
1508
|
+
name: process2.name,
|
|
1509
|
+
path: process2.path,
|
|
1510
|
+
purpose: process2.purpose,
|
|
1511
|
+
updatedAt: sql`CAST(ROUND((${process2.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`.as("updated_at_millis"),
|
|
1512
|
+
deleted: process2._deleted,
|
|
1513
|
+
orgUnitId: orgUnit.id,
|
|
1514
|
+
orgUnitName: orgUnit.name,
|
|
1515
|
+
orgUnitLevel: orgUnit.orgUnitLevel,
|
|
1516
|
+
startStepPath: step.path,
|
|
1517
|
+
formFieldCount: step.formFields
|
|
1518
|
+
};
|
|
1519
|
+
const queryProcesses = (whereClause, limit, ids) => Effect15.gen(function* () {
|
|
1520
|
+
const processStateFilter = and(ids === undefined ? undefined : inArray(processState.processId, ids), eq(processState._deleted, sql`0`), eq(processExecution._deleted, sql`0`));
|
|
1521
|
+
const activeProcesses = db.$with("active_processes").as(db.select({
|
|
1522
|
+
processId: processState.processId,
|
|
1523
|
+
activeProcesses: countDistinct(toDo.id).as("active_processes")
|
|
1524
|
+
}).from(processState).innerJoin(processExecution, eq(processExecution.processStateId, processState.id)).innerJoin(toDo, eq(toDo.processExecutionId, processExecution.id)).where(and(processStateFilter, eq(toDo._deleted, sql`0`))).groupBy(processState.processId));
|
|
1525
|
+
const durationStats = db.$with("duration_stats").as(db.select({
|
|
1526
|
+
processId: processState.processId,
|
|
1527
|
+
minDurationMs: sql`MIN((${processExecution.finishedAt} - ${processExecution.createdAt}) * 86400000)`.as("min_duration_ms"),
|
|
1528
|
+
maxDurationMs: sql`MAX((${processExecution.finishedAt} - ${processExecution.createdAt}) * 86400000)`.as("max_duration_ms")
|
|
1529
|
+
}).from(processState).innerJoin(processExecution, eq(processExecution.processStateId, processState.id)).where(and(isNotNull(processExecution.finishedAt), processStateFilter)).groupBy(processState.processId));
|
|
1530
|
+
const baseQuery = db.with(activeProcesses, durationStats).select({
|
|
1531
|
+
...metadataFields,
|
|
1532
|
+
activeInstances: activeProcesses.activeProcesses,
|
|
1533
|
+
minDurationMs: durationStats.minDurationMs,
|
|
1534
|
+
maxDurationMs: durationStats.maxDurationMs
|
|
1535
|
+
}).from(process2).innerJoin(orgUnit, eq(process2.orgUnitId, orgUnit.id)).leftJoin(step, eq(step.id, startStepId)).leftJoin(activeProcesses, eq(process2.id, activeProcesses.processId)).leftJoin(durationStats, eq(process2.id, durationStats.processId)).where(whereClause).orderBy(sql`updated_at_millis`, process2.id);
|
|
1536
|
+
const query = limit !== undefined ? baseQuery.limit(limit) : baseQuery;
|
|
1537
|
+
const rows = yield* query;
|
|
1538
|
+
return rows.map((row) => ({
|
|
1539
|
+
id: row.id,
|
|
1540
|
+
name: row.name,
|
|
1541
|
+
path: row.path,
|
|
1542
|
+
purpose: row.purpose,
|
|
1543
|
+
updatedAt: row.updatedAt,
|
|
1544
|
+
deleted: row.deleted,
|
|
1545
|
+
orgUnit: {
|
|
1546
|
+
id: row.orgUnitId,
|
|
1547
|
+
name: row.orgUnitName,
|
|
1548
|
+
orgUnitLevel: row.orgUnitLevel
|
|
1549
|
+
},
|
|
1550
|
+
startStepPath: row.startStepPath ?? "",
|
|
1551
|
+
formFieldCount: row.formFieldCount ?? 0,
|
|
1552
|
+
activeInstances: row.activeInstances ?? 0,
|
|
1553
|
+
minDurationMs: row.minDurationMs,
|
|
1554
|
+
maxDurationMs: row.maxDurationMs
|
|
1555
|
+
}));
|
|
1556
|
+
});
|
|
1557
|
+
const buildCheckpointFilter = (checkpoint) => {
|
|
1558
|
+
if (!checkpoint)
|
|
1559
|
+
return;
|
|
1560
|
+
const updatedAtMillis = sql`CAST(ROUND((${process2.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;
|
|
1561
|
+
return or(gt(updatedAtMillis, checkpoint.updatedAt), and(eq(updatedAtMillis, checkpoint.updatedAt), gt(process2.id, checkpoint.id)));
|
|
1562
|
+
};
|
|
1563
|
+
return {
|
|
1564
|
+
advanceProcessRevision: (id) => Effect15.gen(function* () {
|
|
1565
|
+
const rows = yield* db.select({
|
|
1566
|
+
latest: sql`CAST(ROUND((MAX(${process2.updatedAt}) - 2440587.5) * 86400000) AS INTEGER)`
|
|
1567
|
+
}).from(process2);
|
|
1568
|
+
yield* db.update(process2).set({
|
|
1569
|
+
updatedAt: DateTime2.makeUnsafe(Number(rows[0]?.latest ?? 0) + 1)
|
|
1570
|
+
}).where(eq(process2.id, id));
|
|
1571
|
+
}),
|
|
1572
|
+
observeProcesses: (scope, ids) => ids.length === 0 ? Effect15.void : db.insert(processVisibility).values(ids.map((processId) => ({
|
|
1573
|
+
processId,
|
|
1574
|
+
replicationScope: scope
|
|
1575
|
+
}))).onConflictDoNothing().pipe(Effect15.asVoid),
|
|
1576
|
+
getObservedProcessIds: (scope, ids) => ids.length === 0 ? Effect15.succeed([]) : db.select({ id: processVisibility.processId }).from(processVisibility).where(and(eq(processVisibility.replicationScope, scope), inArray(processVisibility.processId, [...ids]), eq(processVisibility._deleted, sql`0`))).pipe(Effect15.map((rows) => rows.map((row) => row.id))),
|
|
1577
|
+
pullProcess: (checkpoint, limit) => queryProcesses(buildCheckpointFilter(checkpoint), limit),
|
|
1578
|
+
getProcessMetadata: (ids) => ids.length === 0 ? Effect15.succeed([]) : db.select(metadataFields).from(process2).innerJoin(orgUnit, eq(process2.orgUnitId, orgUnit.id)).leftJoin(step, eq(step.id, startStepId)).where(inArray(process2.id, ids)).orderBy(sql`updated_at_millis`, process2.id).pipe(Effect15.map((rows) => rows.map((row) => ({
|
|
1579
|
+
id: row.id,
|
|
1580
|
+
name: row.name,
|
|
1581
|
+
path: row.path,
|
|
1582
|
+
purpose: row.purpose,
|
|
1583
|
+
updatedAt: row.updatedAt,
|
|
1584
|
+
deleted: row.deleted,
|
|
1585
|
+
orgUnit: {
|
|
1586
|
+
id: row.orgUnitId,
|
|
1587
|
+
name: row.orgUnitName,
|
|
1588
|
+
orgUnitLevel: row.orgUnitLevel
|
|
1589
|
+
},
|
|
1590
|
+
startStepPath: row.startStepPath ?? "",
|
|
1591
|
+
formFieldCount: row.formFieldCount ?? 0
|
|
1592
|
+
})))),
|
|
1593
|
+
getProcesses: (ids) => ids.length === 0 ? Effect15.succeed([]) : queryProcesses(inArray(process2.id, ids), undefined, ids)
|
|
1594
|
+
};
|
|
1595
|
+
}));
|
|
1596
|
+
|
|
1597
|
+
|
|
1598
|
+
import { DateTime as DateTime3, Effect as Effect16, Layer as Layer16, Option as Option2 } from "effect";
|
|
1599
|
+
var mapToProviderUserRow = (result) => ({
|
|
1600
|
+
id: result.id,
|
|
1601
|
+
userId: result.user.id,
|
|
1602
|
+
email: result.email,
|
|
1603
|
+
name: result.name,
|
|
1604
|
+
firstName: result.firstName,
|
|
1605
|
+
lastName: result.lastName,
|
|
1606
|
+
picture: result.picture,
|
|
1607
|
+
locale: result.locale,
|
|
1608
|
+
provider: result.user.provider,
|
|
1609
|
+
sub: result.user.sub,
|
|
1610
|
+
orgUnitId: result.orgUnitId,
|
|
1611
|
+
orgUnitPath: result.orgUnit.path,
|
|
1612
|
+
createdAt: DateTime3.toDateUtc(result.createdAt),
|
|
1613
|
+
updatedAt: DateTime3.toDateUtc(result.updatedAt),
|
|
1614
|
+
createdBy: result.createdBy,
|
|
1615
|
+
updatedBy: result.updatedBy
|
|
1616
|
+
});
|
|
1617
|
+
var escapeLikePattern = (value) => value.replace(/[\\%_]/g, "\\$&");
|
|
1618
|
+
var SqliteProviderUserQueriesLive = Layer16.effect(ProviderUserQueries, Effect16.gen(function* () {
|
|
1619
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1620
|
+
return {
|
|
1621
|
+
queryProviderUserByUserId: (id) => Effect16.gen(function* () {
|
|
1622
|
+
const results = yield* db.query.providerUser.findMany({
|
|
1623
|
+
with: {
|
|
1624
|
+
user: true,
|
|
1625
|
+
orgUnit: true
|
|
1626
|
+
},
|
|
1627
|
+
where: { userId: id }
|
|
1628
|
+
});
|
|
1629
|
+
if (results.length && results[0]) {
|
|
1630
|
+
return Option2.some(mapToProviderUserRow(results[0]));
|
|
1631
|
+
} else {
|
|
1632
|
+
return Option2.none();
|
|
1633
|
+
}
|
|
1634
|
+
}),
|
|
1635
|
+
queryProviderUserByProviderUserId: (id) => Effect16.gen(function* () {
|
|
1636
|
+
const results = yield* db.query.providerUser.findMany({
|
|
1637
|
+
with: {
|
|
1638
|
+
user: true,
|
|
1639
|
+
orgUnit: true
|
|
1640
|
+
},
|
|
1641
|
+
where: { id }
|
|
1642
|
+
});
|
|
1643
|
+
if (results.length && results[0]) {
|
|
1644
|
+
return Option2.some(mapToProviderUserRow(results[0]));
|
|
1645
|
+
} else {
|
|
1646
|
+
return Option2.none();
|
|
1647
|
+
}
|
|
1648
|
+
}),
|
|
1649
|
+
queryProviderUserByEmail: (email) => Effect16.gen(function* () {
|
|
1650
|
+
const normalizedEmail = email.trim().toLowerCase();
|
|
1651
|
+
const results = yield* db.select({
|
|
1652
|
+
providerUser,
|
|
1653
|
+
user,
|
|
1654
|
+
orgUnit
|
|
1655
|
+
}).from(providerUser).innerJoin(user, eq(providerUser.userId, user.id)).innerJoin(orgUnit, eq(providerUser.orgUnitId, orgUnit.id)).where(and(sql`lower(${providerUser.email}) = ${normalizedEmail}`, eq(providerUser._deleted, false), eq(user._deleted, false), eq(orgUnit._deleted, false))).limit(1);
|
|
1656
|
+
const row = results[0];
|
|
1657
|
+
if (!row) {
|
|
1658
|
+
return Option2.none();
|
|
1659
|
+
}
|
|
1660
|
+
return Option2.some(mapToProviderUserRow({
|
|
1661
|
+
...row.providerUser,
|
|
1662
|
+
user: row.user,
|
|
1663
|
+
orgUnit: row.orgUnit
|
|
1664
|
+
}));
|
|
1665
|
+
}),
|
|
1666
|
+
queryProviderUsers: (filter, options) => Effect16.gen(function* () {
|
|
1667
|
+
const trimmed = filter.trim();
|
|
1668
|
+
if (options.limit <= 0)
|
|
1669
|
+
return [];
|
|
1670
|
+
const results = yield* db.query.providerUser.findMany({
|
|
1671
|
+
with: {
|
|
1672
|
+
user: true,
|
|
1673
|
+
orgUnit: true
|
|
1674
|
+
},
|
|
1675
|
+
where: trimmed.length === 0 ? { _deleted: false } : {
|
|
1676
|
+
_deleted: false,
|
|
1677
|
+
OR: [
|
|
1678
|
+
{
|
|
1679
|
+
RAW: (providerUser2) => sql`${providerUser2.name} like ${`%${escapeLikePattern(trimmed)}%`} escape ${"\\"}`
|
|
1680
|
+
},
|
|
1681
|
+
{
|
|
1682
|
+
RAW: (providerUser2) => sql`${providerUser2.email} like ${`%${escapeLikePattern(trimmed)}%`} escape ${"\\"}`
|
|
1683
|
+
}
|
|
1684
|
+
]
|
|
1685
|
+
},
|
|
1686
|
+
orderBy: { name: "asc", email: "asc" },
|
|
1687
|
+
limit: options.limit,
|
|
1688
|
+
offset: options.offset
|
|
1689
|
+
});
|
|
1690
|
+
return results.map(mapToProviderUserRow);
|
|
1691
|
+
}),
|
|
1692
|
+
queryAllRoles: () => Effect16.gen(function* () {
|
|
1693
|
+
const results = yield* db.query.role.findMany({
|
|
1694
|
+
where: { _deleted: false }
|
|
1695
|
+
});
|
|
1696
|
+
return results.map((r) => ({
|
|
1697
|
+
id: r.id,
|
|
1698
|
+
name: r.name,
|
|
1699
|
+
path: r.path
|
|
1700
|
+
}));
|
|
1701
|
+
}),
|
|
1702
|
+
queryProviderUserRoleIds: (providerUserId) => Effect16.gen(function* () {
|
|
1703
|
+
const results = yield* db.query.providerUserRole.findMany({
|
|
1704
|
+
where: { providerUserId, _deleted: false }
|
|
1705
|
+
});
|
|
1706
|
+
return results.map((r) => r.roleId);
|
|
1707
|
+
}),
|
|
1708
|
+
queryProviderUserRolePaths: (providerUserId) => Effect16.gen(function* () {
|
|
1709
|
+
const results = yield* db.query.providerUserRole.findMany({
|
|
1710
|
+
with: {
|
|
1711
|
+
role: true
|
|
1712
|
+
},
|
|
1713
|
+
where: { providerUserId, _deleted: false }
|
|
1714
|
+
});
|
|
1715
|
+
return results.map((r) => r.role.path);
|
|
1716
|
+
}),
|
|
1717
|
+
queryProviderUserRolePathsByProviderUserIds: (providerUserIds) => Effect16.gen(function* () {
|
|
1718
|
+
if (providerUserIds.length === 0)
|
|
1719
|
+
return new Map;
|
|
1720
|
+
const results = yield* db.query.providerUserRole.findMany({
|
|
1721
|
+
with: {
|
|
1722
|
+
role: true
|
|
1723
|
+
},
|
|
1724
|
+
where: {
|
|
1725
|
+
RAW: (providerUserRole) => and(inArray(providerUserRole.providerUserId, [
|
|
1726
|
+
...providerUserIds
|
|
1727
|
+
]), eq(providerUserRole._deleted, false)) ?? sql`false`
|
|
1728
|
+
}
|
|
1729
|
+
});
|
|
1730
|
+
const rolePaths = new Map;
|
|
1731
|
+
for (const result of results) {
|
|
1732
|
+
const current = rolePaths.get(result.providerUserId) ?? [];
|
|
1733
|
+
current.push(result.role.path);
|
|
1734
|
+
rolePaths.set(result.providerUserId, current);
|
|
1735
|
+
}
|
|
1736
|
+
return rolePaths;
|
|
1737
|
+
}),
|
|
1738
|
+
replacePermittedRoles: (providerUserId, roleIds) => Effect16.gen(function* () {
|
|
1739
|
+
yield* db.delete(permittedRole).where(eq(permittedRole.providerUserId, providerUserId));
|
|
1740
|
+
if (roleIds.length > 0) {
|
|
1741
|
+
yield* db.insert(permittedRole).values(roleIds.map((roleId) => ({
|
|
1742
|
+
providerUserId,
|
|
1743
|
+
roleId
|
|
1744
|
+
})));
|
|
1745
|
+
}
|
|
1746
|
+
}),
|
|
1747
|
+
queryRoleByPath: (path) => Effect16.gen(function* () {
|
|
1748
|
+
const results = yield* db.query.role.findMany({
|
|
1749
|
+
where: { path, _deleted: false }
|
|
1750
|
+
});
|
|
1751
|
+
if (results.length && results[0]) {
|
|
1752
|
+
const r = results[0];
|
|
1753
|
+
return Option2.some({
|
|
1754
|
+
id: r.id,
|
|
1755
|
+
name: r.name,
|
|
1756
|
+
path: r.path
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
return Option2.none();
|
|
1760
|
+
}),
|
|
1761
|
+
addPermittedRole: (providerUserId, roleId) => db.insert(permittedRole).values({
|
|
1762
|
+
providerUserId,
|
|
1763
|
+
roleId
|
|
1764
|
+
}).onConflictDoUpdate({
|
|
1765
|
+
target: [permittedRole.providerUserId, permittedRole.roleId],
|
|
1766
|
+
targetWhere: sql`_deleted = 0`,
|
|
1767
|
+
set: { updatedAt: sql`julianday('now')` }
|
|
1768
|
+
})
|
|
1769
|
+
};
|
|
1770
|
+
}));
|
|
1771
|
+
|
|
1772
|
+
|
|
1773
|
+
import { Effect as Effect17, Layer as Layer17 } from "effect";
|
|
1774
|
+
var SqliteWorkflowQueriesLive = Layer17.effect(WorkflowQueries, Effect17.gen(function* () {
|
|
1775
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1776
|
+
return {
|
|
1777
|
+
queryWorkflowByProcessPath: (processPath) => Effect17.gen(function* () {
|
|
1778
|
+
const processes = yield* db.select({
|
|
1779
|
+
id: process2.id,
|
|
1780
|
+
name: process2.name,
|
|
1781
|
+
path: process2.path,
|
|
1782
|
+
purpose: process2.purpose
|
|
1783
|
+
}).from(process2).where(and(eq(process2.path, processPath), eq(process2._deleted, false))).limit(1);
|
|
1784
|
+
const processData = processes[0];
|
|
1785
|
+
if (!processData) {
|
|
1786
|
+
return yield* new ProcessNotFoundError({
|
|
1787
|
+
path: processPath,
|
|
1788
|
+
message: `Process not found: ${processPath}`
|
|
1789
|
+
});
|
|
1790
|
+
}
|
|
1791
|
+
const steps = yield* db.select({
|
|
1792
|
+
id: step.id,
|
|
1793
|
+
name: step.name,
|
|
1794
|
+
path: step.path,
|
|
1795
|
+
purpose: step.purpose,
|
|
1796
|
+
processId: step.processId,
|
|
1797
|
+
roleId: step.roleId,
|
|
1798
|
+
roleName: role.name,
|
|
1799
|
+
rolePath: role.path,
|
|
1800
|
+
phaseId: phase.id,
|
|
1801
|
+
phaseName: phase.name,
|
|
1802
|
+
phasePath: phase.path,
|
|
1803
|
+
phaseOrder: phase.phaseOrder,
|
|
1804
|
+
isStartStep: stepItsCanStartProcess.canStartProcess,
|
|
1805
|
+
isEmbedded: step.embedded
|
|
1806
|
+
}).from(step).leftJoin(role, eq(step.roleId, role.id)).leftJoin(phase, eq(step.phaseId, phase.id)).innerJoin(stepItsCanStartProcess, eq(step.id, stepItsCanStartProcess.id)).where(and(eq(step.processId, processData.id), eq(step._deleted, false), or(isNull(step.roleId), eq(role._deleted, false))));
|
|
1807
|
+
const stepIds = steps.map((s) => s.id);
|
|
1808
|
+
const flows = stepIds.length > 0 ? yield* db.select({
|
|
1809
|
+
id: flow.id,
|
|
1810
|
+
sourceStepId: flow.sourceStepId,
|
|
1811
|
+
targetStepId: flow.targetStepId,
|
|
1812
|
+
condition: flow.condition,
|
|
1813
|
+
fallbackBranch: flow.fallbackBranch,
|
|
1814
|
+
errorBranch: flow.errorBranch,
|
|
1815
|
+
deadlineName: flow.deadlineName,
|
|
1816
|
+
errorTags: flow.errorTags,
|
|
1817
|
+
schedule: flow.schedule
|
|
1818
|
+
}).from(flow).where(and(eq(flow._deleted, false), or(inArray(flow.sourceStepId, stepIds), inArray(flow.targetStepId, stepIds)))) : [];
|
|
1819
|
+
const responsibilities = yield* db.select({
|
|
1820
|
+
roleId: roleResponsibility.roleId,
|
|
1821
|
+
roleName: role.name,
|
|
1822
|
+
rolePath: role.path,
|
|
1823
|
+
responsibility: roleResponsibility.responsibility,
|
|
1824
|
+
order: roleResponsibility.responsibilityOrder
|
|
1825
|
+
}).from(roleResponsibility).innerJoin(role, eq(roleResponsibility.roleId, role.id)).where(and(eq(roleResponsibility.processId, processData.id), eq(roleResponsibility._deleted, false), eq(role._deleted, false)));
|
|
1826
|
+
const result = {
|
|
1827
|
+
processId: processData.id,
|
|
1828
|
+
processName: processData.name,
|
|
1829
|
+
processPath: processData.path,
|
|
1830
|
+
processPurpose: processData.purpose,
|
|
1831
|
+
steps: steps.map((s) => ({
|
|
1832
|
+
id: s.id,
|
|
1833
|
+
name: s.name,
|
|
1834
|
+
path: s.path,
|
|
1835
|
+
purpose: s.purpose,
|
|
1836
|
+
processId: s.processId,
|
|
1837
|
+
roleId: s.roleId,
|
|
1838
|
+
roleName: s.roleName,
|
|
1839
|
+
rolePath: s.rolePath,
|
|
1840
|
+
phaseId: s.phaseId,
|
|
1841
|
+
phaseName: s.phaseName,
|
|
1842
|
+
phasePath: s.phasePath,
|
|
1843
|
+
phaseOrder: s.phaseOrder,
|
|
1844
|
+
isStartStep: s.isStartStep,
|
|
1845
|
+
isEmbedded: s.isEmbedded
|
|
1846
|
+
})),
|
|
1847
|
+
flows: flows.map((f) => ({
|
|
1848
|
+
id: f.id,
|
|
1849
|
+
sourceStepId: f.sourceStepId,
|
|
1850
|
+
targetStepId: f.targetStepId,
|
|
1851
|
+
condition: f.condition,
|
|
1852
|
+
isElse: f.fallbackBranch,
|
|
1853
|
+
isOnError: f.errorBranch,
|
|
1854
|
+
deadlineName: f.deadlineName,
|
|
1855
|
+
taggedErrors: normalizeTaggedErrors(f.errorTags),
|
|
1856
|
+
schedule: f.schedule
|
|
1857
|
+
})),
|
|
1858
|
+
responsibilities: responsibilities.map((r) => ({
|
|
1859
|
+
roleId: r.roleId,
|
|
1860
|
+
roleName: r.roleName,
|
|
1861
|
+
rolePath: r.rolePath,
|
|
1862
|
+
responsibility: r.responsibility,
|
|
1863
|
+
order: r.order
|
|
1864
|
+
}))
|
|
1865
|
+
};
|
|
1866
|
+
return result;
|
|
1867
|
+
})
|
|
1868
|
+
};
|
|
1869
|
+
}));
|
|
1870
|
+
|
|
1871
|
+
|
|
1872
|
+
import { DateTime as DateTime4, Effect as Effect18, Layer as Layer18 } from "effect";
|
|
1873
|
+
var isActiveProviderUserRoleConflict = (error) => {
|
|
1874
|
+
const message = String(error);
|
|
1875
|
+
return message.includes("pf_provider_user_role_provideruserroleidx_idx") || message.includes("UNIQUE constraint failed: pf_provider_user_role.provider_user_id, pf_provider_user_role.role_id");
|
|
1876
|
+
};
|
|
1877
|
+
var SqliteSettingsQueriesLive = Layer18.effect(SettingsQueries, Effect18.gen(function* () {
|
|
1878
|
+
const db = yield* TypedSqliteDrizzle;
|
|
1879
|
+
const latestLogin = db.select({ occurredAt: max(auditEvent.occurredAt) }).from(auditEvent).where(and(eq(auditEvent.auditKind, "login"), eq(sql`json_extract(${auditEvent.auditDetails}, '$.actorUserId')`, user.id)));
|
|
1880
|
+
const lastLoggedIn = sql`coalesce((${latestLogin}), ${user.createdAt})`.mapWith(user.createdAt);
|
|
1881
|
+
const loadInvitationRoles = (invitationId) => Effect18.gen(function* () {
|
|
1882
|
+
const roleResults = yield* db.select({
|
|
1883
|
+
id: role.id,
|
|
1884
|
+
name: role.name,
|
|
1885
|
+
path: role.path
|
|
1886
|
+
}).from(invitationRole).innerJoin(role, eq(role.id, invitationRole.roleId)).where(and(eq(invitationRole.invitationId, invitationId), eq(invitationRole._deleted, false), eq(role._deleted, false))).orderBy(role.path);
|
|
1887
|
+
return roleResults;
|
|
1888
|
+
});
|
|
1889
|
+
const toLifecycleStatus = (status) => {
|
|
1890
|
+
if (status === InvitationLifecycleStatus.Accepted) {
|
|
1891
|
+
return InvitationLifecycleStatus.Accepted;
|
|
1892
|
+
}
|
|
1893
|
+
if (status === InvitationLifecycleStatus.LegacyClosed) {
|
|
1894
|
+
return InvitationLifecycleStatus.LegacyClosed;
|
|
1895
|
+
}
|
|
1896
|
+
return InvitationLifecycleStatus.Pending;
|
|
1897
|
+
};
|
|
1898
|
+
const toInvitationSource = (source) => {
|
|
1899
|
+
if (source === InvitationSource.Model) {
|
|
1900
|
+
return InvitationSource.Model;
|
|
1901
|
+
}
|
|
1902
|
+
if (source === InvitationSource.Dashboard) {
|
|
1903
|
+
return InvitationSource.Dashboard;
|
|
1904
|
+
}
|
|
1905
|
+
if (source === InvitationSource.Process) {
|
|
1906
|
+
return InvitationSource.Process;
|
|
1907
|
+
}
|
|
1908
|
+
if (source === InvitationSource.Cli) {
|
|
1909
|
+
return InvitationSource.Cli;
|
|
1910
|
+
}
|
|
1911
|
+
return InvitationSource.Legacy;
|
|
1912
|
+
};
|
|
1913
|
+
const toUtcDate = (value) => value ? DateTime4.toDateUtc(value) : null;
|
|
1914
|
+
const deriveRegistrationLinkStatus = (input) => {
|
|
1915
|
+
if (input.lifecycleStatus !== InvitationLifecycleStatus.Pending) {
|
|
1916
|
+
return RegistrationLinkStatus.NotGenerated;
|
|
1917
|
+
}
|
|
1918
|
+
if (input.tokenHash) {
|
|
1919
|
+
if (input.expiresAt && DateTime4.toEpochMillis(input.expiresAt) <= DateTime4.toEpochMillis(input.now)) {
|
|
1920
|
+
return RegistrationLinkStatus.Expired;
|
|
1921
|
+
}
|
|
1922
|
+
return RegistrationLinkStatus.Active;
|
|
1923
|
+
}
|
|
1924
|
+
if (input.revokedAt) {
|
|
1925
|
+
return RegistrationLinkStatus.Revoked;
|
|
1926
|
+
}
|
|
1927
|
+
return RegistrationLinkStatus.NotGenerated;
|
|
1928
|
+
};
|
|
1929
|
+
const clearRegistrationLinkColumns = {
|
|
1930
|
+
registrationTokenHash: null,
|
|
1931
|
+
registrationEncryptionVersion: null,
|
|
1932
|
+
registrationEncryptionNonce: null,
|
|
1933
|
+
registrationAuthenticationTag: null,
|
|
1934
|
+
registrationEncryptedToken: null,
|
|
1935
|
+
registrationLinkExpiresAt: null,
|
|
1936
|
+
registrationLinkGeneration: sql`coalesce(${invitation.registrationLinkGeneration}, 0) + 1`
|
|
1937
|
+
};
|
|
1938
|
+
const buildInvitationRow = (row, now) => Effect18.gen(function* () {
|
|
1939
|
+
const roles = yield* loadInvitationRoles(row.id);
|
|
1940
|
+
const status = toLifecycleStatus(row.invitationStatus);
|
|
1941
|
+
return {
|
|
1942
|
+
id: row.id,
|
|
1943
|
+
email: row.email,
|
|
1944
|
+
status,
|
|
1945
|
+
source: toInvitationSource(row.invitationSource),
|
|
1946
|
+
roles,
|
|
1947
|
+
acceptedAt: toUtcDate(row.invitationAcceptedAt),
|
|
1948
|
+
acceptedByProvider: row.invitationAcceptedByProvider,
|
|
1949
|
+
acceptedBySubject: row.invitationAcceptedBySubject,
|
|
1950
|
+
acceptedByProviderUserId: row.acceptedByProviderUserId,
|
|
1951
|
+
legacyClosedAt: toUtcDate(row.invitationLegacyClosedAt),
|
|
1952
|
+
legacyClosureReason: row.invitationLegacyClosureReason,
|
|
1953
|
+
registrationLinkStatus: deriveRegistrationLinkStatus({
|
|
1954
|
+
lifecycleStatus: status,
|
|
1955
|
+
tokenHash: row.registrationTokenHash,
|
|
1956
|
+
expiresAt: row.registrationLinkExpiresAt,
|
|
1957
|
+
revokedAt: row.registrationLinkRevokedAt,
|
|
1958
|
+
now
|
|
1959
|
+
}),
|
|
1960
|
+
registrationLinkExpiresAt: toUtcDate(row.registrationLinkExpiresAt),
|
|
1961
|
+
registrationLinkGeneratedAt: toUtcDate(row.registrationLinkGeneratedAt),
|
|
1962
|
+
registrationLinkGeneratedBy: row.registrationLinkGeneratedBy,
|
|
1963
|
+
registrationLinkRevealedAt: toUtcDate(row.registrationLinkRevealedAt),
|
|
1964
|
+
registrationLinkRevealedBy: row.registrationLinkRevealedBy,
|
|
1965
|
+
registrationLinkRevokedAt: toUtcDate(row.registrationLinkRevokedAt),
|
|
1966
|
+
registrationLinkRevokedBy: row.registrationLinkRevokedBy,
|
|
1967
|
+
registrationLinkGeneration: row.registrationLinkGeneration ?? 0
|
|
1968
|
+
};
|
|
1969
|
+
});
|
|
1970
|
+
const invitationSelect = {
|
|
1971
|
+
id: invitation.id,
|
|
1972
|
+
email: invitation.email,
|
|
1973
|
+
invitationStatus: invitation.invitationStatus,
|
|
1974
|
+
invitationSource: invitation.invitationSource,
|
|
1975
|
+
invitationAcceptedAt: invitation.invitationAcceptedAt,
|
|
1976
|
+
invitationAcceptedByProvider: invitation.invitationAcceptedByProvider,
|
|
1977
|
+
invitationAcceptedBySubject: invitation.invitationAcceptedBySubject,
|
|
1978
|
+
acceptedByProviderUserId: invitation.acceptedByProviderUserId,
|
|
1979
|
+
invitationLegacyClosedAt: invitation.invitationLegacyClosedAt,
|
|
1980
|
+
invitationLegacyClosureReason: invitation.invitationLegacyClosureReason,
|
|
1981
|
+
registrationTokenHash: invitation.registrationTokenHash,
|
|
1982
|
+
registrationLinkExpiresAt: invitation.registrationLinkExpiresAt,
|
|
1983
|
+
registrationLinkGeneratedAt: invitation.registrationLinkGeneratedAt,
|
|
1984
|
+
registrationLinkGeneratedBy: invitation.registrationLinkGeneratedBy,
|
|
1985
|
+
registrationLinkRevealedAt: invitation.registrationLinkRevealedAt,
|
|
1986
|
+
registrationLinkRevealedBy: invitation.registrationLinkRevealedBy,
|
|
1987
|
+
registrationLinkRevokedAt: invitation.registrationLinkRevokedAt,
|
|
1988
|
+
registrationLinkRevokedBy: invitation.registrationLinkRevokedBy,
|
|
1989
|
+
registrationLinkGeneration: invitation.registrationLinkGeneration
|
|
1990
|
+
};
|
|
1991
|
+
const countUsers = () => db.select({ count: count() }).from(user).where(eq(user._deleted, false)).pipe(Effect18.map((rows) => rows[0]?.count ?? 0));
|
|
1992
|
+
const countRoles = () => db.select({ count: count() }).from(role).where(eq(role._deleted, false)).pipe(Effect18.map((rows) => rows[0]?.count ?? 0));
|
|
1993
|
+
const countOAuthProviders = () => db.select({ count: count() }).from(oauthProvider).where(eq(oauthProvider._deleted, false)).pipe(Effect18.map((rows) => rows[0]?.count ?? 0));
|
|
1994
|
+
const invitationStatusFilter = (status) => and(eq(invitation._deleted, false), eq(invitation.invitationStatus, status));
|
|
1995
|
+
const countInvitations = (status = InvitationLifecycleStatus.Pending) => db.select({ count: count() }).from(invitation).where(invitationStatusFilter(status)).pipe(Effect18.map((rows) => rows[0]?.count ?? 0));
|
|
1996
|
+
return {
|
|
1997
|
+
countUsers,
|
|
1998
|
+
countRoles,
|
|
1999
|
+
countOAuthProviders,
|
|
2000
|
+
countInvitations,
|
|
2001
|
+
queryAllUsers: (page, limit) => Effect18.gen(function* () {
|
|
2002
|
+
const offset = (page - 1) * limit;
|
|
2003
|
+
const totalCount = yield* countUsers();
|
|
2004
|
+
const results = yield* db.select({
|
|
2005
|
+
id: user.id,
|
|
2006
|
+
provider: user.provider,
|
|
2007
|
+
sub: user.sub,
|
|
2008
|
+
lastLoggedIn,
|
|
2009
|
+
providerUserId: providerUser.id,
|
|
2010
|
+
providerUserName: providerUser.name,
|
|
2011
|
+
providerUserEmail: providerUser.email
|
|
2012
|
+
}).from(user).leftJoin(providerUser, and(eq(providerUser.userId, user.id), eq(providerUser._deleted, false))).where(eq(user._deleted, false)).orderBy(desc(lastLoggedIn), user.id).limit(limit).offset(offset);
|
|
2013
|
+
const items = results.map((r) => ({
|
|
2014
|
+
id: r.id,
|
|
2015
|
+
provider: r.provider,
|
|
2016
|
+
sub: r.sub,
|
|
2017
|
+
lastLoggedIn: DateTime4.toDateUtc(r.lastLoggedIn),
|
|
2018
|
+
isProviderUser: r.providerUserId !== null,
|
|
2019
|
+
providerUserName: r.providerUserName,
|
|
2020
|
+
providerUserEmail: r.providerUserEmail
|
|
2021
|
+
}));
|
|
2022
|
+
return {
|
|
2023
|
+
items,
|
|
2024
|
+
totalCount
|
|
2025
|
+
};
|
|
2026
|
+
}),
|
|
2027
|
+
queryAllOAuthProviders: (page, limit) => Effect18.gen(function* () {
|
|
2028
|
+
const offset = (page - 1) * limit;
|
|
2029
|
+
const totalCount = yield* countOAuthProviders();
|
|
2030
|
+
const results = yield* db.select({
|
|
2031
|
+
id: oauthProvider.id,
|
|
2032
|
+
providerName: oauthProvider.providerName
|
|
2033
|
+
}).from(oauthProvider).where(eq(oauthProvider._deleted, false)).orderBy(oauthProvider.providerName).limit(limit).offset(offset);
|
|
2034
|
+
const items = results.map((r) => ({
|
|
2035
|
+
id: r.id,
|
|
2036
|
+
providerName: r.providerName
|
|
2037
|
+
}));
|
|
2038
|
+
return {
|
|
2039
|
+
items,
|
|
2040
|
+
totalCount
|
|
2041
|
+
};
|
|
2042
|
+
}),
|
|
2043
|
+
queryAllInvitations: (page, limit, status = InvitationLifecycleStatus.Pending) => Effect18.gen(function* () {
|
|
2044
|
+
const offset = (page - 1) * limit;
|
|
2045
|
+
const totalCount = yield* countInvitations(status);
|
|
2046
|
+
const paginatedInvitations = yield* db.select(invitationSelect).from(invitation).where(invitationStatusFilter(status)).orderBy(invitation.email).limit(limit).offset(offset);
|
|
2047
|
+
const now = yield* DateTime4.now;
|
|
2048
|
+
const items = [];
|
|
2049
|
+
for (const invitation2 of paginatedInvitations) {
|
|
2050
|
+
items.push(yield* buildInvitationRow(invitation2, now));
|
|
2051
|
+
}
|
|
2052
|
+
return {
|
|
2053
|
+
items,
|
|
2054
|
+
totalCount
|
|
2055
|
+
};
|
|
2056
|
+
}),
|
|
2057
|
+
queryInvitationDetail: (invitationId) => Effect18.gen(function* () {
|
|
2058
|
+
const results = yield* db.select(invitationSelect).from(invitation).where(and(eq(invitation.id, invitationId), eq(invitation._deleted, false))).limit(1);
|
|
2059
|
+
const invitation2 = results[0];
|
|
2060
|
+
if (!invitation2) {
|
|
2061
|
+
return null;
|
|
2062
|
+
}
|
|
2063
|
+
return yield* buildInvitationRow(invitation2, yield* DateTime4.now);
|
|
2064
|
+
}),
|
|
2065
|
+
queryPendingInvitationByEmail: (email) => Effect18.gen(function* () {
|
|
2066
|
+
const results = yield* db.select(invitationSelect).from(invitation).where(and(eq(invitation.invitationPendingEmail, email), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false))).limit(1);
|
|
2067
|
+
const invitation2 = results[0];
|
|
2068
|
+
if (!invitation2) {
|
|
2069
|
+
return null;
|
|
2070
|
+
}
|
|
2071
|
+
return yield* buildInvitationRow(invitation2, yield* DateTime4.now);
|
|
2072
|
+
}),
|
|
2073
|
+
queryInvitationByNormalizedEmail: (email) => Effect18.gen(function* () {
|
|
2074
|
+
const pendingResults = yield* db.select(invitationSelect).from(invitation).where(and(eq(invitation.invitationPendingEmail, email), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false))).limit(1);
|
|
2075
|
+
const pending = pendingResults[0];
|
|
2076
|
+
if (pending) {
|
|
2077
|
+
return yield* buildInvitationRow(pending, yield* DateTime4.now);
|
|
2078
|
+
}
|
|
2079
|
+
const historicalResults = yield* db.select(invitationSelect).from(invitation).where(and(eq(invitation.email, email), eq(invitation._deleted, false))).orderBy(desc(invitation.createdAt)).limit(1);
|
|
2080
|
+
const historical = historicalResults[0];
|
|
2081
|
+
if (!historical) {
|
|
2082
|
+
return null;
|
|
2083
|
+
}
|
|
2084
|
+
return yield* buildInvitationRow(historical, yield* DateTime4.now);
|
|
2085
|
+
}),
|
|
2086
|
+
queryUserDetail: (userId) => Effect18.gen(function* () {
|
|
2087
|
+
const results = yield* db.select({
|
|
2088
|
+
id: user.id,
|
|
2089
|
+
provider: user.provider,
|
|
2090
|
+
sub: user.sub,
|
|
2091
|
+
lastLoggedIn,
|
|
2092
|
+
providerUserId: providerUser.id,
|
|
2093
|
+
providerUserEmail: providerUser.email,
|
|
2094
|
+
providerUserName: providerUser.name,
|
|
2095
|
+
providerUserFirstName: providerUser.firstName,
|
|
2096
|
+
providerUserLastName: providerUser.lastName,
|
|
2097
|
+
notificationPreference: userSettings.notificationPreference
|
|
2098
|
+
}).from(user).leftJoin(providerUser, and(eq(providerUser.userId, user.id), eq(providerUser._deleted, false))).leftJoin(userSettings, and(eq(userSettings.userId, user.id), eq(userSettings._deleted, false))).where(and(eq(user.id, userId), eq(user._deleted, false))).limit(1);
|
|
2099
|
+
const r = results[0];
|
|
2100
|
+
if (!r) {
|
|
2101
|
+
return null;
|
|
2102
|
+
}
|
|
2103
|
+
let roleIds = [];
|
|
2104
|
+
if (r.providerUserId) {
|
|
2105
|
+
const roleResults = yield* db.select({
|
|
2106
|
+
roleId: role.id
|
|
2107
|
+
}).from(providerUserRole).innerJoin(role, and(eq(providerUserRole.roleId, role.id), eq(role._deleted, false))).where(and(eq(providerUserRole.providerUserId, r.providerUserId), eq(providerUserRole._deleted, false)));
|
|
2108
|
+
roleIds = roleResults.map((rr) => rr.roleId);
|
|
2109
|
+
}
|
|
2110
|
+
const notificationPreferences = r.notificationPreference ? parseNotificationPreferences(r.notificationPreference) : defaultNotificationPreferences;
|
|
2111
|
+
return {
|
|
2112
|
+
id: r.id,
|
|
2113
|
+
provider: r.provider,
|
|
2114
|
+
sub: r.sub,
|
|
2115
|
+
lastLoggedIn: DateTime4.toDateUtc(r.lastLoggedIn),
|
|
2116
|
+
providerUser: r.providerUserId ? {
|
|
2117
|
+
id: r.providerUserId,
|
|
2118
|
+
email: r.providerUserEmail ?? "",
|
|
2119
|
+
name: r.providerUserName ?? "",
|
|
2120
|
+
firstName: r.providerUserFirstName ?? "",
|
|
2121
|
+
lastName: r.providerUserLastName ?? "",
|
|
2122
|
+
roleIds,
|
|
2123
|
+
notificationPreferences
|
|
2124
|
+
} : null
|
|
2125
|
+
};
|
|
2126
|
+
}),
|
|
2127
|
+
queryProviderUserDetail: (providerUserId) => Effect18.gen(function* () {
|
|
2128
|
+
const results = yield* db.select({
|
|
2129
|
+
id: providerUser.id,
|
|
2130
|
+
provider: user.provider,
|
|
2131
|
+
email: providerUser.email,
|
|
2132
|
+
name: providerUser.name,
|
|
2133
|
+
firstName: providerUser.firstName,
|
|
2134
|
+
lastName: providerUser.lastName,
|
|
2135
|
+
notificationPreference: userSettings.notificationPreference
|
|
2136
|
+
}).from(providerUser).innerJoin(user, and(eq(user.id, providerUser.userId), eq(user._deleted, false))).leftJoin(userSettings, and(eq(userSettings.userId, providerUser.userId), eq(userSettings._deleted, false))).where(and(eq(providerUser.id, providerUserId), eq(providerUser._deleted, false))).limit(1);
|
|
2137
|
+
const r = results[0];
|
|
2138
|
+
if (!r) {
|
|
2139
|
+
return null;
|
|
2140
|
+
}
|
|
2141
|
+
const roleResults = yield* db.select({
|
|
2142
|
+
roleId: role.id
|
|
2143
|
+
}).from(providerUserRole).innerJoin(role, and(eq(providerUserRole.roleId, role.id), eq(role._deleted, false))).where(and(eq(providerUserRole.providerUserId, providerUserId), eq(providerUserRole._deleted, false)));
|
|
2144
|
+
const notificationPreferences = r.notificationPreference ? parseNotificationPreferences(r.notificationPreference) : defaultNotificationPreferences;
|
|
2145
|
+
return {
|
|
2146
|
+
id: r.id,
|
|
2147
|
+
provider: r.provider,
|
|
2148
|
+
email: r.email ?? "",
|
|
2149
|
+
name: r.name ?? "",
|
|
2150
|
+
firstName: r.firstName ?? "",
|
|
2151
|
+
lastName: r.lastName ?? "",
|
|
2152
|
+
roleIds: roleResults.map((rr) => rr.roleId),
|
|
2153
|
+
notificationPreferences
|
|
2154
|
+
};
|
|
2155
|
+
}),
|
|
2156
|
+
updateProviderUserNames: (providerUserId, names, updatedBy) => Effect18.gen(function* () {
|
|
2157
|
+
const now = yield* getRequestTime();
|
|
2158
|
+
yield* db.update(providerUser).set({
|
|
2159
|
+
...names,
|
|
2160
|
+
updatedAt: now,
|
|
2161
|
+
updatedBy
|
|
2162
|
+
}).where(and(eq(providerUser.id, providerUserId), eq(providerUser._deleted, false)));
|
|
2163
|
+
}),
|
|
2164
|
+
queryAllRoles: () => Effect18.gen(function* () {
|
|
2165
|
+
const results = yield* db.select({
|
|
2166
|
+
id: role.id,
|
|
2167
|
+
name: role.name,
|
|
2168
|
+
path: role.path
|
|
2169
|
+
}).from(role).where(eq(role._deleted, false)).orderBy(role.path);
|
|
2170
|
+
return results;
|
|
2171
|
+
}),
|
|
2172
|
+
queryRolesByIds: (roleIds) => Effect18.gen(function* () {
|
|
2173
|
+
if (roleIds.length === 0) {
|
|
2174
|
+
return [];
|
|
2175
|
+
}
|
|
2176
|
+
const results = yield* db.select({
|
|
2177
|
+
id: role.id,
|
|
2178
|
+
name: role.name,
|
|
2179
|
+
path: role.path
|
|
2180
|
+
}).from(role).where(and(inArray(role.id, [...roleIds]), eq(role._deleted, false)));
|
|
2181
|
+
return results;
|
|
2182
|
+
}),
|
|
2183
|
+
queryPaginatedRoles: (page, limit) => Effect18.gen(function* () {
|
|
2184
|
+
const offset = (page - 1) * limit;
|
|
2185
|
+
const totalCount = yield* countRoles();
|
|
2186
|
+
const results = yield* db.select({
|
|
2187
|
+
id: role.id,
|
|
2188
|
+
name: role.name,
|
|
2189
|
+
path: role.path
|
|
2190
|
+
}).from(role).where(eq(role._deleted, false)).orderBy(role.path).limit(limit).offset(offset);
|
|
2191
|
+
return {
|
|
2192
|
+
items: results,
|
|
2193
|
+
totalCount
|
|
2194
|
+
};
|
|
2195
|
+
}),
|
|
2196
|
+
queryProviderUserRoleIds: (providerUserId) => Effect18.gen(function* () {
|
|
2197
|
+
const results = yield* db.select({
|
|
2198
|
+
roleId: role.id
|
|
2199
|
+
}).from(providerUserRole).innerJoin(role, and(eq(providerUserRole.roleId, role.id), eq(role._deleted, false))).where(and(eq(providerUserRole.providerUserId, providerUserId), eq(providerUserRole._deleted, false)));
|
|
2200
|
+
return results.map((r) => r.roleId);
|
|
2201
|
+
}),
|
|
2202
|
+
replaceProviderUserRoles: (providerUserId, roleIds) => Effect18.gen(function* () {
|
|
2203
|
+
yield* db.delete(providerUserRole).where(eq(providerUserRole.providerUserId, providerUserId));
|
|
2204
|
+
if (roleIds.length > 0) {
|
|
2205
|
+
const now = yield* DateTime4.now;
|
|
2206
|
+
const values = roleIds.map((roleId) => ({
|
|
2207
|
+
providerUserId,
|
|
2208
|
+
roleId,
|
|
2209
|
+
createdAt: now,
|
|
2210
|
+
updatedAt: now,
|
|
2211
|
+
createdBy: "SYSTEM",
|
|
2212
|
+
updatedBy: "SYSTEM",
|
|
2213
|
+
_deleted: false
|
|
2214
|
+
}));
|
|
2215
|
+
yield* db.insert(providerUserRole).values(values);
|
|
2216
|
+
}
|
|
2217
|
+
}),
|
|
2218
|
+
createInvitation: (input) => Effect18.gen(function* () {
|
|
2219
|
+
const now = yield* DateTime4.now;
|
|
2220
|
+
const result = yield* db.insert(invitation).values({
|
|
2221
|
+
invitationId: input.invitationId,
|
|
2222
|
+
email: input.email,
|
|
2223
|
+
invitationStatus: InvitationLifecycleStatus.Pending,
|
|
2224
|
+
invitationSource: input.source,
|
|
2225
|
+
invitationPendingEmail: input.email,
|
|
2226
|
+
createdAt: now,
|
|
2227
|
+
updatedAt: now,
|
|
2228
|
+
createdBy: input.createdBy,
|
|
2229
|
+
updatedBy: input.updatedBy,
|
|
2230
|
+
_deleted: false
|
|
2231
|
+
}).returning({ id: invitation.id });
|
|
2232
|
+
return (yield* returnedRow(result)).id;
|
|
2233
|
+
}),
|
|
2234
|
+
updateInvitationDetails: (invitationId, input) => Effect18.gen(function* () {
|
|
2235
|
+
const now = yield* DateTime4.now;
|
|
2236
|
+
const existingRows = yield* db.select({
|
|
2237
|
+
id: invitation.id,
|
|
2238
|
+
email: invitation.email
|
|
2239
|
+
}).from(invitation).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false))).limit(1);
|
|
2240
|
+
const existing = existingRows[0];
|
|
2241
|
+
if (!existing) {
|
|
2242
|
+
return false;
|
|
2243
|
+
}
|
|
2244
|
+
const emailChanged = existing.email !== input.email;
|
|
2245
|
+
const updatedInvitations = yield* db.update(invitation).set({
|
|
2246
|
+
email: input.email,
|
|
2247
|
+
invitationPendingEmail: input.email,
|
|
2248
|
+
updatedAt: now,
|
|
2249
|
+
updatedBy: input.updatedBy
|
|
2250
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false))).returning({ id: invitation.id });
|
|
2251
|
+
if (updatedInvitations.length === 0) {
|
|
2252
|
+
return false;
|
|
2253
|
+
}
|
|
2254
|
+
if (emailChanged) {
|
|
2255
|
+
yield* db.update(invitation).set({
|
|
2256
|
+
...clearRegistrationLinkColumns,
|
|
2257
|
+
registrationLinkRevokedAt: now,
|
|
2258
|
+
registrationLinkRevokedBy: input.updatedBy,
|
|
2259
|
+
updatedAt: now,
|
|
2260
|
+
updatedBy: input.updatedBy
|
|
2261
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), isNotNull(invitation.registrationTokenHash)));
|
|
2262
|
+
}
|
|
2263
|
+
return true;
|
|
2264
|
+
}),
|
|
2265
|
+
replaceInvitationRoles: (invitationId, roleIds, updatedBy) => Effect18.gen(function* () {
|
|
2266
|
+
const now = yield* DateTime4.now;
|
|
2267
|
+
const pendingInvitation = yield* db.select({ id: invitation.id }).from(invitation).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false))).limit(1);
|
|
2268
|
+
if (pendingInvitation.length === 0) {
|
|
2269
|
+
return;
|
|
2270
|
+
}
|
|
2271
|
+
const existingInvitationRoles = yield* db.select({
|
|
2272
|
+
id: invitationRole.id,
|
|
2273
|
+
roleId: invitationRole.roleId,
|
|
2274
|
+
deleted: invitationRole._deleted
|
|
2275
|
+
}).from(invitationRole).where(eq(invitationRole.invitationId, invitationId));
|
|
2276
|
+
const existingByRoleId = new Map(existingInvitationRoles.map((invitationRole2) => [
|
|
2277
|
+
invitationRole2.roleId,
|
|
2278
|
+
invitationRole2
|
|
2279
|
+
]));
|
|
2280
|
+
const desiredRoleIds = new Set(roleIds);
|
|
2281
|
+
const existingActiveRoleIds = new Set(existingInvitationRoles.filter((invitationRole2) => !invitationRole2.deleted).map((invitationRole2) => invitationRole2.roleId));
|
|
2282
|
+
const rolesChanged = roleIds.some((roleId) => !existingActiveRoleIds.has(roleId)) || [...existingActiveRoleIds].some((roleId) => !desiredRoleIds.has(roleId));
|
|
2283
|
+
const invitationRoleIdsToSoftDelete = existingInvitationRoles.filter((invitationRole2) => !invitationRole2.deleted && !desiredRoleIds.has(invitationRole2.roleId)).map((invitationRole2) => invitationRole2.id);
|
|
2284
|
+
if (invitationRoleIdsToSoftDelete.length > 0) {
|
|
2285
|
+
yield* db.update(invitationRole).set({
|
|
2286
|
+
_deleted: true,
|
|
2287
|
+
updatedAt: now,
|
|
2288
|
+
updatedBy
|
|
2289
|
+
}).where(inArray(invitationRole.id, invitationRoleIdsToSoftDelete));
|
|
2290
|
+
}
|
|
2291
|
+
if (roleIds.length === 0) {
|
|
2292
|
+
if (rolesChanged) {
|
|
2293
|
+
yield* db.update(invitation).set({
|
|
2294
|
+
...clearRegistrationLinkColumns,
|
|
2295
|
+
registrationLinkRevokedAt: now,
|
|
2296
|
+
registrationLinkRevokedBy: updatedBy,
|
|
2297
|
+
updatedAt: now,
|
|
2298
|
+
updatedBy
|
|
2299
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), isNotNull(invitation.registrationTokenHash)));
|
|
2300
|
+
}
|
|
2301
|
+
return;
|
|
2302
|
+
}
|
|
2303
|
+
const invitationRoleIdsToReactivate = roleIds.flatMap((roleId) => {
|
|
2304
|
+
const invitationRole2 = existingByRoleId.get(roleId);
|
|
2305
|
+
return invitationRole2?.deleted ? [invitationRole2.id] : [];
|
|
2306
|
+
});
|
|
2307
|
+
if (invitationRoleIdsToReactivate.length > 0) {
|
|
2308
|
+
yield* db.update(invitationRole).set({
|
|
2309
|
+
_deleted: false,
|
|
2310
|
+
updatedAt: now,
|
|
2311
|
+
updatedBy
|
|
2312
|
+
}).where(inArray(invitationRole.id, invitationRoleIdsToReactivate));
|
|
2313
|
+
}
|
|
2314
|
+
const roleIdsToInsert = roleIds.filter((roleId) => !existingByRoleId.has(roleId));
|
|
2315
|
+
if (roleIdsToInsert.length > 0) {
|
|
2316
|
+
yield* db.insert(invitationRole).values(roleIdsToInsert.map((roleId) => ({
|
|
2317
|
+
invitationId,
|
|
2318
|
+
roleId,
|
|
2319
|
+
createdAt: now,
|
|
2320
|
+
updatedAt: now,
|
|
2321
|
+
createdBy: updatedBy,
|
|
2322
|
+
updatedBy,
|
|
2323
|
+
_deleted: false
|
|
2324
|
+
})));
|
|
2325
|
+
}
|
|
2326
|
+
if (rolesChanged) {
|
|
2327
|
+
yield* db.update(invitation).set({
|
|
2328
|
+
...clearRegistrationLinkColumns,
|
|
2329
|
+
registrationLinkRevokedAt: now,
|
|
2330
|
+
registrationLinkRevokedBy: updatedBy,
|
|
2331
|
+
updatedAt: now,
|
|
2332
|
+
updatedBy
|
|
2333
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), isNotNull(invitation.registrationTokenHash)));
|
|
2334
|
+
}
|
|
2335
|
+
}),
|
|
2336
|
+
deleteInvitation: (invitationId, deletedBy) => Effect18.gen(function* () {
|
|
2337
|
+
const now = yield* DateTime4.now;
|
|
2338
|
+
const updatedInvitations = yield* db.update(invitation).set({
|
|
2339
|
+
_deleted: true,
|
|
2340
|
+
invitationPendingEmail: null,
|
|
2341
|
+
...clearRegistrationLinkColumns,
|
|
2342
|
+
registrationLinkRevokedAt: now,
|
|
2343
|
+
registrationLinkRevokedBy: deletedBy,
|
|
2344
|
+
updatedAt: now,
|
|
2345
|
+
updatedBy: deletedBy
|
|
2346
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false))).returning({ id: invitation.id });
|
|
2347
|
+
if (updatedInvitations.length === 0) {
|
|
2348
|
+
return false;
|
|
2349
|
+
}
|
|
2350
|
+
yield* db.update(invitationRole).set({
|
|
2351
|
+
_deleted: true,
|
|
2352
|
+
updatedAt: now,
|
|
2353
|
+
updatedBy: deletedBy
|
|
2354
|
+
}).where(and(eq(invitationRole.invitationId, invitationId), eq(invitationRole._deleted, false)));
|
|
2355
|
+
return true;
|
|
2356
|
+
}),
|
|
2357
|
+
storeRegistrationLink: (invitationId, input) => Effect18.gen(function* () {
|
|
2358
|
+
const now = yield* DateTime4.now;
|
|
2359
|
+
const expiresAt = DateTime4.makeUnsafe(input.expiresAt);
|
|
2360
|
+
const linkStatePredicate = input.requireActiveLink ? and(isNotNull(invitation.registrationTokenHash), gt(invitation.registrationLinkExpiresAt, now)) : or(isNull(invitation.registrationTokenHash), lte(invitation.registrationLinkExpiresAt, now));
|
|
2361
|
+
const updated = yield* db.update(invitation).set({
|
|
2362
|
+
registrationTokenHash: input.tokenHash,
|
|
2363
|
+
registrationEncryptionVersion: input.encryptionVersion,
|
|
2364
|
+
registrationEncryptionNonce: input.nonce,
|
|
2365
|
+
registrationAuthenticationTag: input.authenticationTag,
|
|
2366
|
+
registrationEncryptedToken: input.ciphertext,
|
|
2367
|
+
registrationLinkExpiresAt: expiresAt,
|
|
2368
|
+
registrationLinkGeneratedAt: now,
|
|
2369
|
+
registrationLinkGeneratedBy: input.actor,
|
|
2370
|
+
registrationLinkRevealedAt: null,
|
|
2371
|
+
registrationLinkRevealedBy: null,
|
|
2372
|
+
registrationLinkRevokedAt: null,
|
|
2373
|
+
registrationLinkRevokedBy: null,
|
|
2374
|
+
registrationLinkGeneration: input.generation,
|
|
2375
|
+
updatedAt: now,
|
|
2376
|
+
updatedBy: input.actor
|
|
2377
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), sql`coalesce(${invitation.registrationLinkGeneration}, 0) = ${input.expectedPreviousGeneration}`, linkStatePredicate)).returning({ id: invitation.id });
|
|
2378
|
+
return updated.length > 0;
|
|
2379
|
+
}),
|
|
2380
|
+
recordRegistrationLinkReveal: (invitationId, revealedBy, pin) => Effect18.gen(function* () {
|
|
2381
|
+
const now = yield* DateTime4.now;
|
|
2382
|
+
const updated = yield* db.update(invitation).set({
|
|
2383
|
+
registrationLinkRevealedAt: now,
|
|
2384
|
+
registrationLinkRevealedBy: revealedBy,
|
|
2385
|
+
updatedAt: now,
|
|
2386
|
+
updatedBy: revealedBy
|
|
2387
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), eq(invitation.registrationTokenHash, pin.tokenHash), sql`coalesce(${invitation.registrationLinkGeneration}, 0) = ${pin.generation}`, gt(invitation.registrationLinkExpiresAt, now))).returning({ id: invitation.id });
|
|
2388
|
+
return updated.length > 0;
|
|
2389
|
+
}),
|
|
2390
|
+
queryLiveRegistrationLink: (invitationId, now) => Effect18.gen(function* () {
|
|
2391
|
+
const nowUtc = DateTime4.makeUnsafe(now);
|
|
2392
|
+
const results = yield* db.select({
|
|
2393
|
+
invitationId: invitation.id,
|
|
2394
|
+
tokenHash: invitation.registrationTokenHash,
|
|
2395
|
+
encryptionVersion: invitation.registrationEncryptionVersion,
|
|
2396
|
+
nonce: invitation.registrationEncryptionNonce,
|
|
2397
|
+
authenticationTag: invitation.registrationAuthenticationTag,
|
|
2398
|
+
ciphertext: invitation.registrationEncryptedToken,
|
|
2399
|
+
expiresAt: invitation.registrationLinkExpiresAt,
|
|
2400
|
+
generation: invitation.registrationLinkGeneration
|
|
2401
|
+
}).from(invitation).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), isNotNull(invitation.registrationTokenHash), gt(invitation.registrationLinkExpiresAt, nowUtc))).limit(1);
|
|
2402
|
+
const row = results[0];
|
|
2403
|
+
if (!row?.tokenHash || row.encryptionVersion === null || !row.nonce || !row.authenticationTag || !row.ciphertext || !row.expiresAt || row.generation === null) {
|
|
2404
|
+
return null;
|
|
2405
|
+
}
|
|
2406
|
+
return {
|
|
2407
|
+
invitationId: row.invitationId,
|
|
2408
|
+
tokenHash: row.tokenHash,
|
|
2409
|
+
encryptionVersion: row.encryptionVersion,
|
|
2410
|
+
nonce: row.nonce,
|
|
2411
|
+
authenticationTag: row.authenticationTag,
|
|
2412
|
+
ciphertext: row.ciphertext,
|
|
2413
|
+
expiresAt: DateTime4.toDateUtc(row.expiresAt),
|
|
2414
|
+
generation: row.generation
|
|
2415
|
+
};
|
|
2416
|
+
}),
|
|
2417
|
+
revokeRegistrationLink: (invitationId, revokedBy, pin) => Effect18.gen(function* () {
|
|
2418
|
+
const now = yield* DateTime4.now;
|
|
2419
|
+
const pinPredicates = pin ? [
|
|
2420
|
+
eq(invitation.registrationTokenHash, pin.tokenHash),
|
|
2421
|
+
sql`coalesce(${invitation.registrationLinkGeneration}, 0) = ${pin.generation}`
|
|
2422
|
+
] : [isNotNull(invitation.registrationTokenHash)];
|
|
2423
|
+
const updated = yield* db.update(invitation).set({
|
|
2424
|
+
...clearRegistrationLinkColumns,
|
|
2425
|
+
registrationLinkRevokedAt: now,
|
|
2426
|
+
registrationLinkRevokedBy: revokedBy,
|
|
2427
|
+
updatedAt: now,
|
|
2428
|
+
updatedBy: revokedBy
|
|
2429
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation.invitationStatus, InvitationLifecycleStatus.Pending), eq(invitation._deleted, false), ...pinPredicates)).returning({ id: invitation.id });
|
|
2430
|
+
return updated.length > 0;
|
|
2431
|
+
}),
|
|
2432
|
+
clearRegistrationLink: (invitationId, updatedBy) => Effect18.gen(function* () {
|
|
2433
|
+
const now = yield* DateTime4.now;
|
|
2434
|
+
yield* db.update(invitation).set({
|
|
2435
|
+
...clearRegistrationLinkColumns,
|
|
2436
|
+
registrationLinkRevokedAt: now,
|
|
2437
|
+
registrationLinkRevokedBy: updatedBy,
|
|
2438
|
+
updatedAt: now,
|
|
2439
|
+
updatedBy
|
|
2440
|
+
}).where(and(eq(invitation.id, invitationId), eq(invitation._deleted, false), isNotNull(invitation.registrationTokenHash)));
|
|
2441
|
+
}),
|
|
2442
|
+
isPasskeyProviderEnabled: () => Effect18.gen(function* () {
|
|
2443
|
+
const results = yield* db.select({ id: oauthProvider.id }).from(oauthProvider).where(and(eq(oauthProvider.providerName, "passkey"), eq(oauthProvider._deleted, false))).limit(1);
|
|
2444
|
+
return results.length > 0;
|
|
2445
|
+
}),
|
|
2446
|
+
queryNotificationPreferences: (userId) => Effect18.gen(function* () {
|
|
2447
|
+
const results = yield* db.select({
|
|
2448
|
+
notificationPreference: userSettings.notificationPreference
|
|
2449
|
+
}).from(userSettings).where(and(eq(userSettings.userId, userId), eq(userSettings._deleted, false))).limit(1);
|
|
2450
|
+
const r = results[0];
|
|
2451
|
+
if (!r?.notificationPreference) {
|
|
2452
|
+
return defaultNotificationPreferences;
|
|
2453
|
+
}
|
|
2454
|
+
return parseNotificationPreferences(r.notificationPreference);
|
|
2455
|
+
}),
|
|
2456
|
+
updateNotificationPreferences: (userId, preferences, updatedBy) => Effect18.gen(function* () {
|
|
2457
|
+
const now = yield* DateTime4.now;
|
|
2458
|
+
yield* db.insert(userSettings).values({
|
|
2459
|
+
userId,
|
|
2460
|
+
notificationPreference: serializeNotificationPreferences(preferences),
|
|
2461
|
+
createdAt: now,
|
|
2462
|
+
updatedAt: now,
|
|
2463
|
+
updatedBy
|
|
2464
|
+
}).onConflictDoUpdate({
|
|
2465
|
+
target: userSettings.userId,
|
|
2466
|
+
targetWhere: sql`_deleted = 0`,
|
|
2467
|
+
set: {
|
|
2468
|
+
notificationPreference: serializeNotificationPreferences(preferences),
|
|
2469
|
+
updatedAt: now,
|
|
2470
|
+
updatedBy
|
|
2471
|
+
}
|
|
2472
|
+
});
|
|
2473
|
+
}),
|
|
2474
|
+
queryProviderUserByEmail: (email) => Effect18.gen(function* () {
|
|
2475
|
+
const normalizedEmail = email.trim().toLowerCase();
|
|
2476
|
+
const results = yield* db.select({
|
|
2477
|
+
id: providerUser.id,
|
|
2478
|
+
email: providerUser.email
|
|
2479
|
+
}).from(providerUser).where(and(sql`lower(${providerUser.email}) = ${normalizedEmail}`, eq(providerUser._deleted, false))).limit(1);
|
|
2480
|
+
return results[0] ?? null;
|
|
2481
|
+
}),
|
|
2482
|
+
queryRoleByPath: (path) => Effect18.gen(function* () {
|
|
2483
|
+
const results = yield* db.select({
|
|
2484
|
+
id: role.id,
|
|
2485
|
+
path: role.path
|
|
2486
|
+
}).from(role).where(and(eq(role.path, path), eq(role._deleted, false))).limit(1);
|
|
2487
|
+
return results[0] ?? null;
|
|
2488
|
+
}),
|
|
2489
|
+
grantProviderUserRole: (providerUserId, roleId, grantedBy) => Effect18.gen(function* () {
|
|
2490
|
+
const existing = yield* db.select({
|
|
2491
|
+
id: providerUserRole.id,
|
|
2492
|
+
deleted: providerUserRole._deleted
|
|
2493
|
+
}).from(providerUserRole).where(and(eq(providerUserRole.providerUserId, providerUserId), eq(providerUserRole.roleId, roleId))).limit(1);
|
|
2494
|
+
const row = existing[0];
|
|
2495
|
+
if (row && !row.deleted) {
|
|
2496
|
+
return { alreadyHadRole: true };
|
|
2497
|
+
}
|
|
2498
|
+
const now = yield* DateTime4.now;
|
|
2499
|
+
if (row?.deleted) {
|
|
2500
|
+
yield* db.update(providerUserRole).set({
|
|
2501
|
+
_deleted: false,
|
|
2502
|
+
updatedAt: now,
|
|
2503
|
+
updatedBy: grantedBy
|
|
2504
|
+
}).where(eq(providerUserRole.id, row.id));
|
|
2505
|
+
return { alreadyHadRole: false };
|
|
2506
|
+
}
|
|
2507
|
+
const inserted = yield* db.insert(providerUserRole).values({
|
|
2508
|
+
providerUserId,
|
|
2509
|
+
roleId,
|
|
2510
|
+
createdAt: now,
|
|
2511
|
+
updatedAt: now,
|
|
2512
|
+
createdBy: grantedBy,
|
|
2513
|
+
updatedBy: grantedBy,
|
|
2514
|
+
_deleted: false
|
|
2515
|
+
}).returning({ id: providerUserRole.id }).pipe(Effect18.catch((error) => isActiveProviderUserRoleConflict(error) ? Effect18.succeed([]) : Effect18.fail(error)));
|
|
2516
|
+
return {
|
|
2517
|
+
alreadyHadRole: inserted.length === 0
|
|
2518
|
+
};
|
|
2519
|
+
})
|
|
2520
|
+
};
|
|
2521
|
+
}));
|
|
2522
|
+
|
|
2523
|
+
|
|
2524
|
+
import { strict as assert } from "assert";
|
|
2525
|
+
import { DateTime as DateTime5, Effect as Effect19, Layer as Layer19, Schema } from "effect";
|
|
2526
|
+
var SqliteStepCompletionOperationsLive = Layer19.effect(StepCompletionOperations, Effect19.gen(function* () {
|
|
2527
|
+
const db = yield* TypedSqliteDrizzle;
|
|
2528
|
+
const queryTodo = (todoId, includeCompleted) => Effect19.gen(function* () {
|
|
2529
|
+
const result = yield* db.select({
|
|
2530
|
+
id: toDo.id,
|
|
2531
|
+
externalWriteAttemptId: toDo.externalWriteAttemptId,
|
|
2532
|
+
failureReason: toDo.failureReason,
|
|
2533
|
+
restartAttemptId: toDo.restartAttemptId,
|
|
2534
|
+
createdBy: toDo.createdBy,
|
|
2535
|
+
processExecutionId: toDo.processExecutionId,
|
|
2536
|
+
processStateId: processExecution.processStateId,
|
|
2537
|
+
startedByUserId: processState.startedByUserId,
|
|
2538
|
+
targetStepId: step.id,
|
|
2539
|
+
targetStepPath: step.path,
|
|
2540
|
+
processPath: process2.path,
|
|
2541
|
+
orgUnitPath: orgUnit.path,
|
|
2542
|
+
assignedToProviderUserId: toDo.assignedToProviderUserId,
|
|
2543
|
+
assignedToProviderUserEmail: providerUser.email,
|
|
2544
|
+
correctionRequiredAt: toDo.correctionRequiredAt,
|
|
2545
|
+
createdAtMs: sql`(${toDo.createdAt} - 2440587.5) * 86400000`.as("created_at_ms"),
|
|
2546
|
+
orgUnitId: process2.orgUnitId,
|
|
2547
|
+
itemData: toDo.itemData,
|
|
2548
|
+
hasForEach: step.hasForEach,
|
|
2549
|
+
barrierScheduledFlowId: toDo.barrierScheduledFlowId,
|
|
2550
|
+
completed: toDo._deleted
|
|
2551
|
+
}).from(toDo).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(process2, eq(processState.processId, process2.id)).innerJoin(orgUnit, eq(process2.orgUnitId, orgUnit.id)).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).leftJoin(providerUser, eq(toDo.assignedToProviderUserId, providerUser.id)).where(includeCompleted ? and(eq(toDo.id, todoId), isNull(toDo.interruptedAt)) : and(eq(toDo.id, todoId), eq(toDo._deleted, false))).limit(1);
|
|
2552
|
+
return result[0] ?? null;
|
|
2553
|
+
});
|
|
2554
|
+
const getCompletedStepsForExecutions = (processExecutionIds) => Effect19.gen(function* () {
|
|
2555
|
+
const stepsByExecution = new Map;
|
|
2556
|
+
for (const executionId of processExecutionIds) {
|
|
2557
|
+
stepsByExecution.set(executionId, []);
|
|
2558
|
+
}
|
|
2559
|
+
if (stepsByExecution.size === 0)
|
|
2560
|
+
return stepsByExecution;
|
|
2561
|
+
const executionIds = [...stepsByExecution.keys()];
|
|
2562
|
+
const startStepResults = yield* db.select({
|
|
2563
|
+
executionId: processExecution.id,
|
|
2564
|
+
stepPath: step.path,
|
|
2565
|
+
userId: user.id,
|
|
2566
|
+
userSub: user.sub,
|
|
2567
|
+
providerUserId: sql`COALESCE(${providerUser.id}, ${user.id})`.as("assigned_to_provider_user_id"),
|
|
2568
|
+
providerUserName: sql`COALESCE(${providerUser.name}, ${user.sub})`.as("provider_user_name"),
|
|
2569
|
+
providerUserFirstName: sql`COALESCE(${providerUser.firstName}, ${user.sub})`.as("provider_user_first_name"),
|
|
2570
|
+
providerUserLastName: sql`COALESCE(${providerUser.lastName}, '')`.as("provider_user_last_name"),
|
|
2571
|
+
providerUserEmail: sql`COALESCE(${providerUser.email}, ${user.sub})`.as("provider_user_email"),
|
|
2572
|
+
providerUserPicture: sql`COALESCE(${providerUser.picture}, '')`.as("provider_user_picture"),
|
|
2573
|
+
completedAt: sql`(${processExecution.createdAt} - 2440587.5) * 86400000`.as("completed_at_millis")
|
|
2574
|
+
}).from(processExecution).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(step, eq(processState.startStepId, step.id)).innerJoin(user, eq(processState.startedByUserId, user.id)).leftJoin(providerUser, eq(user.id, providerUser.userId)).where(inArray(processExecution.id, executionIds));
|
|
2575
|
+
const todoResults = yield* db.select({
|
|
2576
|
+
executionId: toDo.processExecutionId,
|
|
2577
|
+
stepPath: step.path,
|
|
2578
|
+
userId: user.id,
|
|
2579
|
+
userSub: user.sub,
|
|
2580
|
+
providerUserId: sql`COALESCE(${providerUser.id}, ${user.id})`.as("assigned_to_provider_user_id"),
|
|
2581
|
+
providerUserName: sql`COALESCE(${providerUser.name}, ${user.sub})`.as("provider_user_name"),
|
|
2582
|
+
providerUserFirstName: sql`COALESCE(${providerUser.firstName}, ${user.sub})`.as("provider_user_first_name"),
|
|
2583
|
+
providerUserLastName: sql`COALESCE(${providerUser.lastName}, '')`.as("provider_user_last_name"),
|
|
2584
|
+
providerUserEmail: sql`COALESCE(${providerUser.email}, ${user.sub})`.as("provider_user_email"),
|
|
2585
|
+
providerUserPicture: sql`COALESCE(${providerUser.picture}, '')`.as("provider_user_picture"),
|
|
2586
|
+
completedAt: sql`(${toDo.updatedAt} - 2440587.5) * 86400000`.as("completed_at_millis")
|
|
2587
|
+
}).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).innerJoin(user, eq(toDo.completedByUserId, user.id)).leftJoin(providerUser, eq(user.id, providerUser.userId)).where(and(inArray(toDo.processExecutionId, executionIds), eq(toDo._deleted, sql`1`), isNotNull(toDo.completedByUserId)));
|
|
2588
|
+
for (const row of [...startStepResults, ...todoResults]) {
|
|
2589
|
+
stepsByExecution.get(row.executionId)?.push({
|
|
2590
|
+
stepPath: row.stepPath,
|
|
2591
|
+
userId: row.userId,
|
|
2592
|
+
userSub: row.userSub,
|
|
2593
|
+
providerUserId: row.providerUserId,
|
|
2594
|
+
providerUserName: row.providerUserName,
|
|
2595
|
+
providerUserFirstName: row.providerUserFirstName,
|
|
2596
|
+
providerUserLastName: row.providerUserLastName,
|
|
2597
|
+
providerUserEmail: row.providerUserEmail,
|
|
2598
|
+
providerUserPicture: row.providerUserPicture,
|
|
2599
|
+
completedAt: DateTime5.fromDateUnsafe(new Date(row.completedAt))
|
|
2600
|
+
});
|
|
2601
|
+
}
|
|
2602
|
+
return stepsByExecution;
|
|
2603
|
+
});
|
|
2604
|
+
return {
|
|
2605
|
+
queryTodoById: (todoId) => queryTodo(todoId, false),
|
|
2606
|
+
queryTodoForCompletionById: (todoId) => queryTodo(todoId, true),
|
|
2607
|
+
queryPublicTodoInfo: (todoId) => Effect19.gen(function* () {
|
|
2608
|
+
const result = yield* db.select({
|
|
2609
|
+
todoId: toDo.id,
|
|
2610
|
+
deleted: toDo._deleted,
|
|
2611
|
+
failureReason: toDo.failureReason,
|
|
2612
|
+
correctionRequiredAt: toDo.correctionRequiredAt,
|
|
2613
|
+
abandonedAt: processExecution.abandonedAt,
|
|
2614
|
+
stepPath: step.path,
|
|
2615
|
+
itemData: toDo.itemData
|
|
2616
|
+
}).from(toDo).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).where(eq(toDo.id, todoId)).limit(1);
|
|
2617
|
+
const row = result[0];
|
|
2618
|
+
if (!row) {
|
|
2619
|
+
return {
|
|
2620
|
+
todoId,
|
|
2621
|
+
status: "unavailable",
|
|
2622
|
+
stepPath: null,
|
|
2623
|
+
latestPublicCompletionInvitationRecipientEmail: null,
|
|
2624
|
+
itemData: null
|
|
2625
|
+
};
|
|
2626
|
+
}
|
|
2627
|
+
const status = row.failureReason != null || row.correctionRequiredAt != null ? "unavailable" : row.deleted ? row.abandonedAt ? "unavailable" : "completed" : "active";
|
|
2628
|
+
const latestInvitation = status !== "unavailable" ? yield* db.select({
|
|
2629
|
+
email: publicCompletionInvitationAttempt.email
|
|
2630
|
+
}).from(publicCompletionInvitationAttempt).where(and(eq(publicCompletionInvitationAttempt.toDoId, todoId), eq(publicCompletionInvitationAttempt._deleted, false))).orderBy(desc(publicCompletionInvitationAttempt.createdAt), desc(publicCompletionInvitationAttempt.id)).limit(1) : [];
|
|
2631
|
+
return {
|
|
2632
|
+
todoId: row.todoId,
|
|
2633
|
+
status,
|
|
2634
|
+
stepPath: row.stepPath,
|
|
2635
|
+
latestPublicCompletionInvitationRecipientEmail: latestInvitation[0]?.email ?? null,
|
|
2636
|
+
itemData: row.itemData
|
|
2637
|
+
};
|
|
2638
|
+
}),
|
|
2639
|
+
queryLatestPublicCompletionInvitationAttempt: (todoId) => Effect19.gen(function* () {
|
|
2640
|
+
const rows = yield* db.select({
|
|
2641
|
+
id: publicCompletionInvitationAttempt.id,
|
|
2642
|
+
email: publicCompletionInvitationAttempt.email
|
|
2643
|
+
}).from(publicCompletionInvitationAttempt).where(and(eq(publicCompletionInvitationAttempt.toDoId, todoId), eq(publicCompletionInvitationAttempt._deleted, false))).orderBy(desc(publicCompletionInvitationAttempt.createdAt), desc(publicCompletionInvitationAttempt.id)).limit(1);
|
|
2644
|
+
return rows[0] ?? null;
|
|
2645
|
+
}),
|
|
2646
|
+
createPublicCompletionInvitationAttempt: ({ todoId, recipientEmail }) => Effect19.gen(function* () {
|
|
2647
|
+
const requestTime = yield* getRequestTime();
|
|
2648
|
+
const userDetails = yield* getUserDetails();
|
|
2649
|
+
const rows = yield* db.insert(publicCompletionInvitationAttempt).values({
|
|
2650
|
+
toDoId: todoId,
|
|
2651
|
+
email: recipientEmail,
|
|
2652
|
+
createdAt: requestTime,
|
|
2653
|
+
updatedAt: requestTime,
|
|
2654
|
+
createdBy: userDetails.by,
|
|
2655
|
+
updatedBy: userDetails.by
|
|
2656
|
+
}).returning({ id: publicCompletionInvitationAttempt.id });
|
|
2657
|
+
return (yield* returnedRow(rows)).id;
|
|
2658
|
+
}),
|
|
2659
|
+
recordPublicCompletionInvitationAttemptReceipt: (attemptId, receipt) => Effect19.gen(function* () {
|
|
2660
|
+
const requestTime = yield* getRequestTime();
|
|
2661
|
+
const userDetails = yield* getUserDetails();
|
|
2662
|
+
const rows = yield* db.update(publicCompletionInvitationAttempt).set({
|
|
2663
|
+
providerMessageId: receipt.providerMessageId,
|
|
2664
|
+
providerSentTo: receipt.providerSentTo,
|
|
2665
|
+
updatedAt: requestTime,
|
|
2666
|
+
updatedBy: userDetails.by
|
|
2667
|
+
}).where(and(eq(publicCompletionInvitationAttempt.id, attemptId), eq(publicCompletionInvitationAttempt._deleted, false))).returning({ id: publicCompletionInvitationAttempt.id });
|
|
2668
|
+
return rows.length > 0;
|
|
2669
|
+
}),
|
|
2670
|
+
queryPublicCompletionInvitationAttemptCallbackTarget: (todoId, attemptId) => Effect19.gen(function* () {
|
|
2671
|
+
const latest = yield* db.select({ id: publicCompletionInvitationAttempt.id }).from(publicCompletionInvitationAttempt).where(and(eq(publicCompletionInvitationAttempt.toDoId, todoId), eq(publicCompletionInvitationAttempt._deleted, false))).orderBy(desc(publicCompletionInvitationAttempt.createdAt), desc(publicCompletionInvitationAttempt.id)).limit(1);
|
|
2672
|
+
if (latest[0]?.id !== attemptId) {
|
|
2673
|
+
return null;
|
|
2674
|
+
}
|
|
2675
|
+
const rows = yield* db.select({
|
|
2676
|
+
attemptId: publicCompletionInvitationAttempt.id,
|
|
2677
|
+
todoId: toDo.id,
|
|
2678
|
+
providerMessageId: publicCompletionInvitationAttempt.providerMessageId,
|
|
2679
|
+
providerSentTo: publicCompletionInvitationAttempt.providerSentTo,
|
|
2680
|
+
processExecutionId: toDo.processExecutionId,
|
|
2681
|
+
assignedToProviderUserId: toDo.assignedToProviderUserId,
|
|
2682
|
+
roleId: step.roleId,
|
|
2683
|
+
stepPath: step.path,
|
|
2684
|
+
stepName: step.name,
|
|
2685
|
+
processName: process2.name
|
|
2686
|
+
}).from(publicCompletionInvitationAttempt).innerJoin(toDo, eq(publicCompletionInvitationAttempt.toDoId, toDo.id)).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).innerJoin(process2, eq(step.processId, process2.id)).where(and(eq(publicCompletionInvitationAttempt.id, attemptId), eq(publicCompletionInvitationAttempt.toDoId, todoId), eq(publicCompletionInvitationAttempt._deleted, false), eq(toDo._deleted, false), isNull(toDo.completedByUserId), isNull(toDo.completedByExternalParticipantId), isNull(toDo.completedByRoleId), isNull(toDo.failureReason), isNull(toDo.correctionRequiredAt), eq(flow._deleted, false), eq(step._deleted, false), eq(process2._deleted, false))).limit(1);
|
|
2687
|
+
return rows[0] ?? null;
|
|
2688
|
+
}),
|
|
2689
|
+
recordPublicCompletionInvitationAttemptDeliveryEvent: (attemptId, event) => Effect19.gen(function* () {
|
|
2690
|
+
const requestTime = yield* getRequestTime();
|
|
2691
|
+
const userDetails = yield* getUserDetails();
|
|
2692
|
+
const rows = yield* db.update(publicCompletionInvitationAttempt).set({
|
|
2693
|
+
deliveryStatus: event.deliveryStatus,
|
|
2694
|
+
deliveryEventId: event.deliveryEventId,
|
|
2695
|
+
deliveryFailureKind: event.deliveryStatus === "failed" ? event.deliveryFailureKind ?? null : null,
|
|
2696
|
+
deliveryFailureReason: event.deliveryStatus === "failed" ? event.deliveryFailureReason ?? null : null,
|
|
2697
|
+
...event.providerMessageId !== undefined && {
|
|
2698
|
+
providerMessageId: event.providerMessageId
|
|
2699
|
+
},
|
|
2700
|
+
updatedAt: requestTime,
|
|
2701
|
+
updatedBy: userDetails.by
|
|
2702
|
+
}).where(and(eq(publicCompletionInvitationAttempt.id, attemptId), eq(publicCompletionInvitationAttempt._deleted, false))).returning({ id: publicCompletionInvitationAttempt.id });
|
|
2703
|
+
return rows.length > 0;
|
|
2704
|
+
}),
|
|
2705
|
+
enterPublicCompletionCorrectionRequired: (input) => Effect19.gen(function* () {
|
|
2706
|
+
const requestTime = yield* getRequestTime();
|
|
2707
|
+
const userDetails = yield* getUserDetails();
|
|
2708
|
+
const rows = yield* db.update(toDo).set({
|
|
2709
|
+
correctionRequiredAt: requestTime,
|
|
2710
|
+
correctionFailureReason: input.failureReason,
|
|
2711
|
+
correctionInvitationAttemptId: input.invitationAttemptId,
|
|
2712
|
+
updatedAt: requestTime,
|
|
2713
|
+
updatedBy: userDetails.by
|
|
2714
|
+
}).where(and(eq(toDo.id, input.todoId), eq(toDo._deleted, false), isNull(toDo.completedByUserId), isNull(toDo.completedByExternalParticipantId), isNull(toDo.completedByRoleId), isNull(toDo.failureReason), isNull(toDo.correctionRequiredAt))).returning({
|
|
2715
|
+
id: toDo.id,
|
|
2716
|
+
processExecutionId: toDo.processExecutionId
|
|
2717
|
+
});
|
|
2718
|
+
const row = rows[0];
|
|
2719
|
+
if (!row)
|
|
2720
|
+
return false;
|
|
2721
|
+
yield* db.update(processExecution).set({
|
|
2722
|
+
updatedAt: requestTime,
|
|
2723
|
+
updatedBy: userDetails.by
|
|
2724
|
+
}).where(eq(processExecution.id, row.processExecutionId));
|
|
2725
|
+
return true;
|
|
2726
|
+
}),
|
|
2727
|
+
queryPublicCompletionCorrectionRecipient: (todoId) => Effect19.gen(function* () {
|
|
2728
|
+
const rows = yield* db.select({
|
|
2729
|
+
recipientEmail: publicCompletionInvitationAttempt.email,
|
|
2730
|
+
failureReason: toDo.correctionFailureReason
|
|
2731
|
+
}).from(toDo).innerJoin(publicCompletionInvitationAttempt, eq(toDo.correctionInvitationAttemptId, publicCompletionInvitationAttempt.id)).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false), isNull(toDo.completedByUserId), isNull(toDo.completedByExternalParticipantId), isNull(toDo.completedByRoleId), isNull(toDo.failureReason), isNotNull(toDo.correctionRequiredAt), eq(publicCompletionInvitationAttempt._deleted, false))).limit(1);
|
|
2732
|
+
return rows[0] ?? null;
|
|
2733
|
+
}),
|
|
2734
|
+
clearPublicCompletionCorrectionRequired: (todoId) => Effect19.gen(function* () {
|
|
2735
|
+
const requestTime = yield* getRequestTime();
|
|
2736
|
+
const userDetails = yield* getUserDetails();
|
|
2737
|
+
const rows = yield* db.update(toDo).set({
|
|
2738
|
+
correctionRequiredAt: null,
|
|
2739
|
+
correctionFailureReason: null,
|
|
2740
|
+
correctionInvitationAttemptId: null,
|
|
2741
|
+
updatedAt: requestTime,
|
|
2742
|
+
updatedBy: userDetails.by
|
|
2743
|
+
}).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false), isNull(toDo.completedByUserId), isNull(toDo.completedByExternalParticipantId), isNull(toDo.completedByRoleId), isNull(toDo.failureReason), isNotNull(toDo.correctionRequiredAt))).returning({
|
|
2744
|
+
id: toDo.id,
|
|
2745
|
+
processExecutionId: toDo.processExecutionId
|
|
2746
|
+
});
|
|
2747
|
+
const row = rows[0];
|
|
2748
|
+
if (!row)
|
|
2749
|
+
return false;
|
|
2750
|
+
yield* db.update(processExecution).set({
|
|
2751
|
+
updatedAt: requestTime,
|
|
2752
|
+
updatedBy: userDetails.by
|
|
2753
|
+
}).where(eq(processExecution.id, row.processExecutionId));
|
|
2754
|
+
return true;
|
|
2755
|
+
}),
|
|
2756
|
+
updateProcessState: (processStateId, data) => Effect19.gen(function* () {
|
|
2757
|
+
const requestTime = yield* getRequestTime();
|
|
2758
|
+
const userDetails = yield* getUserDetails();
|
|
2759
|
+
yield* db.update(processState).set({
|
|
2760
|
+
state: sql`json_patch(${processState.state}, ${globalThis.JSON.stringify(data)})`,
|
|
2761
|
+
updatedAt: requestTime,
|
|
2762
|
+
updatedBy: userDetails.by
|
|
2763
|
+
}).where(eq(processState.id, processStateId));
|
|
2764
|
+
}),
|
|
2765
|
+
updateProcessStateIfUnchanged: (processStateId, expectedUpdatedAt, data) => Effect19.gen(function* () {
|
|
2766
|
+
const requestTime = yield* getRequestTime();
|
|
2767
|
+
const userDetails = yield* getUserDetails();
|
|
2768
|
+
const updatedAt = DateTime5.toEpochMillis(requestTime) > DateTime5.toEpochMillis(expectedUpdatedAt) ? requestTime : DateTime5.add(expectedUpdatedAt, { milliseconds: 1 });
|
|
2769
|
+
const rows = yield* db.update(processState).set({
|
|
2770
|
+
state: sql`json_patch(${processState.state}, ${globalThis.JSON.stringify(data)})`,
|
|
2771
|
+
updatedAt,
|
|
2772
|
+
updatedBy: userDetails.by
|
|
2773
|
+
}).where(and(eq(processState.id, processStateId), sql`ROUND((${processState.updatedAt} - 2440587.5) * 86400000) = ${Math.round(DateTime5.toEpochMillis(expectedUpdatedAt))}`)).returning({
|
|
2774
|
+
updatedAtMs: sql`ROUND((${processState.updatedAt} - 2440587.5) * 86400000)`
|
|
2775
|
+
});
|
|
2776
|
+
const row = rows[0];
|
|
2777
|
+
return row ? {
|
|
2778
|
+
kind: "updated",
|
|
2779
|
+
updatedAt: DateTime5.makeUnsafe(row.updatedAtMs)
|
|
2780
|
+
} : { kind: "conflict" };
|
|
2781
|
+
}),
|
|
2782
|
+
appendProcessStateArrayItem: (processStateId, stateKey, item) => Effect19.gen(function* () {
|
|
2783
|
+
const requestTime = yield* getRequestTime();
|
|
2784
|
+
const userDetails = yield* getUserDetails();
|
|
2785
|
+
const path = `$.${stateKey}`;
|
|
2786
|
+
const itemJson = globalThis.JSON.stringify(item);
|
|
2787
|
+
yield* db.update(processState).set({
|
|
2788
|
+
state: sql`json_set(COALESCE(${processState.state}, json('{}')), ${path}, json_insert(COALESCE(json_extract(${processState.state}, ${path}), json('[]')), '$[#]', json(${itemJson})))`,
|
|
2789
|
+
updatedAt: requestTime,
|
|
2790
|
+
updatedBy: userDetails.by
|
|
2791
|
+
}).where(eq(processState.id, processStateId));
|
|
2792
|
+
}),
|
|
2793
|
+
appendProcessStateArrayItemIfUnchanged: (processStateId, expectedUpdatedAt, stateKey, item) => Effect19.gen(function* () {
|
|
2794
|
+
const requestTime = yield* getRequestTime();
|
|
2795
|
+
const userDetails = yield* getUserDetails();
|
|
2796
|
+
const updatedAt = DateTime5.toEpochMillis(requestTime) > DateTime5.toEpochMillis(expectedUpdatedAt) ? requestTime : DateTime5.add(expectedUpdatedAt, { milliseconds: 1 });
|
|
2797
|
+
const path = `$.${stateKey}`;
|
|
2798
|
+
const itemJson = globalThis.JSON.stringify(item);
|
|
2799
|
+
const rows = yield* db.update(processState).set({
|
|
2800
|
+
state: sql`json_set(COALESCE(${processState.state}, json('{}')), ${path}, json_insert(COALESCE(json_extract(${processState.state}, ${path}), json('[]')), '$[#]', json(${itemJson})))`,
|
|
2801
|
+
updatedAt,
|
|
2802
|
+
updatedBy: userDetails.by
|
|
2803
|
+
}).where(and(eq(processState.id, processStateId), sql`ROUND((${processState.updatedAt} - 2440587.5) * 86400000) = ${Math.round(DateTime5.toEpochMillis(expectedUpdatedAt))}`)).returning({
|
|
2804
|
+
updatedAtMs: sql`ROUND((${processState.updatedAt} - 2440587.5) * 86400000)`
|
|
2805
|
+
});
|
|
2806
|
+
const row = rows[0];
|
|
2807
|
+
return row ? {
|
|
2808
|
+
kind: "updated",
|
|
2809
|
+
updatedAt: DateTime5.makeUnsafe(row.updatedAtMs)
|
|
2810
|
+
} : { kind: "conflict" };
|
|
2811
|
+
}),
|
|
2812
|
+
completeToDo: (todoId, userId, businessDurationMs, externalParticipantId, completedByRoleId) => Effect19.gen(function* () {
|
|
2813
|
+
const requestTime = yield* getRequestTime();
|
|
2814
|
+
const userDetails = yield* getUserDetails();
|
|
2815
|
+
yield* db.update(toDo).set({
|
|
2816
|
+
completedByUserId: userId,
|
|
2817
|
+
...externalParticipantId !== undefined ? { completedByExternalParticipantId: externalParticipantId } : {},
|
|
2818
|
+
...completedByRoleId !== undefined ? { completedByRoleId } : {},
|
|
2819
|
+
businessDuration: businessDurationMs,
|
|
2820
|
+
failureReason: null,
|
|
2821
|
+
notStartedReason: null,
|
|
2822
|
+
correctionRequiredAt: null,
|
|
2823
|
+
correctionFailureReason: null,
|
|
2824
|
+
correctionInvitationAttemptId: null,
|
|
2825
|
+
_deleted: true,
|
|
2826
|
+
updatedAt: requestTime,
|
|
2827
|
+
updatedBy: userDetails.by
|
|
2828
|
+
}).where(eq(toDo.id, todoId));
|
|
2829
|
+
const rows = yield* db.select({
|
|
2830
|
+
id: toDo.id,
|
|
2831
|
+
processExecutionId: toDo.processExecutionId,
|
|
2832
|
+
flowId: toDo.flowId,
|
|
2833
|
+
processName: process2.name,
|
|
2834
|
+
processPath: process2.path,
|
|
2835
|
+
processOrgUnitPath: orgUnit.path,
|
|
2836
|
+
stepName: step.name,
|
|
2837
|
+
stepPath: step.path,
|
|
2838
|
+
rolePath: role.path,
|
|
2839
|
+
assignedToProviderUserId: toDo.assignedToProviderUserId,
|
|
2840
|
+
assignedToProviderUserEmail: providerUser.email,
|
|
2841
|
+
role: role.name,
|
|
2842
|
+
description: step.purpose,
|
|
2843
|
+
formFields: step.formFields,
|
|
2844
|
+
updatedAt: sql`(${toDo.updatedAt} - 2440587.5) * 86400000`.as("updated_at_millis"),
|
|
2845
|
+
createdAt: sql`strftime('%Y-%m-%dT%H:%M:%fZ', (${toDo.createdAt} - 2440587.5) * 86400, 'unixepoch')`.as("created_at_iso"),
|
|
2846
|
+
slaTargetAt: sql`CASE WHEN ${toDo.slaTargetAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${toDo.slaTargetAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_target_at_iso"),
|
|
2847
|
+
slaWarningAt: sql`CASE WHEN ${toDo.slaWarningAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${toDo.slaWarningAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_warning_at_iso"),
|
|
2848
|
+
deleted: toDo._deleted
|
|
2849
|
+
}).from(toDo).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(process2, eq(processState.processId, process2.id)).innerJoin(orgUnit, eq(process2.orgUnitId, orgUnit.id)).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).leftJoin(role, eq(step.roleId, role.id)).leftJoin(providerUser, eq(toDo.assignedToProviderUserId, providerUser.id)).where(eq(toDo.id, todoId)).limit(1);
|
|
2850
|
+
assert(rows[0]);
|
|
2851
|
+
const row = rows[0];
|
|
2852
|
+
return {
|
|
2853
|
+
id: row.id,
|
|
2854
|
+
processExecutionId: row.processExecutionId,
|
|
2855
|
+
flowId: row.flowId,
|
|
2856
|
+
processName: row.processName,
|
|
2857
|
+
processPath: row.processPath,
|
|
2858
|
+
processOrgUnitPath: row.processOrgUnitPath,
|
|
2859
|
+
stepName: row.stepName,
|
|
2860
|
+
stepPath: row.stepPath,
|
|
2861
|
+
rolePath: row.rolePath,
|
|
2862
|
+
assignedToProviderUserId: row.assignedToProviderUserId,
|
|
2863
|
+
assignedToProviderUserEmail: row.assignedToProviderUserEmail,
|
|
2864
|
+
role: row.role,
|
|
2865
|
+
description: row.description,
|
|
2866
|
+
status: "Active",
|
|
2867
|
+
priority: "Medium",
|
|
2868
|
+
assignedAt: row.createdAt,
|
|
2869
|
+
dueAt: row.slaTargetAt,
|
|
2870
|
+
dueWarningAt: row.slaWarningAt,
|
|
2871
|
+
formComplexity: calculateFormComplexity(row.formFields),
|
|
2872
|
+
updatedAt: row.updatedAt,
|
|
2873
|
+
deleted: row.deleted,
|
|
2874
|
+
summary: []
|
|
2875
|
+
};
|
|
2876
|
+
}),
|
|
2877
|
+
completeToDoIfOpen: (input) => Effect19.gen(function* () {
|
|
2878
|
+
const requestTime = yield* getRequestTime();
|
|
2879
|
+
const userDetails = yield* getUserDetails();
|
|
2880
|
+
const rows = yield* db.update(toDo).set({
|
|
2881
|
+
completedByUserId: input.userId,
|
|
2882
|
+
completedByExternalParticipantId: input.externalParticipantId,
|
|
2883
|
+
completedByRoleId: input.completedByRoleId,
|
|
2884
|
+
completionFingerprint: input.completionFingerprint ?? null,
|
|
2885
|
+
businessDuration: input.businessDurationMs,
|
|
2886
|
+
failureReason: null,
|
|
2887
|
+
notStartedReason: null,
|
|
2888
|
+
correctionRequiredAt: null,
|
|
2889
|
+
correctionFailureReason: null,
|
|
2890
|
+
correctionInvitationAttemptId: null,
|
|
2891
|
+
_deleted: true,
|
|
2892
|
+
updatedAt: requestTime,
|
|
2893
|
+
updatedBy: userDetails.by
|
|
2894
|
+
}).where(and(eq(toDo.id, input.todoId), eq(toDo._deleted, false))).returning({ id: toDo.id });
|
|
2895
|
+
if (rows[0])
|
|
2896
|
+
return { kind: "completed" };
|
|
2897
|
+
const existing = yield* db.select({
|
|
2898
|
+
deleted: toDo._deleted,
|
|
2899
|
+
completedByUserId: toDo.completedByUserId,
|
|
2900
|
+
completedByExternalParticipantId: toDo.completedByExternalParticipantId,
|
|
2901
|
+
completedByRoleId: toDo.completedByRoleId,
|
|
2902
|
+
completionFingerprint: toDo.completionFingerprint,
|
|
2903
|
+
businessDuration: toDo.businessDuration
|
|
2904
|
+
}).from(toDo).where(and(eq(toDo.id, input.todoId), isNull(toDo.interruptedAt))).limit(1);
|
|
2905
|
+
const row = existing[0];
|
|
2906
|
+
if (!row)
|
|
2907
|
+
return { kind: "not-found" };
|
|
2908
|
+
if (row.deleted && row.completedByUserId === input.userId && row.completedByExternalParticipantId === input.externalParticipantId && (input.completionFingerprint === undefined ? row.completedByRoleId === input.completedByRoleId : row.completionFingerprint === input.completionFingerprint)) {
|
|
2909
|
+
return { kind: "already-completed" };
|
|
2910
|
+
}
|
|
2911
|
+
return { kind: "conflict" };
|
|
2912
|
+
}),
|
|
2913
|
+
completeAsyncToDo: (todoId, userId, businessDurationMs, completedByRoleId) => Effect19.gen(function* () {
|
|
2914
|
+
const requestTime = yield* getRequestTime();
|
|
2915
|
+
const userDetails = yield* getUserDetails();
|
|
2916
|
+
const result = yield* db.update(toDo).set({
|
|
2917
|
+
completedByUserId: userId,
|
|
2918
|
+
businessDuration: businessDurationMs,
|
|
2919
|
+
failureReason: null,
|
|
2920
|
+
notStartedReason: null,
|
|
2921
|
+
correctionRequiredAt: null,
|
|
2922
|
+
correctionFailureReason: null,
|
|
2923
|
+
correctionInvitationAttemptId: null,
|
|
2924
|
+
_deleted: true,
|
|
2925
|
+
...completedByRoleId !== undefined ? { completedByRoleId } : {},
|
|
2926
|
+
updatedAt: requestTime,
|
|
2927
|
+
updatedBy: userDetails.by
|
|
2928
|
+
}).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false))).returning({ id: toDo.id });
|
|
2929
|
+
return result.length > 0;
|
|
2930
|
+
}),
|
|
2931
|
+
failToDo: (todoId, failureReason) => Effect19.gen(function* () {
|
|
2932
|
+
const requestTime = yield* getRequestTime();
|
|
2933
|
+
const userDetails = yield* getUserDetails();
|
|
2934
|
+
yield* db.update(toDo).set({
|
|
2935
|
+
failureReason,
|
|
2936
|
+
notStartedReason: null,
|
|
2937
|
+
correctionRequiredAt: null,
|
|
2938
|
+
correctionFailureReason: null,
|
|
2939
|
+
correctionInvitationAttemptId: null,
|
|
2940
|
+
completedByUserId: null,
|
|
2941
|
+
_deleted: false,
|
|
2942
|
+
updatedAt: requestTime,
|
|
2943
|
+
updatedBy: userDetails.by
|
|
2944
|
+
}).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false)));
|
|
2945
|
+
}),
|
|
2946
|
+
failAsyncToDo: (todoId, failureReason) => Effect19.gen(function* () {
|
|
2947
|
+
const requestTime = yield* getRequestTime();
|
|
2948
|
+
const userDetails = yield* getUserDetails();
|
|
2949
|
+
const result = yield* db.update(toDo).set({
|
|
2950
|
+
failureReason,
|
|
2951
|
+
notStartedReason: null,
|
|
2952
|
+
updatedAt: requestTime,
|
|
2953
|
+
updatedBy: userDetails.by
|
|
2954
|
+
}).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false), isNull(toDo.failureReason), isNull(toDo.correctionRequiredAt))).returning({ id: toDo.id });
|
|
2955
|
+
return result.length > 0;
|
|
2956
|
+
}),
|
|
2957
|
+
getProcessStateByTodoId: (todoId) => Effect19.gen(function* () {
|
|
2958
|
+
const result = yield* db.select({
|
|
2959
|
+
processExecutionId: processExecution.id,
|
|
2960
|
+
processStateId: processState.id,
|
|
2961
|
+
state: processState.state,
|
|
2962
|
+
updatedAtMs: sql`ROUND((${processState.updatedAt} - 2440587.5) * 86400000)`,
|
|
2963
|
+
processStartedAt: sql`(${processExecution.createdAt} - 2440587.5) * 86400000`.as("process_started_at_millis")
|
|
2964
|
+
}).from(toDo).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(processState, eq(processExecution.processStateId, processState.id)).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false))).limit(1);
|
|
2965
|
+
if (!result[0]) {
|
|
2966
|
+
return null;
|
|
2967
|
+
}
|
|
2968
|
+
const StateSchema = Schema.Unknown.check(Schema.makeFilter((value) => typeof value === "object" && value !== null && !Array.isArray(value))).pipe(Schema.decodeTo(Schema.Record(Schema.String, Schema.Unknown)));
|
|
2969
|
+
const parseResult = Schema.decodeUnknownResult(StateSchema)(result[0].state ?? {});
|
|
2970
|
+
if (parseResult._tag === "Failure") {
|
|
2971
|
+
return yield* new InvalidProcessStateError({
|
|
2972
|
+
processStateId: result[0].processStateId,
|
|
2973
|
+
message: `Process state has invalid format in database`
|
|
2974
|
+
});
|
|
2975
|
+
}
|
|
2976
|
+
return {
|
|
2977
|
+
processExecutionId: result[0].processExecutionId,
|
|
2978
|
+
processStateId: result[0].processStateId,
|
|
2979
|
+
state: parseResult.success,
|
|
2980
|
+
updatedAt: DateTime5.makeUnsafe(result[0].updatedAtMs),
|
|
2981
|
+
processStartedAt: DateTime5.fromDateUnsafe(new Date(result[0].processStartedAt))
|
|
2982
|
+
};
|
|
2983
|
+
}),
|
|
2984
|
+
countActiveTodos: (processExecutionId) => Effect19.gen(function* () {
|
|
2985
|
+
const result = yield* db.select({ count: sql`COUNT(*)`.as("count") }).from(toDo).where(and(eq(toDo.processExecutionId, processExecutionId), eq(toDo._deleted, false)));
|
|
2986
|
+
return Number(result[0]?.count ?? 0);
|
|
2987
|
+
}),
|
|
2988
|
+
countPendingFlowJobs: (processExecutionId, queueName) => Effect19.gen(function* () {
|
|
2989
|
+
const result = yield* db.select({ count: sql`COUNT(*)`.as("count") }).from(jobQueue).where(and(eq(jobQueue.queue, queueName), eq(jobQueue._deleted, false), sql`json_extract(${jobQueue.jobPayload}, '$.processExecutionId') = ${processExecutionId}`));
|
|
2990
|
+
return Number(result[0]?.count ?? 0);
|
|
2991
|
+
}),
|
|
2992
|
+
setProcessExecutionFinished: (processExecutionId, businessDurationMs) => Effect19.gen(function* () {
|
|
2993
|
+
const requestTime = yield* getRequestTime();
|
|
2994
|
+
const userDetails = yield* getUserDetails();
|
|
2995
|
+
yield* db.update(processExecution).set({
|
|
2996
|
+
finishedAt: requestTime,
|
|
2997
|
+
businessDuration: businessDurationMs,
|
|
2998
|
+
updatedAt: requestTime,
|
|
2999
|
+
updatedBy: userDetails.by
|
|
3000
|
+
}).where(eq(processExecution.id, processExecutionId));
|
|
3001
|
+
}),
|
|
3002
|
+
getProcessStatesByTodoIds: (todoIds) => Effect19.gen(function* () {
|
|
3003
|
+
if (todoIds.length === 0) {
|
|
3004
|
+
return [];
|
|
3005
|
+
}
|
|
3006
|
+
const results = yield* db.select({
|
|
3007
|
+
todoId: toDo.id,
|
|
3008
|
+
processExecutionId: processExecution.id,
|
|
3009
|
+
processStateId: processState.id,
|
|
3010
|
+
state: processState.state,
|
|
3011
|
+
stepPath: step.path,
|
|
3012
|
+
itemData: toDo.itemData,
|
|
3013
|
+
processStartedAt: sql`(${processExecution.createdAt} - 2440587.5) * 86400000`.as("process_started_at_millis")
|
|
3014
|
+
}).from(toDo).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).where(inArray(toDo.id, todoIds));
|
|
3015
|
+
const StateSchema = Schema.Unknown.check(Schema.makeFilter((value) => typeof value === "object" && value !== null && !Array.isArray(value))).pipe(Schema.decodeTo(Schema.Record(Schema.String, Schema.Unknown)));
|
|
3016
|
+
const validated = [];
|
|
3017
|
+
for (const result of results) {
|
|
3018
|
+
const parseResult = Schema.decodeUnknownResult(StateSchema)(result.state ?? {});
|
|
3019
|
+
if (parseResult._tag === "Failure") {
|
|
3020
|
+
return yield* new InvalidProcessStateError({
|
|
3021
|
+
processStateId: result.processStateId,
|
|
3022
|
+
message: `Process state has invalid format in database`
|
|
3023
|
+
});
|
|
3024
|
+
}
|
|
3025
|
+
validated.push({
|
|
3026
|
+
todoId: result.todoId,
|
|
3027
|
+
processExecutionId: result.processExecutionId,
|
|
3028
|
+
processStateId: result.processStateId,
|
|
3029
|
+
state: parseResult.success,
|
|
3030
|
+
stepPath: result.stepPath,
|
|
3031
|
+
processStartedAt: DateTime5.fromDateUnsafe(new Date(result.processStartedAt)),
|
|
3032
|
+
itemData: result.itemData
|
|
3033
|
+
});
|
|
3034
|
+
}
|
|
3035
|
+
return validated;
|
|
3036
|
+
}),
|
|
3037
|
+
getCompletedStepsForExecutions,
|
|
3038
|
+
getCompletedStepsForExecution: (processExecutionId) => getCompletedStepsForExecutions([processExecutionId]).pipe(Effect19.map((steps) => steps.get(processExecutionId) ?? [])),
|
|
3039
|
+
queryFailedTodosForExecution: (executionId) => Effect19.gen(function* () {
|
|
3040
|
+
const results = yield* db.select({
|
|
3041
|
+
todoId: toDo.id,
|
|
3042
|
+
stepPath: step.path,
|
|
3043
|
+
isSystemStep: sql`CASE WHEN ${step.roleId} IS NULL THEN 1 ELSE 0 END`.as("is_system_step")
|
|
3044
|
+
}).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).where(and(eq(toDo.processExecutionId, executionId), eq(toDo._deleted, false), isNotNull(toDo.failureReason)));
|
|
3045
|
+
return results.map((row) => ({
|
|
3046
|
+
todoId: row.todoId,
|
|
3047
|
+
stepPath: row.stepPath,
|
|
3048
|
+
isSystemStep: row.isSystemStep
|
|
3049
|
+
}));
|
|
3050
|
+
}),
|
|
3051
|
+
failSystemStepAttempt: ({
|
|
3052
|
+
todoId,
|
|
3053
|
+
expectedWriteAttemptId,
|
|
3054
|
+
expectedRestartAttemptId,
|
|
3055
|
+
failureReason,
|
|
3056
|
+
nextWriteAttemptId
|
|
3057
|
+
}) => Effect19.gen(function* () {
|
|
3058
|
+
const requestTime = yield* getRequestTime();
|
|
3059
|
+
const userDetails = yield* getUserDetails();
|
|
3060
|
+
const rows = yield* db.update(toDo).set({
|
|
3061
|
+
failureReason,
|
|
3062
|
+
externalWriteAttemptId: nextWriteAttemptId ?? expectedWriteAttemptId,
|
|
3063
|
+
updatedAt: requestTime,
|
|
3064
|
+
updatedBy: userDetails.by
|
|
3065
|
+
}).where(and(eq(toDo.id, todoId), eq(toDo._deleted, false), isNull(toDo.failureReason), expectedRestartAttemptId === null ? isNull(toDo.restartAttemptId) : eq(toDo.restartAttemptId, expectedRestartAttemptId), expectedWriteAttemptId === null ? isNull(toDo.externalWriteAttemptId) : eq(toDo.externalWriteAttemptId, expectedWriteAttemptId))).returning({ id: toDo.id });
|
|
3066
|
+
return rows.length === 1;
|
|
3067
|
+
}),
|
|
3068
|
+
clearTodoFailures: (todoIds, restartAttemptId) => Effect19.gen(function* () {
|
|
3069
|
+
if (todoIds.length === 0) {
|
|
3070
|
+
return;
|
|
3071
|
+
}
|
|
3072
|
+
const requestTime = yield* getRequestTime();
|
|
3073
|
+
const userDetails = yield* getUserDetails();
|
|
3074
|
+
yield* db.update(toDo).set({
|
|
3075
|
+
failureReason: null,
|
|
3076
|
+
notStartedReason: null,
|
|
3077
|
+
restartAttemptId,
|
|
3078
|
+
updatedAt: requestTime,
|
|
3079
|
+
updatedBy: userDetails.by
|
|
3080
|
+
}).where(and(inArray(toDo.id, todoIds), isNotNull(toDo.failureReason), eq(toDo._deleted, false)));
|
|
3081
|
+
}),
|
|
3082
|
+
clearProcessExecutionFinished: (executionId) => Effect19.gen(function* () {
|
|
3083
|
+
const requestTime = yield* getRequestTime();
|
|
3084
|
+
const userDetails = yield* getUserDetails();
|
|
3085
|
+
yield* db.update(processExecution).set({
|
|
3086
|
+
finishedAt: null,
|
|
3087
|
+
businessDuration: null,
|
|
3088
|
+
abandonedReason: null,
|
|
3089
|
+
updatedAt: requestTime,
|
|
3090
|
+
updatedBy: userDetails.by
|
|
3091
|
+
}).where(eq(processExecution.id, executionId));
|
|
3092
|
+
}),
|
|
3093
|
+
reopenFailedSystemStartExecution: (executionId, restartAttemptId) => Effect19.gen(function* () {
|
|
3094
|
+
const requestTime = yield* getRequestTime();
|
|
3095
|
+
const userDetails = yield* getUserDetails();
|
|
3096
|
+
const rows = yield* db.update(processExecution).set({
|
|
3097
|
+
finishedAt: null,
|
|
3098
|
+
businessDuration: null,
|
|
3099
|
+
abandonedReason: null,
|
|
3100
|
+
restartAttemptId,
|
|
3101
|
+
updatedAt: requestTime,
|
|
3102
|
+
updatedBy: userDetails.by
|
|
3103
|
+
}).where(and(eq(processExecution.id, executionId), isNotNull(processExecution.finishedAt), isNull(processExecution.abandonedAt), isNotNull(processExecution.abandonedReason))).returning({ id: processExecution.id });
|
|
3104
|
+
return rows.length > 0;
|
|
3105
|
+
}),
|
|
3106
|
+
queryActiveTodoStepPaths: (executionId) => Effect19.gen(function* () {
|
|
3107
|
+
const results = yield* db.selectDistinct({
|
|
3108
|
+
stepPath: step.path
|
|
3109
|
+
}).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).where(and(eq(toDo.processExecutionId, executionId), eq(toDo._deleted, false), isNull(toDo.failureReason)));
|
|
3110
|
+
return results.map((r) => r.stepPath);
|
|
3111
|
+
}),
|
|
3112
|
+
setProcessExecutionAbandoned: (executionId, reason) => Effect19.gen(function* () {
|
|
3113
|
+
const requestTime = yield* getRequestTime();
|
|
3114
|
+
const userDetails = yield* getUserDetails();
|
|
3115
|
+
yield* db.update(processExecution).set({
|
|
3116
|
+
finishedAt: requestTime,
|
|
3117
|
+
abandonedAt: requestTime,
|
|
3118
|
+
updatedAt: requestTime,
|
|
3119
|
+
updatedBy: userDetails.by,
|
|
3120
|
+
...reason === undefined ? {} : { abandonedReason: reason }
|
|
3121
|
+
}).where(eq(processExecution.id, executionId));
|
|
3122
|
+
}),
|
|
3123
|
+
softDeleteActiveTodosForExecution: (executionId) => Effect19.gen(function* () {
|
|
3124
|
+
const requestTime = yield* getRequestTime();
|
|
3125
|
+
const userDetails = yield* getUserDetails();
|
|
3126
|
+
const result = yield* db.update(toDo).set({
|
|
3127
|
+
_deleted: true,
|
|
3128
|
+
failureReason: "Execution abandoned",
|
|
3129
|
+
updatedAt: requestTime,
|
|
3130
|
+
updatedBy: userDetails.by
|
|
3131
|
+
}).where(and(eq(toDo.processExecutionId, executionId), eq(toDo._deleted, false))).returning({ id: toDo.id });
|
|
3132
|
+
return result.map((r) => r.id);
|
|
3133
|
+
})
|
|
3134
|
+
};
|
|
3135
|
+
}));
|
|
3136
|
+
|
|
3137
|
+
|
|
3138
|
+
import { Effect as Effect20, Layer as Layer20 } from "effect";
|
|
3139
|
+
var SqliteStepRoleQueriesLive = Layer20.effect(StepRoleQueries, Effect20.gen(function* () {
|
|
3140
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3141
|
+
const querySupportingRolePaths = (stepPath) => Effect20.gen(function* () {
|
|
3142
|
+
const results = yield* db.select({ path: role.path }).from(stepSupportingRole).innerJoin(role, eq(stepSupportingRole.roleId, role.id)).innerJoin(step, eq(stepSupportingRole.stepId, step.id)).where(and(eq(step.path, stepPath), eq(stepSupportingRole._deleted, false), eq(role._deleted, false))).orderBy(asc(stepSupportingRole.createdAt));
|
|
3143
|
+
return results.map((r) => r.path);
|
|
3144
|
+
});
|
|
3145
|
+
const emptyResult = {
|
|
3146
|
+
rolePath: null,
|
|
3147
|
+
supportingRolePaths: [],
|
|
3148
|
+
startsProcess: false,
|
|
3149
|
+
embedded: false
|
|
3150
|
+
};
|
|
3151
|
+
return {
|
|
3152
|
+
queryRolePathsByStepPath: (stepPath) => Effect20.gen(function* () {
|
|
3153
|
+
const stepInfo = yield* db.select({
|
|
3154
|
+
rolePath: role.path,
|
|
3155
|
+
canStartProcess: stepItsCanStartProcess.canStartProcess,
|
|
3156
|
+
embedded: step.embedded
|
|
3157
|
+
}).from(step).leftJoin(role, eq(step.roleId, role.id)).innerJoin(stepItsCanStartProcess, eq(step.id, stepItsCanStartProcess.id)).where(and(eq(step.path, stepPath), eq(step._deleted, false), or(isNull(role.id), eq(role._deleted, false)))).limit(1);
|
|
3158
|
+
const firstStep = stepInfo[0];
|
|
3159
|
+
if (!firstStep) {
|
|
3160
|
+
return { ...emptyResult };
|
|
3161
|
+
}
|
|
3162
|
+
const supportingRolePaths = yield* querySupportingRolePaths(stepPath);
|
|
3163
|
+
return {
|
|
3164
|
+
rolePath: firstStep.rolePath,
|
|
3165
|
+
supportingRolePaths,
|
|
3166
|
+
startsProcess: firstStep.canStartProcess,
|
|
3167
|
+
embedded: firstStep.embedded
|
|
3168
|
+
};
|
|
3169
|
+
}),
|
|
3170
|
+
queryRolePathsByStepPaths: (stepPaths) => Effect20.gen(function* () {
|
|
3171
|
+
if (stepPaths.length === 0) {
|
|
3172
|
+
return new Map;
|
|
3173
|
+
}
|
|
3174
|
+
const stepInfoResults = yield* db.select({
|
|
3175
|
+
stepId: step.id,
|
|
3176
|
+
stepPath: step.path,
|
|
3177
|
+
rolePath: role.path,
|
|
3178
|
+
canStartProcess: stepItsCanStartProcess.canStartProcess,
|
|
3179
|
+
embedded: step.embedded
|
|
3180
|
+
}).from(step).leftJoin(role, eq(step.roleId, role.id)).innerJoin(stepItsCanStartProcess, eq(step.id, stepItsCanStartProcess.id)).where(and(inArray(step.path, stepPaths), eq(step._deleted, false), or(isNull(role.id), eq(role._deleted, false))));
|
|
3181
|
+
const stepIds = stepInfoResults.map((s) => s.stepId);
|
|
3182
|
+
const allSupporting = stepIds.length > 0 ? yield* db.select({
|
|
3183
|
+
stepPath: step.path,
|
|
3184
|
+
rolePath: role.path
|
|
3185
|
+
}).from(stepSupportingRole).innerJoin(role, eq(stepSupportingRole.roleId, role.id)).innerJoin(step, eq(stepSupportingRole.stepId, step.id)).where(and(inArray(step.id, stepIds), eq(stepSupportingRole._deleted, false), eq(role._deleted, false))).orderBy(asc(stepSupportingRole.createdAt)) : [];
|
|
3186
|
+
const supportingByPath = new Map;
|
|
3187
|
+
for (const r of allSupporting) {
|
|
3188
|
+
const paths = supportingByPath.get(r.stepPath);
|
|
3189
|
+
if (paths) {
|
|
3190
|
+
paths.push(r.rolePath);
|
|
3191
|
+
} else {
|
|
3192
|
+
supportingByPath.set(r.stepPath, [r.rolePath]);
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
3195
|
+
const map = new Map;
|
|
3196
|
+
for (const p of stepPaths) {
|
|
3197
|
+
map.set(p, { ...emptyResult });
|
|
3198
|
+
}
|
|
3199
|
+
for (const s of stepInfoResults) {
|
|
3200
|
+
map.set(s.stepPath, {
|
|
3201
|
+
rolePath: s.rolePath,
|
|
3202
|
+
supportingRolePaths: supportingByPath.get(s.stepPath) ?? [],
|
|
3203
|
+
startsProcess: s.canStartProcess,
|
|
3204
|
+
embedded: s.embedded
|
|
3205
|
+
});
|
|
3206
|
+
}
|
|
3207
|
+
return map;
|
|
3208
|
+
}),
|
|
3209
|
+
queryRoleIdByPath: (rolePath) => Effect20.gen(function* () {
|
|
3210
|
+
const results = yield* db.select({ id: role.id }).from(role).where(and(eq(role.path, rolePath), eq(role._deleted, false))).limit(1);
|
|
3211
|
+
return results[0]?.id;
|
|
3212
|
+
})
|
|
3213
|
+
};
|
|
3214
|
+
}));
|
|
3215
|
+
|
|
3216
|
+
|
|
3217
|
+
import { Effect as Effect21, Layer as Layer21 } from "effect";
|
|
3218
|
+
var SqliteSystemUserOperationsLive = Layer21.effect(SystemUserOperations, Effect21.gen(function* () {
|
|
3219
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3220
|
+
return {
|
|
3221
|
+
registerInvitation: (input) => Effect21.gen(function* () {
|
|
3222
|
+
const requestTime = yield* getRequestTime();
|
|
3223
|
+
const userDetails = yield* getUserDetails();
|
|
3224
|
+
const normalizedEmail = input.email.trim().toLowerCase();
|
|
3225
|
+
yield* db.insert(invitation).values({
|
|
3226
|
+
invitationId: input.invitationId,
|
|
3227
|
+
email: normalizedEmail,
|
|
3228
|
+
invitationStatus: "pending",
|
|
3229
|
+
invitationSource: "process",
|
|
3230
|
+
invitationPendingEmail: normalizedEmail,
|
|
3231
|
+
createdAt: requestTime,
|
|
3232
|
+
updatedAt: requestTime,
|
|
3233
|
+
createdBy: userDetails.by,
|
|
3234
|
+
updatedBy: userDetails.by
|
|
3235
|
+
});
|
|
3236
|
+
})
|
|
3237
|
+
};
|
|
3238
|
+
}));
|
|
3239
|
+
|
|
3240
|
+
|
|
3241
|
+
import { Effect as Effect22, Layer as Layer22 } from "effect";
|
|
3242
|
+
var todoUpdatedAtMillis = sql`CAST(ROUND((${toDo.updatedAt} - 2440587.5) * 86400000) AS INTEGER)`;
|
|
3243
|
+
var buildTodoBaseQuery = (db) => db.select({
|
|
3244
|
+
id: toDo.id,
|
|
3245
|
+
processExecutionId: toDo.processExecutionId,
|
|
3246
|
+
flowId: toDo.flowId,
|
|
3247
|
+
processName: process2.name,
|
|
3248
|
+
processPath: process2.path,
|
|
3249
|
+
processOrgUnitPath: orgUnit.path,
|
|
3250
|
+
stepName: step.name,
|
|
3251
|
+
stepPath: step.path,
|
|
3252
|
+
rolePath: role.path,
|
|
3253
|
+
assignedToProviderUserId: toDo.assignedToProviderUserId,
|
|
3254
|
+
assignedToProviderUserEmail: providerUser.email,
|
|
3255
|
+
role: role.name,
|
|
3256
|
+
description: step.purpose,
|
|
3257
|
+
formFields: step.formFields,
|
|
3258
|
+
correctionRequiredAt: toDo.correctionRequiredAt,
|
|
3259
|
+
updatedAt: todoUpdatedAtMillis.as("updated_at_millis"),
|
|
3260
|
+
createdAt: sql`strftime('%Y-%m-%dT%H:%M:%fZ', (${toDo.createdAt} - 2440587.5) * 86400, 'unixepoch')`.as("created_at_iso"),
|
|
3261
|
+
slaTargetAt: sql`CASE WHEN ${toDo.slaTargetAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${toDo.slaTargetAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_target_at_iso"),
|
|
3262
|
+
slaWarningAt: sql`CASE WHEN ${toDo.slaWarningAt} IS NOT NULL THEN strftime('%Y-%m-%dT%H:%M:%fZ', (${toDo.slaWarningAt} - 2440587.5) * 86400, 'unixepoch') ELSE NULL END`.as("sla_warning_at_iso"),
|
|
3263
|
+
deleted: toDo._deleted
|
|
3264
|
+
}).from(toDo).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(processState, eq(processExecution.processStateId, processState.id)).innerJoin(process2, eq(processState.processId, process2.id)).innerJoin(orgUnit, eq(process2.orgUnitId, orgUnit.id)).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).innerJoin(role, eq(step.roleId, role.id)).leftJoin(providerUser, eq(toDo.assignedToProviderUserId, providerUser.id));
|
|
3265
|
+
var mapRowToTodo = (row) => ({
|
|
3266
|
+
id: row.id,
|
|
3267
|
+
processExecutionId: row.processExecutionId,
|
|
3268
|
+
flowId: row.flowId,
|
|
3269
|
+
processName: row.processName,
|
|
3270
|
+
processPath: row.processPath,
|
|
3271
|
+
processOrgUnitPath: row.processOrgUnitPath,
|
|
3272
|
+
stepName: row.stepName,
|
|
3273
|
+
stepPath: row.stepPath,
|
|
3274
|
+
rolePath: row.rolePath,
|
|
3275
|
+
assignedToProviderUserId: row.assignedToProviderUserId,
|
|
3276
|
+
assignedToProviderUserEmail: row.assignedToProviderUserEmail,
|
|
3277
|
+
role: row.role,
|
|
3278
|
+
description: row.description,
|
|
3279
|
+
status: row.correctionRequiredAt ? "Correction Required" : row.deleted ? "Completed" : "Active",
|
|
3280
|
+
priority: "Medium",
|
|
3281
|
+
assignedAt: row.createdAt,
|
|
3282
|
+
dueAt: row.slaTargetAt,
|
|
3283
|
+
dueWarningAt: row.slaWarningAt,
|
|
3284
|
+
formComplexity: calculateFormComplexity(row.formFields),
|
|
3285
|
+
updatedAt: row.updatedAt,
|
|
3286
|
+
deleted: row.deleted,
|
|
3287
|
+
summary: []
|
|
3288
|
+
});
|
|
3289
|
+
var SqliteTodoQueriesLive = Layer22.effect(TodoQueries, Effect22.gen(function* () {
|
|
3290
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3291
|
+
return {
|
|
3292
|
+
pullTodo: (checkpoint, limit, mode) => Effect22.gen(function* () {
|
|
3293
|
+
if (mode.kind === "live-backfill" && mode.head === null) {
|
|
3294
|
+
return [];
|
|
3295
|
+
}
|
|
3296
|
+
const conditions = [];
|
|
3297
|
+
const isLiveBackfill = mode.kind === "live-backfill";
|
|
3298
|
+
if (isLiveBackfill) {
|
|
3299
|
+
conditions.push(eq(toDo._deleted, false));
|
|
3300
|
+
}
|
|
3301
|
+
if (mode.kind === "live-backfill" && mode.head) {
|
|
3302
|
+
const headFilter = or(lt(todoUpdatedAtMillis, mode.head.updatedAt), and(eq(todoUpdatedAtMillis, mode.head.updatedAt), lte(toDo.id, mode.head.id)));
|
|
3303
|
+
if (headFilter) {
|
|
3304
|
+
conditions.push(headFilter);
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
if (checkpoint) {
|
|
3308
|
+
const checkpointFilter = or(gt(todoUpdatedAtMillis, checkpoint.updatedAt), and(eq(todoUpdatedAtMillis, checkpoint.updatedAt), gt(toDo.id, checkpoint.id)));
|
|
3309
|
+
if (checkpointFilter) {
|
|
3310
|
+
conditions.push(checkpointFilter);
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
const rows = yield* buildTodoBaseQuery(db).where(conditions.length > 0 ? and(...conditions) : undefined).orderBy(todoUpdatedAtMillis, toDo.id).limit(limit);
|
|
3314
|
+
return rows.map(mapRowToTodo);
|
|
3315
|
+
}),
|
|
3316
|
+
getTodoReplicationHead: () => Effect22.gen(function* () {
|
|
3317
|
+
const rows = yield* db.select({
|
|
3318
|
+
id: toDo.id,
|
|
3319
|
+
updatedAt: todoUpdatedAtMillis
|
|
3320
|
+
}).from(toDo).orderBy(desc(todoUpdatedAtMillis), desc(toDo.id)).limit(1);
|
|
3321
|
+
return rows[0] ?? null;
|
|
3322
|
+
}),
|
|
3323
|
+
getTodos: (ids) => Effect22.gen(function* () {
|
|
3324
|
+
if (ids.length === 0) {
|
|
3325
|
+
return [];
|
|
3326
|
+
}
|
|
3327
|
+
const rows = yield* buildTodoBaseQuery(db).where(inArray(toDo.id, ids)).orderBy(toDo.updatedAt, toDo.id);
|
|
3328
|
+
return rows.map(mapRowToTodo);
|
|
3329
|
+
}),
|
|
3330
|
+
listTodos: (query) => Effect22.gen(function* () {
|
|
3331
|
+
const conditions = [];
|
|
3332
|
+
if (query.processPath != null) {
|
|
3333
|
+
conditions.push(eq(process2.path, query.processPath));
|
|
3334
|
+
}
|
|
3335
|
+
if (query.state) {
|
|
3336
|
+
switch (query.state.kind) {
|
|
3337
|
+
case "correction-required":
|
|
3338
|
+
conditions.push(isNotNull(toDo.correctionRequiredAt));
|
|
3339
|
+
break;
|
|
3340
|
+
case "correction-free":
|
|
3341
|
+
conditions.push(isNull(toDo.correctionRequiredAt), eq(toDo._deleted, query.state.deleted));
|
|
3342
|
+
break;
|
|
3343
|
+
}
|
|
3344
|
+
}
|
|
3345
|
+
const rows = yield* buildTodoBaseQuery(db).where(conditions.length > 0 ? and(...conditions) : undefined).orderBy(desc(toDo.createdAt), toDo.id).limit(query.limit).offset(query.offset);
|
|
3346
|
+
return rows.map(mapRowToTodo);
|
|
3347
|
+
})
|
|
3348
|
+
};
|
|
3349
|
+
}));
|
|
3350
|
+
|
|
3351
|
+
|
|
3352
|
+
var SqliteGraphqlDbOperationsLive = Layer23.mergeAll(SqliteAwsRoleProofStoreLive, SqliteBusinessCalendarQueriesLive, SqliteCleanupOperationsLive, SqliteOrgQueriesLive, SqliteProcessQueriesLive, SqliteProcessCollectionQueriesLive, SqliteProviderUserQueriesLive, SqliteOAuthClientQueriesLive, SqliteProcessExecutionOperationsLive, SqliteDraftProcessExecutionQueriesLive, SqliteExecutionDurationQueriesLive, SqliteExecutionQueriesLive, SqliteExternalParticipantOperationsLive, SqliteFlowQueriesLive, SqliteSettingsQueriesLive, SqliteSystemUserOperationsLive, SqliteTodoQueriesLive, SqliteStepCompletionOperationsLive, SqliteStepRoleQueriesLive, SqliteWorkflowQueriesLive);
|
|
3353
|
+
|
|
3354
|
+
import { strict as assert2 } from "assert";
|
|
3355
|
+
import { DateTime as DateTime6, Effect as Effect23, Layer as Layer24 } from "effect";
|
|
3356
|
+
|
|
3357
|
+
|
|
3358
|
+
import { Context as Context2, Data } from "effect";
|
|
3359
|
+
|
|
3360
|
+
class FlowCrossProcessError extends Data.TaggedError("FlowCrossProcessError") {
|
|
3361
|
+
}
|
|
3362
|
+
|
|
3363
|
+
class DbOperations extends Context2.Service()("processfocus:internal-tag/org-to-db/DbOperations") {
|
|
3364
|
+
}
|
|
3365
|
+
|
|
3366
|
+
|
|
3367
|
+
var SqliteDbOperationsLive = Layer24.succeed(DbOperations, {
|
|
3368
|
+
nextProcessReplicationRevision: Effect23.gen(function* () {
|
|
3369
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3370
|
+
const now = yield* getRequestTime();
|
|
3371
|
+
const rows = yield* db.select({
|
|
3372
|
+
latest: sql`CAST(ROUND((MAX(${process2.updatedAt}) - 2440587.5) * 86400000) AS INTEGER)`
|
|
3373
|
+
}).from(process2);
|
|
3374
|
+
return Math.max(DateTime6.toEpochMillis(now), Number(rows[0]?.latest ?? 0)) + 1;
|
|
3375
|
+
}),
|
|
3376
|
+
setProcessReplicationRevision: (revision) => Effect23.gen(function* () {
|
|
3377
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3378
|
+
const rows = yield* db.update(process2).set({ updatedAt: DateTime6.makeUnsafe(revision) }).returning({ id: process2.id });
|
|
3379
|
+
return rows.map((row) => row.id);
|
|
3380
|
+
}),
|
|
3381
|
+
enqueueProcessChanges: (ids) => Effect23.gen(function* () {
|
|
3382
|
+
if (ids.length === 0)
|
|
3383
|
+
return;
|
|
3384
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3385
|
+
const requestTime = yield* getRequestTime();
|
|
3386
|
+
yield* db.insert(jobQueue).values(ids.map((processId) => ({
|
|
3387
|
+
queue: PROCESS_IMPORT_OUTBOX_QUEUE,
|
|
3388
|
+
jobPayload: { processId },
|
|
3389
|
+
availableAt: requestTime
|
|
3390
|
+
})));
|
|
3391
|
+
}),
|
|
3392
|
+
upsertOrgUnit: (orgUnit2, parentOrgUnitId) => Effect23.gen(function* () {
|
|
3393
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3394
|
+
const requestTime = yield* getRequestTime();
|
|
3395
|
+
const result = yield* db.insert(orgUnit).values({
|
|
3396
|
+
name: orgUnit2.name,
|
|
3397
|
+
orgUnitLevel: orgUnit2.orgUnitLevel,
|
|
3398
|
+
path: orgUnit2.path,
|
|
3399
|
+
parentOrgUnitId: parentOrgUnitId ?? null,
|
|
3400
|
+
acronym: orgUnit2.acronym ?? null,
|
|
3401
|
+
timezone: orgUnit2.timezone,
|
|
3402
|
+
startDayOfWeek: orgUnit2.startDayOfWeek ?? null,
|
|
3403
|
+
createdAt: requestTime,
|
|
3404
|
+
updatedAt: requestTime
|
|
3405
|
+
}).onConflictDoUpdate({
|
|
3406
|
+
target: orgUnit.path,
|
|
3407
|
+
targetWhere: sql`_deleted = 0`,
|
|
3408
|
+
set: {
|
|
3409
|
+
name: orgUnit2.name,
|
|
3410
|
+
orgUnitLevel: orgUnit2.orgUnitLevel,
|
|
3411
|
+
parentOrgUnitId: parentOrgUnitId ?? null,
|
|
3412
|
+
acronym: orgUnit2.acronym ?? null,
|
|
3413
|
+
timezone: orgUnit2.timezone,
|
|
3414
|
+
startDayOfWeek: orgUnit2.startDayOfWeek ?? null,
|
|
3415
|
+
updatedAt: requestTime
|
|
3416
|
+
}
|
|
3417
|
+
}).returning({ id: orgUnit.id });
|
|
3418
|
+
return (yield* returnedRow(result)).id;
|
|
3419
|
+
}),
|
|
3420
|
+
upsertProcess: (process, orgUnitId) => Effect23.gen(function* () {
|
|
3421
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3422
|
+
const requestTime = yield* getRequestTime();
|
|
3423
|
+
const slaValue = process.sla?.value ?? null;
|
|
3424
|
+
const slaUnit = process.sla?.unit ?? null;
|
|
3425
|
+
const slaWarning = process.sla?.warningAt ?? null;
|
|
3426
|
+
const result = yield* db.insert(process2).values({
|
|
3427
|
+
orgUnitId,
|
|
3428
|
+
name: process.name,
|
|
3429
|
+
path: process.path,
|
|
3430
|
+
purpose: process.purpose,
|
|
3431
|
+
slaValue,
|
|
3432
|
+
slaUnit,
|
|
3433
|
+
slaWarning,
|
|
3434
|
+
createdAt: requestTime,
|
|
3435
|
+
updatedAt: requestTime
|
|
3436
|
+
}).onConflictDoUpdate({
|
|
3437
|
+
target: process2.path,
|
|
3438
|
+
targetWhere: sql`_deleted = 0`,
|
|
3439
|
+
set: {
|
|
3440
|
+
name: process.name,
|
|
3441
|
+
purpose: process.purpose,
|
|
3442
|
+
orgUnitId,
|
|
3443
|
+
slaValue,
|
|
3444
|
+
slaUnit,
|
|
3445
|
+
slaWarning,
|
|
3446
|
+
updatedAt: requestTime
|
|
3447
|
+
}
|
|
3448
|
+
}).returning({ id: process2.id });
|
|
3449
|
+
return (yield* returnedRow(result)).id;
|
|
3450
|
+
}),
|
|
3451
|
+
upsertRole: (role2, orgUnitId) => Effect23.gen(function* () {
|
|
3452
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3453
|
+
const requestTime = yield* getRequestTime();
|
|
3454
|
+
const result = yield* db.insert(role).values({
|
|
3455
|
+
orgUnitId,
|
|
3456
|
+
name: role2.name,
|
|
3457
|
+
path: role2.path,
|
|
3458
|
+
createdAt: requestTime,
|
|
3459
|
+
updatedAt: requestTime
|
|
3460
|
+
}).onConflictDoUpdate({
|
|
3461
|
+
target: role.path,
|
|
3462
|
+
targetWhere: sql`_deleted = 0`,
|
|
3463
|
+
set: {
|
|
3464
|
+
name: role2.name,
|
|
3465
|
+
orgUnitId,
|
|
3466
|
+
_deleted: false,
|
|
3467
|
+
updatedAt: requestTime
|
|
3468
|
+
}
|
|
3469
|
+
}).returning({ id: role.id });
|
|
3470
|
+
return (yield* returnedRow(result)).id;
|
|
3471
|
+
}),
|
|
3472
|
+
upsertPhase: (phase2, processId) => Effect23.gen(function* () {
|
|
3473
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3474
|
+
const requestTime = yield* getRequestTime();
|
|
3475
|
+
const result = yield* db.insert(phase).values({
|
|
3476
|
+
processId,
|
|
3477
|
+
name: phase2.name,
|
|
3478
|
+
path: phase2.path,
|
|
3479
|
+
phaseOrder: phase2.order,
|
|
3480
|
+
createdAt: requestTime,
|
|
3481
|
+
updatedAt: requestTime
|
|
3482
|
+
}).onConflictDoUpdate({
|
|
3483
|
+
target: phase.path,
|
|
3484
|
+
targetWhere: sql`_deleted = 0`,
|
|
3485
|
+
set: {
|
|
3486
|
+
name: phase2.name,
|
|
3487
|
+
processId,
|
|
3488
|
+
phaseOrder: phase2.order,
|
|
3489
|
+
_deleted: false,
|
|
3490
|
+
updatedAt: requestTime
|
|
3491
|
+
}
|
|
3492
|
+
}).returning({ id: phase.id });
|
|
3493
|
+
return (yield* returnedRow(result)).id;
|
|
3494
|
+
}),
|
|
3495
|
+
upsertStep: (step2, processId, phaseId) => Effect23.gen(function* () {
|
|
3496
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3497
|
+
const requestTime = yield* getRequestTime();
|
|
3498
|
+
let roleId = null;
|
|
3499
|
+
if (step2.rolePath) {
|
|
3500
|
+
const roleResult = yield* db.select({ id: role.id }).from(role).where(eq(role.path, step2.rolePath)).limit(1);
|
|
3501
|
+
assert2(roleResult[0], `Role not found for path: ${step2.rolePath}`);
|
|
3502
|
+
roleId = roleResult[0].id;
|
|
3503
|
+
}
|
|
3504
|
+
const formFields = step2.formFields ?? null;
|
|
3505
|
+
const slaValue = step2.sla?.value ?? null;
|
|
3506
|
+
const slaUnit = step2.sla?.unit ?? null;
|
|
3507
|
+
const slaWarning = step2.sla?.warningAt ?? null;
|
|
3508
|
+
const hasForEach = step2.hasForEach ?? false;
|
|
3509
|
+
const embedded = step2.embedded ?? false;
|
|
3510
|
+
const retryLimit = step2.retryLimit ?? null;
|
|
3511
|
+
const result = yield* db.insert(step).values({
|
|
3512
|
+
name: step2.name,
|
|
3513
|
+
purpose: step2.purpose,
|
|
3514
|
+
processId,
|
|
3515
|
+
roleId,
|
|
3516
|
+
formFields,
|
|
3517
|
+
phaseId: phaseId ?? null,
|
|
3518
|
+
path: step2.path,
|
|
3519
|
+
slaValue,
|
|
3520
|
+
slaUnit,
|
|
3521
|
+
slaWarning,
|
|
3522
|
+
hasForEach,
|
|
3523
|
+
embedded,
|
|
3524
|
+
retryLimit,
|
|
3525
|
+
createdAt: requestTime,
|
|
3526
|
+
updatedAt: requestTime
|
|
3527
|
+
}).onConflictDoUpdate({
|
|
3528
|
+
target: step.path,
|
|
3529
|
+
targetWhere: sql`_deleted = 0`,
|
|
3530
|
+
set: {
|
|
3531
|
+
name: step2.name,
|
|
3532
|
+
purpose: step2.purpose,
|
|
3533
|
+
processId,
|
|
3534
|
+
roleId,
|
|
3535
|
+
formFields,
|
|
3536
|
+
phaseId: phaseId ?? null,
|
|
3537
|
+
slaValue,
|
|
3538
|
+
slaUnit,
|
|
3539
|
+
slaWarning,
|
|
3540
|
+
hasForEach,
|
|
3541
|
+
embedded,
|
|
3542
|
+
retryLimit,
|
|
3543
|
+
_deleted: false,
|
|
3544
|
+
updatedAt: requestTime
|
|
3545
|
+
}
|
|
3546
|
+
}).returning({ id: step.id });
|
|
3547
|
+
const stepId = (yield* returnedRow(result)).id;
|
|
3548
|
+
if (step2.supportingRolePaths !== undefined) {
|
|
3549
|
+
yield* db.update(stepSupportingRole).set({ _deleted: true, updatedAt: requestTime }).where(and(eq(stepSupportingRole.stepId, stepId), eq(stepSupportingRole._deleted, false)));
|
|
3550
|
+
for (const rolePath of step2.supportingRolePaths) {
|
|
3551
|
+
const supportingRoleResult = yield* db.select({ id: role.id }).from(role).where(eq(role.path, rolePath)).limit(1);
|
|
3552
|
+
assert2(supportingRoleResult[0], `Supporting role not found for path: ${rolePath}`);
|
|
3553
|
+
yield* db.insert(stepSupportingRole).values({
|
|
3554
|
+
stepId,
|
|
3555
|
+
roleId: supportingRoleResult[0].id,
|
|
3556
|
+
createdAt: requestTime,
|
|
3557
|
+
updatedAt: requestTime
|
|
3558
|
+
}).onConflictDoUpdate({
|
|
3559
|
+
target: [
|
|
3560
|
+
stepSupportingRole.stepId,
|
|
3561
|
+
stepSupportingRole.roleId
|
|
3562
|
+
],
|
|
3563
|
+
targetWhere: sql`_deleted = 0`,
|
|
3564
|
+
set: {
|
|
3565
|
+
_deleted: false,
|
|
3566
|
+
updatedAt: requestTime
|
|
3567
|
+
}
|
|
3568
|
+
});
|
|
3569
|
+
}
|
|
3570
|
+
}
|
|
3571
|
+
return stepId;
|
|
3572
|
+
}),
|
|
3573
|
+
upsertRoleResponsibility: (responsibility, processId, roleId) => Effect23.gen(function* () {
|
|
3574
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3575
|
+
const requestTime = yield* getRequestTime();
|
|
3576
|
+
yield* db.insert(roleResponsibility).values({
|
|
3577
|
+
processId,
|
|
3578
|
+
roleId,
|
|
3579
|
+
responsibility: responsibility.responsibility,
|
|
3580
|
+
responsibilityOrder: responsibility.order,
|
|
3581
|
+
createdAt: requestTime,
|
|
3582
|
+
updatedAt: requestTime
|
|
3583
|
+
}).onConflictDoUpdate({
|
|
3584
|
+
target: [
|
|
3585
|
+
roleResponsibility.processId,
|
|
3586
|
+
roleResponsibility.roleId
|
|
3587
|
+
],
|
|
3588
|
+
targetWhere: sql`_deleted = 0`,
|
|
3589
|
+
set: {
|
|
3590
|
+
responsibility: responsibility.responsibility,
|
|
3591
|
+
responsibilityOrder: responsibility.order,
|
|
3592
|
+
_deleted: false,
|
|
3593
|
+
updatedAt: requestTime
|
|
3594
|
+
}
|
|
3595
|
+
});
|
|
3596
|
+
}),
|
|
3597
|
+
upsertFlow: (flowKey, flow2, sourceStepId, targetStepId) => Effect23.gen(function* () {
|
|
3598
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3599
|
+
const requestTime = yield* getRequestTime();
|
|
3600
|
+
const normalizedTaggedErrors = flow2.taggedErrors ? [...flow2.taggedErrors].sort() : null;
|
|
3601
|
+
const steps = yield* db.select({ id: step.id, processId: step.processId }).from(step).where(inArray(step.id, [sourceStepId, targetStepId]));
|
|
3602
|
+
const sourceStep = steps.find((s) => s.id === sourceStepId);
|
|
3603
|
+
const targetStep = steps.find((s) => s.id === targetStepId);
|
|
3604
|
+
assert2(sourceStep, `Source step not found: ${sourceStepId}`);
|
|
3605
|
+
assert2(targetStep, `Target step not found: ${targetStepId}`);
|
|
3606
|
+
if (sourceStep.processId !== targetStep.processId) {
|
|
3607
|
+
return yield* new FlowCrossProcessError({
|
|
3608
|
+
sourceStepId,
|
|
3609
|
+
targetStepId,
|
|
3610
|
+
sourceProcessId: sourceStep.processId,
|
|
3611
|
+
targetProcessId: targetStep.processId
|
|
3612
|
+
});
|
|
3613
|
+
}
|
|
3614
|
+
const existingFlow = yield* db.select({ id: flow.id }).from(flow).where(and(eq(flow.flowKey, flowKey), eq(flow._deleted, false))).limit(1);
|
|
3615
|
+
const flowToUpdate = existingFlow[0] ?? (yield* db.select({ id: flow.id }).from(flow).where(and(eq(flow.sourceStepId, sourceStepId), eq(flow.targetStepId, targetStepId), flow2.condition === undefined ? isNull(flow.condition) : eq(flow.condition, flow2.condition), flow2.schedule === undefined ? isNull(flow.schedule) : eq(flow.schedule, flow2.schedule), eq(flow.fallbackBranch, flow2.isElse), eq(flow.errorBranch, flow2.isOnError ?? false), normalizedTaggedErrors === null ? isNull(flow.errorTags) : eq(flow.errorTags, normalizedTaggedErrors), eq(flow._deleted, false), like(flow.flowKey, "legacy:%"))).limit(1))[0];
|
|
3616
|
+
if (flowToUpdate) {
|
|
3617
|
+
yield* db.update(flow).set({
|
|
3618
|
+
flowKey,
|
|
3619
|
+
sourceStepId,
|
|
3620
|
+
targetStepId,
|
|
3621
|
+
condition: flow2.condition ?? null,
|
|
3622
|
+
schedule: flow2.schedule ?? null,
|
|
3623
|
+
fallbackBranch: flow2.isElse,
|
|
3624
|
+
errorBranch: flow2.isOnError ?? false,
|
|
3625
|
+
deadlineName: flow2.deadlineName ?? null,
|
|
3626
|
+
interrupting: flow2.interrupting ?? false,
|
|
3627
|
+
errorTags: normalizedTaggedErrors,
|
|
3628
|
+
_deleted: false,
|
|
3629
|
+
updatedAt: requestTime
|
|
3630
|
+
}).where(eq(flow.id, flowToUpdate.id));
|
|
3631
|
+
return;
|
|
3632
|
+
}
|
|
3633
|
+
yield* db.insert(flow).values({
|
|
3634
|
+
flowKey,
|
|
3635
|
+
sourceStepId,
|
|
3636
|
+
targetStepId,
|
|
3637
|
+
condition: flow2.condition ?? null,
|
|
3638
|
+
schedule: flow2.schedule ?? null,
|
|
3639
|
+
fallbackBranch: flow2.isElse,
|
|
3640
|
+
errorBranch: flow2.isOnError ?? false,
|
|
3641
|
+
deadlineName: flow2.deadlineName ?? null,
|
|
3642
|
+
interrupting: flow2.interrupting ?? false,
|
|
3643
|
+
errorTags: normalizedTaggedErrors,
|
|
3644
|
+
createdAt: requestTime,
|
|
3645
|
+
updatedAt: requestTime
|
|
3646
|
+
});
|
|
3647
|
+
}),
|
|
3648
|
+
deleteOrphanedFlows: (currentFlowPaths) => Effect23.gen(function* () {
|
|
3649
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3650
|
+
const requestTime = yield* getRequestTime();
|
|
3651
|
+
if (currentFlowPaths.length === 0) {
|
|
3652
|
+
yield* db.update(flow).set({ _deleted: true, updatedAt: requestTime });
|
|
3653
|
+
return;
|
|
3654
|
+
}
|
|
3655
|
+
const existingFlows = yield* db.select({
|
|
3656
|
+
id: flow.id,
|
|
3657
|
+
flowKey: flow.flowKey
|
|
3658
|
+
}).from(flow);
|
|
3659
|
+
const flowIdsToDelete = existingFlows.filter((flow2) => !currentFlowPaths.includes(flow2.flowKey)).map((flow2) => flow2.id);
|
|
3660
|
+
if (flowIdsToDelete.length > 0) {
|
|
3661
|
+
yield* db.update(flow).set({ _deleted: true, updatedAt: requestTime }).where(inArray(flow.id, flowIdsToDelete));
|
|
3662
|
+
}
|
|
3663
|
+
}),
|
|
3664
|
+
deleteOrphanedSteps: (currentStepPaths) => Effect23.gen(function* () {
|
|
3665
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3666
|
+
const requestTime = yield* getRequestTime();
|
|
3667
|
+
if (currentStepPaths.length === 0) {
|
|
3668
|
+
yield* db.update(step).set({ _deleted: true, updatedAt: requestTime });
|
|
3669
|
+
} else {
|
|
3670
|
+
yield* db.update(step).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(step.path, currentStepPaths));
|
|
3671
|
+
}
|
|
3672
|
+
}),
|
|
3673
|
+
deleteOrphanedRoles: (currentRolePaths) => Effect23.gen(function* () {
|
|
3674
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3675
|
+
const requestTime = yield* getRequestTime();
|
|
3676
|
+
if (currentRolePaths.length === 0) {
|
|
3677
|
+
yield* db.update(role).set({ _deleted: true, updatedAt: requestTime });
|
|
3678
|
+
} else {
|
|
3679
|
+
yield* db.update(role).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(role.path, currentRolePaths));
|
|
3680
|
+
}
|
|
3681
|
+
}),
|
|
3682
|
+
deleteOrphanedProcesses: (currentProcessPaths) => Effect23.gen(function* () {
|
|
3683
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3684
|
+
const requestTime = yield* getRequestTime();
|
|
3685
|
+
if (currentProcessPaths.length === 0) {
|
|
3686
|
+
yield* db.update(process2).set({ _deleted: true, updatedAt: requestTime });
|
|
3687
|
+
} else {
|
|
3688
|
+
yield* db.update(process2).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(process2.path, currentProcessPaths));
|
|
3689
|
+
}
|
|
3690
|
+
}),
|
|
3691
|
+
deleteOrphanedOrgUnits: (currentOrgUnitPaths) => Effect23.gen(function* () {
|
|
3692
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3693
|
+
const requestTime = yield* getRequestTime();
|
|
3694
|
+
if (currentOrgUnitPaths.length === 0) {
|
|
3695
|
+
yield* db.update(orgUnit).set({ _deleted: true, updatedAt: requestTime });
|
|
3696
|
+
} else {
|
|
3697
|
+
yield* db.update(orgUnit).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(orgUnit.path, currentOrgUnitPaths));
|
|
3698
|
+
}
|
|
3699
|
+
}),
|
|
3700
|
+
deleteOrphanedPhases: (currentPhasePaths) => Effect23.gen(function* () {
|
|
3701
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3702
|
+
const requestTime = yield* getRequestTime();
|
|
3703
|
+
if (currentPhasePaths.length === 0) {
|
|
3704
|
+
yield* db.update(phase).set({ _deleted: true, updatedAt: requestTime });
|
|
3705
|
+
} else {
|
|
3706
|
+
yield* db.update(phase).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(phase.path, currentPhasePaths));
|
|
3707
|
+
}
|
|
3708
|
+
}),
|
|
3709
|
+
deleteOrphanedRoleResponsibilities: (currentKeys) => Effect23.gen(function* () {
|
|
3710
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3711
|
+
const requestTime = yield* getRequestTime();
|
|
3712
|
+
if (currentKeys.length === 0) {
|
|
3713
|
+
yield* db.update(roleResponsibility).set({ _deleted: true, updatedAt: requestTime });
|
|
3714
|
+
return;
|
|
3715
|
+
}
|
|
3716
|
+
const processPathToIdMap = new Map;
|
|
3717
|
+
const processes = yield* db.select({ id: process2.id, path: process2.path }).from(process2).where(eq(process2._deleted, false));
|
|
3718
|
+
for (const p of processes) {
|
|
3719
|
+
processPathToIdMap.set(p.path, p.id);
|
|
3720
|
+
}
|
|
3721
|
+
const rolePathToIdMap = new Map;
|
|
3722
|
+
const roles = yield* db.select({ id: role.id, path: role.path }).from(role).where(eq(role._deleted, false));
|
|
3723
|
+
for (const r of roles) {
|
|
3724
|
+
rolePathToIdMap.set(r.path, r.id);
|
|
3725
|
+
}
|
|
3726
|
+
const currentPairIds = currentKeys.map(({ processPath, rolePath }) => {
|
|
3727
|
+
const processId = processPathToIdMap.get(processPath);
|
|
3728
|
+
const roleId = rolePathToIdMap.get(rolePath);
|
|
3729
|
+
return processId && roleId ? { processId, roleId } : null;
|
|
3730
|
+
}).filter((pair) => pair !== null);
|
|
3731
|
+
const existingResponsibilities = yield* db.select({
|
|
3732
|
+
id: roleResponsibility.id,
|
|
3733
|
+
processId: roleResponsibility.processId,
|
|
3734
|
+
roleId: roleResponsibility.roleId
|
|
3735
|
+
}).from(roleResponsibility);
|
|
3736
|
+
const respIdsToDelete = existingResponsibilities.filter((resp) => !currentPairIds.some((pair) => pair.processId === resp.processId && pair.roleId === resp.roleId)).map((resp) => resp.id);
|
|
3737
|
+
if (respIdsToDelete.length > 0) {
|
|
3738
|
+
yield* db.update(roleResponsibility).set({ _deleted: true, updatedAt: requestTime }).where(inArray(roleResponsibility.id, respIdsToDelete));
|
|
3739
|
+
}
|
|
3740
|
+
}),
|
|
3741
|
+
upsertOAuthProvider: (providerName, config) => Effect23.gen(function* () {
|
|
3742
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3743
|
+
const requestTime = yield* getRequestTime();
|
|
3744
|
+
yield* db.insert(oauthProvider).values({
|
|
3745
|
+
providerName,
|
|
3746
|
+
providerConfig: config,
|
|
3747
|
+
createdAt: requestTime,
|
|
3748
|
+
updatedAt: requestTime
|
|
3749
|
+
}).onConflictDoUpdate({
|
|
3750
|
+
target: oauthProvider.providerName,
|
|
3751
|
+
targetWhere: sql`_deleted = 0`,
|
|
3752
|
+
set: {
|
|
3753
|
+
providerConfig: config,
|
|
3754
|
+
updatedAt: requestTime
|
|
3755
|
+
}
|
|
3756
|
+
});
|
|
3757
|
+
}),
|
|
3758
|
+
deleteOrphanedOAuthProviders: (currentProviderNames) => Effect23.gen(function* () {
|
|
3759
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3760
|
+
const requestTime = yield* getRequestTime();
|
|
3761
|
+
if (currentProviderNames.length === 0) {
|
|
3762
|
+
yield* db.update(oauthProvider).set({ _deleted: true, updatedAt: requestTime });
|
|
3763
|
+
} else {
|
|
3764
|
+
yield* db.update(oauthProvider).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(oauthProvider.providerName, currentProviderNames));
|
|
3765
|
+
}
|
|
3766
|
+
}),
|
|
3767
|
+
upsertInvitation: (invitation2, roleIds) => Effect23.gen(function* () {
|
|
3768
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3769
|
+
const requestTime = yield* getRequestTime();
|
|
3770
|
+
const normalizedEmail = invitation2.email.toLowerCase();
|
|
3771
|
+
const existingByConstructId = yield* db.select({
|
|
3772
|
+
id: invitation.id,
|
|
3773
|
+
email: invitation.email,
|
|
3774
|
+
invitationStatus: invitation.invitationStatus
|
|
3775
|
+
}).from(invitation).where(and(eq(invitation.invitationId, invitation2.id), eq(invitation._deleted, false))).limit(1);
|
|
3776
|
+
const existingInvitation = existingByConstructId[0];
|
|
3777
|
+
if (existingInvitation && existingInvitation.invitationStatus !== "pending") {
|
|
3778
|
+
return existingInvitation.id;
|
|
3779
|
+
}
|
|
3780
|
+
const clearRegistrationLinkOnHydrate = {
|
|
3781
|
+
registrationTokenHash: null,
|
|
3782
|
+
registrationEncryptionVersion: null,
|
|
3783
|
+
registrationEncryptionNonce: null,
|
|
3784
|
+
registrationAuthenticationTag: null,
|
|
3785
|
+
registrationEncryptedToken: null,
|
|
3786
|
+
registrationLinkExpiresAt: null,
|
|
3787
|
+
registrationLinkGeneration: sql`coalesce(${invitation.registrationLinkGeneration}, 0) + 1`,
|
|
3788
|
+
registrationLinkRevokedAt: requestTime,
|
|
3789
|
+
registrationLinkRevokedBy: "SYSTEM"
|
|
3790
|
+
};
|
|
3791
|
+
yield* db.update(invitation).set({
|
|
3792
|
+
_deleted: true,
|
|
3793
|
+
invitationPendingEmail: null,
|
|
3794
|
+
...clearRegistrationLinkOnHydrate,
|
|
3795
|
+
updatedAt: requestTime
|
|
3796
|
+
}).where(and(eq(invitation.invitationPendingEmail, normalizedEmail), ne(invitation.invitationId, invitation2.id), eq(invitation.invitationStatus, "pending"), eq(invitation._deleted, false)));
|
|
3797
|
+
yield* db.insert(invitation).values({
|
|
3798
|
+
invitationId: invitation2.id,
|
|
3799
|
+
email: normalizedEmail,
|
|
3800
|
+
invitationStatus: "pending",
|
|
3801
|
+
invitationSource: "model",
|
|
3802
|
+
invitationPendingEmail: normalizedEmail,
|
|
3803
|
+
createdAt: requestTime,
|
|
3804
|
+
updatedAt: requestTime
|
|
3805
|
+
}).onConflictDoUpdate({
|
|
3806
|
+
target: invitation.invitationId,
|
|
3807
|
+
targetWhere: sql`_deleted = 0`,
|
|
3808
|
+
set: {
|
|
3809
|
+
email: normalizedEmail,
|
|
3810
|
+
invitationSource: "model",
|
|
3811
|
+
invitationPendingEmail: normalizedEmail,
|
|
3812
|
+
_deleted: false,
|
|
3813
|
+
updatedAt: requestTime
|
|
3814
|
+
},
|
|
3815
|
+
setWhere: eq(invitation.invitationStatus, "pending")
|
|
3816
|
+
});
|
|
3817
|
+
const afterUpsert = yield* db.select({
|
|
3818
|
+
id: invitation.id,
|
|
3819
|
+
email: invitation.email,
|
|
3820
|
+
invitationStatus: invitation.invitationStatus
|
|
3821
|
+
}).from(invitation).where(and(eq(invitation.invitationId, invitation2.id), eq(invitation._deleted, false))).limit(1);
|
|
3822
|
+
const invitationRow = afterUpsert[0];
|
|
3823
|
+
assert2(invitationRow, `Invitation upsert did not produce a row for ${invitation2.id}`);
|
|
3824
|
+
if (invitationRow.invitationStatus !== "pending") {
|
|
3825
|
+
return invitationRow.id;
|
|
3826
|
+
}
|
|
3827
|
+
const invitationPk = invitationRow.id;
|
|
3828
|
+
const emailChanged = existingInvitation !== undefined && existingInvitation.email !== normalizedEmail;
|
|
3829
|
+
const claimedPending = yield* db.update(invitation).set({ updatedAt: requestTime }).where(and(eq(invitation.id, invitationPk), eq(invitation.invitationStatus, "pending"), eq(invitation._deleted, false))).returning({ id: invitation.id });
|
|
3830
|
+
if (claimedPending.length === 0) {
|
|
3831
|
+
return invitationPk;
|
|
3832
|
+
}
|
|
3833
|
+
const existingInvitationRoles = yield* db.select({
|
|
3834
|
+
id: invitationRole.id,
|
|
3835
|
+
roleId: invitationRole.roleId,
|
|
3836
|
+
deleted: invitationRole._deleted
|
|
3837
|
+
}).from(invitationRole).where(eq(invitationRole.invitationId, invitationPk));
|
|
3838
|
+
const existingRoleIds = new Set(existingInvitationRoles.map((ir) => ir.roleId));
|
|
3839
|
+
const existingActiveRoleIds = new Set(existingInvitationRoles.filter((ir) => !ir.deleted).map((ir) => ir.roleId));
|
|
3840
|
+
const desiredRoleIds = new Set(roleIds);
|
|
3841
|
+
const roleIdsToAdd = roleIds.filter((id) => !existingRoleIds.has(id));
|
|
3842
|
+
const invitationRoleIdsToRemove = existingInvitationRoles.filter((ir) => !ir.deleted && !desiredRoleIds.has(ir.roleId)).map((ir) => ir.id);
|
|
3843
|
+
const rolesChanged = roleIds.some((id) => !existingActiveRoleIds.has(id)) || [...existingActiveRoleIds].some((id) => !desiredRoleIds.has(id));
|
|
3844
|
+
if (emailChanged || rolesChanged) {
|
|
3845
|
+
yield* db.update(invitation).set({
|
|
3846
|
+
...clearRegistrationLinkOnHydrate,
|
|
3847
|
+
updatedAt: requestTime
|
|
3848
|
+
}).where(and(eq(invitation.id, invitationPk), eq(invitation.invitationStatus, "pending"), eq(invitation._deleted, false), isNotNull(invitation.registrationTokenHash)));
|
|
3849
|
+
}
|
|
3850
|
+
if (roleIdsToAdd.length > 0) {
|
|
3851
|
+
yield* db.insert(invitationRole).values(roleIdsToAdd.map((roleId) => ({
|
|
3852
|
+
invitationId: invitationPk,
|
|
3853
|
+
roleId,
|
|
3854
|
+
createdAt: requestTime,
|
|
3855
|
+
updatedAt: requestTime
|
|
3856
|
+
})));
|
|
3857
|
+
}
|
|
3858
|
+
if (invitationRoleIdsToRemove.length > 0) {
|
|
3859
|
+
yield* db.update(invitationRole).set({ _deleted: true, updatedAt: requestTime }).where(inArray(invitationRole.id, invitationRoleIdsToRemove));
|
|
3860
|
+
}
|
|
3861
|
+
const roleIdsToReactivate = roleIds.filter((id) => existingRoleIds.has(id));
|
|
3862
|
+
if (roleIdsToReactivate.length > 0) {
|
|
3863
|
+
const invitationRoleIdsToReactivate = existingInvitationRoles.filter((ir) => roleIdsToReactivate.includes(ir.roleId)).map((ir) => ir.id);
|
|
3864
|
+
if (invitationRoleIdsToReactivate.length > 0) {
|
|
3865
|
+
yield* db.update(invitationRole).set({ _deleted: false, updatedAt: requestTime }).where(inArray(invitationRole.id, invitationRoleIdsToReactivate));
|
|
3866
|
+
}
|
|
3867
|
+
}
|
|
3868
|
+
return invitationPk;
|
|
3869
|
+
}),
|
|
3870
|
+
deleteOrphanedInvitations: (currentInvitationIds) => Effect23.gen(function* () {
|
|
3871
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3872
|
+
const requestTime = yield* getRequestTime();
|
|
3873
|
+
const modelPendingOrphan = currentInvitationIds.length === 0 ? and(eq(invitation.invitationSource, "model"), eq(invitation.invitationStatus, "pending"), eq(invitation._deleted, false)) : and(eq(invitation.invitationSource, "model"), eq(invitation.invitationStatus, "pending"), eq(invitation._deleted, false), notInArray(invitation.invitationId, currentInvitationIds));
|
|
3874
|
+
const orphaned = yield* db.update(invitation).set({
|
|
3875
|
+
_deleted: true,
|
|
3876
|
+
invitationPendingEmail: null,
|
|
3877
|
+
updatedAt: requestTime
|
|
3878
|
+
}).where(modelPendingOrphan).returning({ id: invitation.id });
|
|
3879
|
+
if (orphaned.length > 0) {
|
|
3880
|
+
yield* db.update(invitationRole).set({ _deleted: true, updatedAt: requestTime }).where(and(inArray(invitationRole.invitationId, orphaned.map((row) => row.id)), eq(invitationRole._deleted, false)));
|
|
3881
|
+
}
|
|
3882
|
+
}),
|
|
3883
|
+
upsertOAuthClient: (clientId, secretHash, audience, workloadTrust, awsRoleBindings) => Effect23.gen(function* () {
|
|
3884
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3885
|
+
const requestTime = yield* getRequestTime();
|
|
3886
|
+
const versionedTrust = workloadTrust?.["deploymentProjects"] || workloadTrust?.["databaseTransferProjects"] ? { ...workloadTrust, deploymentGrantGeneration: crypto.randomUUID() } : workloadTrust;
|
|
3887
|
+
yield* db.insert(oauthClient).values({
|
|
3888
|
+
clientId,
|
|
3889
|
+
clientSecretHash: secretHash,
|
|
3890
|
+
workloadTrust: versionedTrust ?? null,
|
|
3891
|
+
awsRoleBindings: awsRoleBindings ?? null,
|
|
3892
|
+
audience,
|
|
3893
|
+
createdAt: requestTime,
|
|
3894
|
+
updatedAt: requestTime
|
|
3895
|
+
}).onConflictDoUpdate({
|
|
3896
|
+
target: oauthClient.clientId,
|
|
3897
|
+
targetWhere: sql`_deleted = 0`,
|
|
3898
|
+
set: {
|
|
3899
|
+
clientSecretHash: secretHash,
|
|
3900
|
+
workloadTrust: versionedTrust !== workloadTrust ? sql`CASE WHEN json_remove(${oauthClient.workloadTrust}, '$.deploymentGrantGeneration') = ${JSON.stringify(workloadTrust)}
|
|
3901
|
+
AND json_extract(${oauthClient.workloadTrust}, '$.deploymentGrantGeneration') IS NOT NULL
|
|
3902
|
+
THEN ${oauthClient.workloadTrust} ELSE excluded.workload_trust END` : workloadTrust ?? null,
|
|
3903
|
+
awsRoleBindings: awsRoleBindings ?? null,
|
|
3904
|
+
audience,
|
|
3905
|
+
_deleted: false,
|
|
3906
|
+
updatedAt: requestTime
|
|
3907
|
+
}
|
|
3908
|
+
});
|
|
3909
|
+
}),
|
|
3910
|
+
deleteOrphanedOAuthClients: (currentClientIds) => Effect23.gen(function* () {
|
|
3911
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3912
|
+
const requestTime = yield* getRequestTime();
|
|
3913
|
+
if (currentClientIds.length === 0) {
|
|
3914
|
+
yield* db.update(oauthClient).set({ _deleted: true, updatedAt: requestTime }).where(sql`json_extract(${oauthClient.workloadTrust}, '$.owner') IS NOT 'project'`);
|
|
3915
|
+
} else {
|
|
3916
|
+
yield* db.update(oauthClient).set({ _deleted: true, updatedAt: requestTime }).where(and(notInArray(oauthClient.clientId, currentClientIds), sql`json_extract(${oauthClient.workloadTrust}, '$.owner') IS NOT 'project'`));
|
|
3917
|
+
}
|
|
3918
|
+
}),
|
|
3919
|
+
upsertWeeklySchedule: (schedule, orgUnitId) => Effect23.gen(function* () {
|
|
3920
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3921
|
+
const requestTime = yield* getRequestTime();
|
|
3922
|
+
yield* db.insert(weeklySchedule).values({
|
|
3923
|
+
orgUnitId,
|
|
3924
|
+
dayOfWeek: schedule.dayOfWeek,
|
|
3925
|
+
timeRanges: schedule.timeRanges,
|
|
3926
|
+
createdAt: requestTime,
|
|
3927
|
+
updatedAt: requestTime
|
|
3928
|
+
}).onConflictDoUpdate({
|
|
3929
|
+
target: [
|
|
3930
|
+
weeklySchedule.orgUnitId,
|
|
3931
|
+
weeklySchedule.dayOfWeek
|
|
3932
|
+
],
|
|
3933
|
+
targetWhere: sql`_deleted = 0`,
|
|
3934
|
+
set: {
|
|
3935
|
+
timeRanges: schedule.timeRanges,
|
|
3936
|
+
_deleted: false,
|
|
3937
|
+
updatedAt: requestTime
|
|
3938
|
+
}
|
|
3939
|
+
});
|
|
3940
|
+
}),
|
|
3941
|
+
deleteOrphanedWeeklySchedules: (currentKeys) => Effect23.gen(function* () {
|
|
3942
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3943
|
+
const requestTime = yield* getRequestTime();
|
|
3944
|
+
if (currentKeys.length === 0) {
|
|
3945
|
+
yield* db.update(weeklySchedule).set({ _deleted: true, updatedAt: requestTime });
|
|
3946
|
+
return;
|
|
3947
|
+
}
|
|
3948
|
+
const orgUnitPathToIdMap = new Map;
|
|
3949
|
+
const orgUnits = yield* db.select({ id: orgUnit.id, path: orgUnit.path }).from(orgUnit).where(eq(orgUnit._deleted, false));
|
|
3950
|
+
for (const ou of orgUnits) {
|
|
3951
|
+
orgUnitPathToIdMap.set(ou.path, ou.id);
|
|
3952
|
+
}
|
|
3953
|
+
const currentPairIds = currentKeys.map(({ orgUnitPath, dayOfWeek }) => {
|
|
3954
|
+
const orgUnitId = orgUnitPathToIdMap.get(orgUnitPath);
|
|
3955
|
+
return orgUnitId ? { orgUnitId, dayOfWeek } : null;
|
|
3956
|
+
}).filter((pair) => pair !== null);
|
|
3957
|
+
const existingSchedules = yield* db.select({
|
|
3958
|
+
id: weeklySchedule.id,
|
|
3959
|
+
orgUnitId: weeklySchedule.orgUnitId,
|
|
3960
|
+
dayOfWeek: weeklySchedule.dayOfWeek
|
|
3961
|
+
}).from(weeklySchedule);
|
|
3962
|
+
const scheduleIdsToDelete = existingSchedules.filter((sched) => !currentPairIds.some((pair) => pair.orgUnitId === sched.orgUnitId && pair.dayOfWeek === sched.dayOfWeek)).map((sched) => sched.id);
|
|
3963
|
+
if (scheduleIdsToDelete.length > 0) {
|
|
3964
|
+
yield* db.update(weeklySchedule).set({ _deleted: true, updatedAt: requestTime }).where(inArray(weeklySchedule.id, scheduleIdsToDelete));
|
|
3965
|
+
}
|
|
3966
|
+
}),
|
|
3967
|
+
upsertHolidayRule: (holiday, orgUnitId) => Effect23.gen(function* () {
|
|
3968
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3969
|
+
const requestTime = yield* getRequestTime();
|
|
3970
|
+
yield* db.insert(holidayInstance).values({
|
|
3971
|
+
orgUnitId,
|
|
3972
|
+
holidayTitle: holiday.name,
|
|
3973
|
+
holidayRule: holiday.rule,
|
|
3974
|
+
createdAt: requestTime,
|
|
3975
|
+
updatedAt: requestTime
|
|
3976
|
+
}).onConflictDoUpdate({
|
|
3977
|
+
target: [
|
|
3978
|
+
holidayInstance.orgUnitId,
|
|
3979
|
+
holidayInstance.holidayTitle
|
|
3980
|
+
],
|
|
3981
|
+
targetWhere: sql`_deleted = 0`,
|
|
3982
|
+
set: {
|
|
3983
|
+
holidayRule: holiday.rule,
|
|
3984
|
+
_deleted: false,
|
|
3985
|
+
updatedAt: requestTime
|
|
3986
|
+
}
|
|
3987
|
+
});
|
|
3988
|
+
}),
|
|
3989
|
+
deleteOrphanedHolidayRules: (currentKeys) => Effect23.gen(function* () {
|
|
3990
|
+
const db = yield* TypedSqliteDrizzle;
|
|
3991
|
+
const requestTime = yield* getRequestTime();
|
|
3992
|
+
if (currentKeys.length === 0) {
|
|
3993
|
+
yield* db.update(holidayInstance).set({ _deleted: true, updatedAt: requestTime });
|
|
3994
|
+
return;
|
|
3995
|
+
}
|
|
3996
|
+
const orgUnitPathToIdMap = new Map;
|
|
3997
|
+
const orgUnits = yield* db.select({ id: orgUnit.id, path: orgUnit.path }).from(orgUnit).where(eq(orgUnit._deleted, false));
|
|
3998
|
+
for (const ou of orgUnits) {
|
|
3999
|
+
orgUnitPathToIdMap.set(ou.path, ou.id);
|
|
4000
|
+
}
|
|
4001
|
+
const currentPairIds = currentKeys.map(({ orgUnitPath, holidayTitle }) => {
|
|
4002
|
+
const orgUnitId = orgUnitPathToIdMap.get(orgUnitPath);
|
|
4003
|
+
return orgUnitId && holidayTitle ? { orgUnitId, holidayTitle } : null;
|
|
4004
|
+
}).filter((pair) => pair !== null);
|
|
4005
|
+
const existingHolidays = yield* db.select({
|
|
4006
|
+
id: holidayInstance.id,
|
|
4007
|
+
orgUnitId: holidayInstance.orgUnitId,
|
|
4008
|
+
holidayTitle: holidayInstance.holidayTitle
|
|
4009
|
+
}).from(holidayInstance);
|
|
4010
|
+
const holidayIdsToDelete = existingHolidays.filter((hol) => !currentPairIds.some((pair) => pair.orgUnitId === hol.orgUnitId && pair.holidayTitle === hol.holidayTitle)).map((hol) => hol.id);
|
|
4011
|
+
if (holidayIdsToDelete.length > 0) {
|
|
4012
|
+
yield* db.update(holidayInstance).set({ _deleted: true, updatedAt: requestTime }).where(inArray(holidayInstance.id, holidayIdsToDelete));
|
|
4013
|
+
}
|
|
4014
|
+
}),
|
|
4015
|
+
upsertDocumentStore: (data, orgUnitId) => Effect23.gen(function* () {
|
|
4016
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4017
|
+
const requestTime = yield* getRequestTime();
|
|
4018
|
+
const result = yield* db.insert(documentStore).values({
|
|
4019
|
+
orgUnitId,
|
|
4020
|
+
name: data.name,
|
|
4021
|
+
path: data.path,
|
|
4022
|
+
acceptedTypes: data.acceptedTypes ?? null,
|
|
4023
|
+
sizeLimit: data.maxFileSize ?? null,
|
|
4024
|
+
createdAt: requestTime,
|
|
4025
|
+
updatedAt: requestTime
|
|
4026
|
+
}).onConflictDoUpdate({
|
|
4027
|
+
target: documentStore.path,
|
|
4028
|
+
targetWhere: sql`_deleted = 0`,
|
|
4029
|
+
set: {
|
|
4030
|
+
name: data.name,
|
|
4031
|
+
orgUnitId,
|
|
4032
|
+
acceptedTypes: data.acceptedTypes ?? null,
|
|
4033
|
+
sizeLimit: data.maxFileSize ?? null,
|
|
4034
|
+
updatedAt: requestTime
|
|
4035
|
+
}
|
|
4036
|
+
}).returning({ id: documentStore.id });
|
|
4037
|
+
return (yield* returnedRow(result)).id;
|
|
4038
|
+
}),
|
|
4039
|
+
deleteOrphanedDocumentStores: (currentPaths) => Effect23.gen(function* () {
|
|
4040
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4041
|
+
const requestTime = yield* getRequestTime();
|
|
4042
|
+
if (currentPaths.length === 0) {
|
|
4043
|
+
yield* db.update(documentStore).set({ _deleted: true, updatedAt: requestTime });
|
|
4044
|
+
} else {
|
|
4045
|
+
yield* db.update(documentStore).set({ _deleted: true, updatedAt: requestTime }).where(notInArray(documentStore.path, currentPaths));
|
|
4046
|
+
}
|
|
4047
|
+
}),
|
|
4048
|
+
upsertStepDocumentStore: (stepId, documentStoreId) => Effect23.gen(function* () {
|
|
4049
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4050
|
+
const requestTime = yield* getRequestTime();
|
|
4051
|
+
yield* db.insert(stepDocumentStore).values({
|
|
4052
|
+
stepId,
|
|
4053
|
+
documentStoreId,
|
|
4054
|
+
createdAt: requestTime,
|
|
4055
|
+
updatedAt: requestTime
|
|
4056
|
+
}).onConflictDoUpdate({
|
|
4057
|
+
target: [
|
|
4058
|
+
stepDocumentStore.stepId,
|
|
4059
|
+
stepDocumentStore.documentStoreId
|
|
4060
|
+
],
|
|
4061
|
+
targetWhere: sql`_deleted = 0`,
|
|
4062
|
+
set: {
|
|
4063
|
+
_deleted: false,
|
|
4064
|
+
updatedAt: requestTime
|
|
4065
|
+
}
|
|
4066
|
+
});
|
|
4067
|
+
}),
|
|
4068
|
+
deleteOrphanedStepDocumentStores: (currentKeys) => Effect23.gen(function* () {
|
|
4069
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4070
|
+
const requestTime = yield* getRequestTime();
|
|
4071
|
+
if (currentKeys.length === 0) {
|
|
4072
|
+
yield* db.update(stepDocumentStore).set({ _deleted: true, updatedAt: requestTime });
|
|
4073
|
+
return;
|
|
4074
|
+
}
|
|
4075
|
+
const stepPathToIdMap = new Map;
|
|
4076
|
+
const steps = yield* db.select({ id: step.id, path: step.path }).from(step).where(eq(step._deleted, false));
|
|
4077
|
+
for (const s of steps) {
|
|
4078
|
+
stepPathToIdMap.set(s.path, s.id);
|
|
4079
|
+
}
|
|
4080
|
+
const storePathToIdMap = new Map;
|
|
4081
|
+
const stores = yield* db.select({
|
|
4082
|
+
id: documentStore.id,
|
|
4083
|
+
path: documentStore.path
|
|
4084
|
+
}).from(documentStore).where(eq(documentStore._deleted, false));
|
|
4085
|
+
for (const s of stores) {
|
|
4086
|
+
storePathToIdMap.set(s.path, s.id);
|
|
4087
|
+
}
|
|
4088
|
+
const currentPairIds = currentKeys.map(({ stepPath, documentStorePath }) => {
|
|
4089
|
+
const stepId = stepPathToIdMap.get(stepPath);
|
|
4090
|
+
const documentStoreId = storePathToIdMap.get(documentStorePath);
|
|
4091
|
+
return stepId && documentStoreId ? { stepId, documentStoreId } : null;
|
|
4092
|
+
}).filter((pair) => pair !== null);
|
|
4093
|
+
const existingEntries = yield* db.select({
|
|
4094
|
+
id: stepDocumentStore.id,
|
|
4095
|
+
stepId: stepDocumentStore.stepId,
|
|
4096
|
+
documentStoreId: stepDocumentStore.documentStoreId
|
|
4097
|
+
}).from(stepDocumentStore);
|
|
4098
|
+
const entryIdsToDelete = existingEntries.filter((entry) => !currentPairIds.some((pair) => pair.stepId === entry.stepId && pair.documentStoreId === entry.documentStoreId)).map((entry) => entry.id);
|
|
4099
|
+
if (entryIdsToDelete.length > 0) {
|
|
4100
|
+
yield* db.update(stepDocumentStore).set({ _deleted: true, updatedAt: requestTime }).where(inArray(stepDocumentStore.id, entryIdsToDelete));
|
|
4101
|
+
}
|
|
4102
|
+
})
|
|
4103
|
+
});
|
|
4104
|
+
|
|
4105
|
+
import { Effect as Effect24, Layer as Layer25, Option as Option3 } from "effect";
|
|
4106
|
+
var SqliteScheduledFlowOperationsLive = Layer25.effect(ScheduledFlowOperations, Effect24.gen(function* () {
|
|
4107
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4108
|
+
const sourceStep = aliasedTable(step, "source_step");
|
|
4109
|
+
const targetStep = aliasedTable(step, "target_step");
|
|
4110
|
+
return {
|
|
4111
|
+
queryPendingTaskDeadlines: (processExecutionId) => db.select({
|
|
4112
|
+
id: taskDeadline.id,
|
|
4113
|
+
scheduledAt: taskDeadline.scheduledAt,
|
|
4114
|
+
withoutWaiting: processExecution.withoutWaiting
|
|
4115
|
+
}).from(taskDeadline).innerJoin(toDo, eq(taskDeadline.ownerToDoId, toDo.id)).innerJoin(processExecution, eq(toDo.processExecutionId, processExecution.id)).innerJoin(scheduledFlow, eq(taskDeadline.id, scheduledFlow.id)).where(and(eq(toDo.processExecutionId, processExecutionId), eq(toDo._deleted, false), isNull(taskDeadline.triggeredAt), isNull(taskDeadline.disarmedAt))),
|
|
4116
|
+
hasTaskDeadlines: (processExecutionId) => Effect24.gen(function* () {
|
|
4117
|
+
const rows = yield* db.select({ id: taskDeadline.id }).from(taskDeadline).innerJoin(toDo, eq(taskDeadline.ownerToDoId, toDo.id)).where(eq(toDo.processExecutionId, processExecutionId)).limit(1);
|
|
4118
|
+
return rows.length > 0;
|
|
4119
|
+
}),
|
|
4120
|
+
insertTaskDeadline: (input) => Effect24.gen(function* () {
|
|
4121
|
+
const now = yield* getRequestTime();
|
|
4122
|
+
const user = yield* getUserDetails();
|
|
4123
|
+
const rows = yield* db.insert(taskDeadline).values({
|
|
4124
|
+
ownerToDoId: input.ownerTodoId,
|
|
4125
|
+
flowId: input.flowId,
|
|
4126
|
+
deadlineName: input.name,
|
|
4127
|
+
scheduledAt: input.dueAt,
|
|
4128
|
+
interrupting: input.interrupting,
|
|
4129
|
+
createdAt: now,
|
|
4130
|
+
updatedAt: now,
|
|
4131
|
+
createdBy: user.by,
|
|
4132
|
+
updatedBy: user.by
|
|
4133
|
+
}).returning({ id: taskDeadline.id });
|
|
4134
|
+
return (yield* returnedRow(rows)).id;
|
|
4135
|
+
}),
|
|
4136
|
+
getTaskDeadline: (id) => Effect24.gen(function* () {
|
|
4137
|
+
const rows = yield* db.select({
|
|
4138
|
+
ownerTodoId: taskDeadline.ownerToDoId,
|
|
4139
|
+
flowId: taskDeadline.flowId,
|
|
4140
|
+
dueAt: taskDeadline.scheduledAt,
|
|
4141
|
+
interrupting: taskDeadline.interrupting,
|
|
4142
|
+
triggeredAt: taskDeadline.triggeredAt,
|
|
4143
|
+
disarmedAt: taskDeadline.disarmedAt
|
|
4144
|
+
}).from(taskDeadline).where(eq(taskDeadline.id, id));
|
|
4145
|
+
return rows[0] ?? null;
|
|
4146
|
+
}),
|
|
4147
|
+
claimTaskDeadline: (id, ownerTodoId) => Effect24.gen(function* () {
|
|
4148
|
+
const owners = yield* db.update(toDo).set({ updatedAt: toDo.updatedAt }).where(and(eq(toDo.id, ownerTodoId), eq(toDo._deleted, false), isNull(toDo.failureReason))).returning({ id: toDo.id });
|
|
4149
|
+
if (owners.length === 0)
|
|
4150
|
+
return false;
|
|
4151
|
+
const now = yield* getRequestTime();
|
|
4152
|
+
const user = yield* getUserDetails();
|
|
4153
|
+
const rows = yield* db.update(taskDeadline).set({ triggeredAt: now, updatedAt: now, updatedBy: user.by }).where(and(eq(taskDeadline.id, id), isNull(taskDeadline.triggeredAt), isNull(taskDeadline.disarmedAt))).returning({ id: taskDeadline.id });
|
|
4154
|
+
return rows.length === 1;
|
|
4155
|
+
}),
|
|
4156
|
+
interruptTask: (ownerTodoId) => Effect24.gen(function* () {
|
|
4157
|
+
const now = yield* getRequestTime();
|
|
4158
|
+
const user = yield* getUserDetails();
|
|
4159
|
+
yield* db.update(toDo).set({
|
|
4160
|
+
_deleted: true,
|
|
4161
|
+
interruptedAt: now,
|
|
4162
|
+
correctionRequiredAt: null,
|
|
4163
|
+
correctionFailureReason: null,
|
|
4164
|
+
correctionInvitationAttemptId: null,
|
|
4165
|
+
updatedAt: now,
|
|
4166
|
+
updatedBy: user.by
|
|
4167
|
+
}).where(eq(toDo.id, ownerTodoId));
|
|
4168
|
+
}),
|
|
4169
|
+
disarmTaskDeadlines: (ownerTodoId) => Effect24.gen(function* () {
|
|
4170
|
+
const now = yield* getRequestTime();
|
|
4171
|
+
const user = yield* getUserDetails();
|
|
4172
|
+
const rows = yield* db.update(taskDeadline).set({ disarmedAt: now, updatedAt: now, updatedBy: user.by }).where(and(eq(taskDeadline.ownerToDoId, ownerTodoId), isNull(taskDeadline.triggeredAt), isNull(taskDeadline.disarmedAt))).returning({ id: taskDeadline.id });
|
|
4173
|
+
for (const row of rows) {
|
|
4174
|
+
yield* db.delete(scheduledFlow).where(eq(scheduledFlow.id, row.id));
|
|
4175
|
+
}
|
|
4176
|
+
}),
|
|
4177
|
+
insertScheduledFlow: (processExecutionId, sourceStepId, options) => Effect24.gen(function* () {
|
|
4178
|
+
const requestTime = yield* getRequestTime();
|
|
4179
|
+
const userDetails = yield* getUserDetails();
|
|
4180
|
+
const result = yield* db.insert(scheduledFlow).values({
|
|
4181
|
+
processExecutionId,
|
|
4182
|
+
sourceStepId,
|
|
4183
|
+
targetStepId: options?.targetStepId,
|
|
4184
|
+
scheduledAt: options?.scheduledAt,
|
|
4185
|
+
forEachBarrier: options?.forEachBarrier ?? false,
|
|
4186
|
+
completedByRoleId: options?.completedByRoleId,
|
|
4187
|
+
createdAt: requestTime,
|
|
4188
|
+
updatedAt: requestTime,
|
|
4189
|
+
createdBy: userDetails.by,
|
|
4190
|
+
updatedBy: userDetails.by
|
|
4191
|
+
}).returning({ id: scheduledFlow.id });
|
|
4192
|
+
return (yield* returnedRow(result)).id;
|
|
4193
|
+
}),
|
|
4194
|
+
insertOrGetScheduledFlow: (id, processExecutionId, sourceStepId, options) => Effect24.gen(function* () {
|
|
4195
|
+
const requestTime = yield* getRequestTime();
|
|
4196
|
+
const userDetails = yield* getUserDetails();
|
|
4197
|
+
const inserted = yield* db.insert(scheduledFlow).values({
|
|
4198
|
+
id,
|
|
4199
|
+
processExecutionId,
|
|
4200
|
+
sourceStepId,
|
|
4201
|
+
targetStepId: options?.targetStepId,
|
|
4202
|
+
scheduledAt: options?.scheduledAt,
|
|
4203
|
+
forEachBarrier: options?.forEachBarrier ?? false,
|
|
4204
|
+
completedByRoleId: options?.completedByRoleId,
|
|
4205
|
+
createdAt: requestTime,
|
|
4206
|
+
updatedAt: requestTime,
|
|
4207
|
+
createdBy: userDetails.by,
|
|
4208
|
+
updatedBy: userDetails.by
|
|
4209
|
+
}).onConflictDoNothing({ target: scheduledFlow.id }).returning({ id: scheduledFlow.id });
|
|
4210
|
+
if (inserted[0])
|
|
4211
|
+
return inserted[0].id;
|
|
4212
|
+
const existing = yield* db.select({ id: scheduledFlow.id }).from(scheduledFlow).where(eq(scheduledFlow.id, id)).limit(1);
|
|
4213
|
+
return (yield* returnedRow(existing)).id;
|
|
4214
|
+
}),
|
|
4215
|
+
getScheduledFlow: (id) => Effect24.gen(function* () {
|
|
4216
|
+
const result = yield* db.select({
|
|
4217
|
+
processExecutionId: scheduledFlow.processExecutionId,
|
|
4218
|
+
createdBy: scheduledFlow.createdBy,
|
|
4219
|
+
sourceStepId: scheduledFlow.sourceStepId,
|
|
4220
|
+
targetStepId: scheduledFlow.targetStepId,
|
|
4221
|
+
scheduledAt: scheduledFlow.scheduledAt,
|
|
4222
|
+
forEachBarrier: scheduledFlow.forEachBarrier,
|
|
4223
|
+
completedByRoleId: scheduledFlow.completedByRoleId
|
|
4224
|
+
}).from(scheduledFlow).where(eq(scheduledFlow.id, id)).limit(1);
|
|
4225
|
+
if (!result[0]) {
|
|
4226
|
+
return Option3.none();
|
|
4227
|
+
}
|
|
4228
|
+
return Option3.some({
|
|
4229
|
+
processExecutionId: result[0].processExecutionId,
|
|
4230
|
+
createdBy: result[0].createdBy,
|
|
4231
|
+
sourceStepId: result[0].sourceStepId,
|
|
4232
|
+
targetStepId: result[0].targetStepId,
|
|
4233
|
+
scheduledAt: result[0].scheduledAt,
|
|
4234
|
+
forEachBarrier: result[0].forEachBarrier,
|
|
4235
|
+
completedByRoleId: result[0].completedByRoleId
|
|
4236
|
+
});
|
|
4237
|
+
}),
|
|
4238
|
+
deleteScheduledFlow: (id) => Effect24.gen(function* () {
|
|
4239
|
+
const result = yield* db.delete(scheduledFlow).where(eq(scheduledFlow.id, id)).returning({ id: scheduledFlow.id });
|
|
4240
|
+
return result.length > 0;
|
|
4241
|
+
}),
|
|
4242
|
+
hasPendingScheduledFlows: (processExecutionId) => Effect24.gen(function* () {
|
|
4243
|
+
const pendingFlows = yield* db.select({ id: scheduledFlow.id }).from(scheduledFlow).where(eq(scheduledFlow.processExecutionId, processExecutionId)).limit(1);
|
|
4244
|
+
if (pendingFlows.length > 0)
|
|
4245
|
+
return true;
|
|
4246
|
+
const activeSystemTodos = yield* db.select({ id: toDo.id }).from(toDo).innerJoin(flow, eq(toDo.flowId, flow.id)).innerJoin(step, eq(flow.targetStepId, step.id)).where(and(eq(toDo.processExecutionId, processExecutionId), isNull(toDo.businessDuration), isNull(toDo.failureReason), eq(toDo._deleted, false), isNull(step.roleId))).limit(1);
|
|
4247
|
+
return activeSystemTodos.length > 0;
|
|
4248
|
+
}),
|
|
4249
|
+
getPendingStartScheduledFlowId: (processExecutionId, sourceStepId) => Effect24.gen(function* () {
|
|
4250
|
+
const result = yield* db.select({ id: scheduledFlow.id }).from(scheduledFlow).where(and(eq(scheduledFlow.processExecutionId, processExecutionId), eq(scheduledFlow.sourceStepId, sourceStepId), isNull(scheduledFlow.targetStepId), isNull(scheduledFlow.scheduledAt), eq(scheduledFlow.forEachBarrier, false))).limit(1);
|
|
4251
|
+
return result[0]?.id ?? null;
|
|
4252
|
+
}),
|
|
4253
|
+
queryPendingAbandonStepPaths: (processExecutionId) => Effect24.gen(function* () {
|
|
4254
|
+
const rows = yield* db.select({
|
|
4255
|
+
sourceStepPath: sourceStep.path,
|
|
4256
|
+
targetStepPath: targetStep.path
|
|
4257
|
+
}).from(scheduledFlow).innerJoin(sourceStep, and(eq(scheduledFlow.sourceStepId, sourceStep.id), eq(sourceStep._deleted, false))).leftJoin(targetStep, and(eq(scheduledFlow.targetStepId, targetStep.id), eq(targetStep._deleted, false))).where(and(eq(scheduledFlow.processExecutionId, processExecutionId), eq(scheduledFlow._deleted, false)));
|
|
4258
|
+
return [
|
|
4259
|
+
...new Set(rows.map((row) => row.targetStepPath ?? row.sourceStepPath))
|
|
4260
|
+
];
|
|
4261
|
+
}),
|
|
4262
|
+
deleteScheduledFlowsForExecution: (processExecutionId) => Effect24.gen(function* () {
|
|
4263
|
+
yield* db.delete(scheduledFlow).where(eq(scheduledFlow.processExecutionId, processExecutionId));
|
|
4264
|
+
}),
|
|
4265
|
+
wasBarrierScheduledFlow: (scheduledFlowId) => Effect24.gen(function* () {
|
|
4266
|
+
const result = yield* db.select({ id: toDo.id }).from(toDo).where(eq(toDo.barrierScheduledFlowId, scheduledFlowId)).limit(1);
|
|
4267
|
+
return result.length > 0;
|
|
4268
|
+
})
|
|
4269
|
+
};
|
|
4270
|
+
}));
|
|
4271
|
+
|
|
4272
|
+
import { Context as Context3, DateTime as DateTime7, Duration, Effect as Effect25, Layer as Layer26, Option as Option4 } from "effect";
|
|
4273
|
+
import { SqlClient } from "effect/sql";
|
|
4274
|
+
var LoggedSqliteQueueFailures = Context3.Reference("processfocus:internal-tag/sqlite-queue-service/LoggedSqliteQueueFailures", {
|
|
4275
|
+
defaultValue: () => {
|
|
4276
|
+
return;
|
|
4277
|
+
}
|
|
4278
|
+
});
|
|
4279
|
+
var logQueueFailure = (operation, summary, error) => Effect25.gen(function* () {
|
|
4280
|
+
const httpStatus = getTursoHttpStatus(error.cause);
|
|
4281
|
+
yield* Effect25.logError("SQLite queue operation failed", {
|
|
4282
|
+
operation,
|
|
4283
|
+
..."queue" in error ? { queue: error.queue } : { jobId: error.jobId },
|
|
4284
|
+
httpStatus,
|
|
4285
|
+
error: summary.slice(0, 512)
|
|
4286
|
+
});
|
|
4287
|
+
const logged = yield* LoggedSqliteQueueFailures;
|
|
4288
|
+
logged?.add(error);
|
|
4289
|
+
return yield* Effect25.fail(error);
|
|
4290
|
+
});
|
|
4291
|
+
var mapClaimVerificationError = (jobId) => Effect25.mapError((error) => new AcknowledgeError({
|
|
4292
|
+
jobId,
|
|
4293
|
+
message: `Failed to verify job claim: ${formatSqlError(error)}`,
|
|
4294
|
+
cause: error
|
|
4295
|
+
}));
|
|
4296
|
+
var MILLISECONDS_PER_DAY = 86400000;
|
|
4297
|
+
var UNIX_EPOCH_JULIAN_DAY = 2440587.5;
|
|
4298
|
+
var ACKNOWLEDGE_BATCH_SIZE = 499;
|
|
4299
|
+
var retryWithClaimTime = (query) => Effect25.gen(function* () {
|
|
4300
|
+
const client = yield* SqlClient.SqlClient;
|
|
4301
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4302
|
+
const transaction = yield* Effect25.serviceOption(client.transactionService);
|
|
4303
|
+
const mutate = Effect25.gen(function* () {
|
|
4304
|
+
yield* db.update(jobQueue).set({
|
|
4305
|
+
claimReceipt: sql`${jobQueue.claimReceipt}`
|
|
4306
|
+
}).where(sql`0`);
|
|
4307
|
+
return yield* Effect25.flatMap(DateTime7.now, query);
|
|
4308
|
+
});
|
|
4309
|
+
return yield* (Option4.isSome(transaction) ? mutate : client.withTransaction(mutate)).pipe(retryTransientSqliteError);
|
|
4310
|
+
});
|
|
4311
|
+
var attemptBudget = (queue, retryLimit) => {
|
|
4312
|
+
if (retryLimit === undefined)
|
|
4313
|
+
return Effect25.succeed(DEFAULT_MAX_RETRIES);
|
|
4314
|
+
return Number.isSafeInteger(retryLimit) && retryLimit >= 0 && Number.isSafeInteger(retryLimit + 1) ? Effect25.succeed(retryLimit + 1) : Effect25.fail(new EnqueueError({
|
|
4315
|
+
queue,
|
|
4316
|
+
message: "retryLimit must be a non-negative safe integer with a safe retryLimit + 1 total-attempt budget"
|
|
4317
|
+
}));
|
|
4318
|
+
};
|
|
4319
|
+
var reportEnqueue = Effect25.fnUntraced(function* (queue, jobId) {
|
|
4320
|
+
const sqlClient = yield* SqlClient.SqlClient;
|
|
4321
|
+
const transaction = yield* Effect25.serviceOption(sqlClient.transactionService);
|
|
4322
|
+
const accepted = Effect25.logInfo("Queue enqueue accepted", {
|
|
4323
|
+
queue,
|
|
4324
|
+
jobId,
|
|
4325
|
+
acceptance: "accepted"
|
|
4326
|
+
});
|
|
4327
|
+
if (Option4.isNone(transaction)) {
|
|
4328
|
+
yield* accepted;
|
|
4329
|
+
return;
|
|
4330
|
+
}
|
|
4331
|
+
yield* Effect25.logInfo("Queue enqueue staged (provisional until outer commit)", {
|
|
4332
|
+
queue,
|
|
4333
|
+
jobId,
|
|
4334
|
+
acceptance: "staged"
|
|
4335
|
+
});
|
|
4336
|
+
const callbacks = yield* Effect25.serviceOption(TransactionCommitCallbacks);
|
|
4337
|
+
if (Option4.isSome(callbacks) && callbacks.value.transactionKey === sqlClient.transactionService.key) {
|
|
4338
|
+
callbacks.value.callbacks.push(accepted);
|
|
4339
|
+
}
|
|
4340
|
+
});
|
|
4341
|
+
var AdditionalClaimCondition = Context3.Reference("processfocus:internal-tag/sqlite-queue-service/AdditionalClaimCondition", {
|
|
4342
|
+
defaultValue: () => {
|
|
4343
|
+
return;
|
|
4344
|
+
}
|
|
4345
|
+
});
|
|
4346
|
+
var QueueLive = Layer26.effect(QueueService, Effect25.gen(function* () {
|
|
4347
|
+
const context = yield* Effect25.context();
|
|
4348
|
+
const additionalClaimCondition = yield* AdditionalClaimCondition;
|
|
4349
|
+
const queue = {
|
|
4350
|
+
queueInTransaction: true,
|
|
4351
|
+
enqueue: (queue, payload, options) => Effect25.gen(function* () {
|
|
4352
|
+
yield* validateQueueName(queue);
|
|
4353
|
+
const maxAttempts = yield* attemptBudget(queue, options?.retryLimit);
|
|
4354
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4355
|
+
const requestTime = yield* getRequestTime();
|
|
4356
|
+
const userDetails = yield* getUserDetails();
|
|
4357
|
+
const result = yield* db.insert(jobQueue).values({
|
|
4358
|
+
queue,
|
|
4359
|
+
jobPayload: payload,
|
|
4360
|
+
jobRetryLimit: maxAttempts,
|
|
4361
|
+
availableAt: requestTime,
|
|
4362
|
+
lockedUntil: null,
|
|
4363
|
+
createdAt: requestTime,
|
|
4364
|
+
updatedAt: requestTime,
|
|
4365
|
+
createdBy: userDetails.by,
|
|
4366
|
+
updatedBy: userDetails.by
|
|
4367
|
+
}).returning({ id: jobQueue.id }).pipe(retryTransientSqliteError, Effect25.catchTag("SqlError", (error) => {
|
|
4368
|
+
const formattedMsg = formatSqlError(error);
|
|
4369
|
+
return logQueueFailure("enqueue", formattedMsg, new EnqueueError({
|
|
4370
|
+
queue,
|
|
4371
|
+
message: `Database error: ${formattedMsg}`,
|
|
4372
|
+
cause: error
|
|
4373
|
+
}));
|
|
4374
|
+
}));
|
|
4375
|
+
const row = yield* returnedRow(result);
|
|
4376
|
+
yield* reportEnqueue(queue, row.id);
|
|
4377
|
+
return row.id;
|
|
4378
|
+
}),
|
|
4379
|
+
enqueueWithDelay: (queue, payload, delay, options) => Effect25.gen(function* () {
|
|
4380
|
+
yield* validateQueueName(queue);
|
|
4381
|
+
const maxAttempts = yield* attemptBudget(queue, options?.retryLimit);
|
|
4382
|
+
const delayMs = Duration.toMillis(delay);
|
|
4383
|
+
if (!Number.isFinite(delayMs) || delayMs < 0) {
|
|
4384
|
+
return yield* new EnqueueError({
|
|
4385
|
+
queue,
|
|
4386
|
+
message: "Scheduling delay must be finite and non-negative"
|
|
4387
|
+
});
|
|
4388
|
+
}
|
|
4389
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4390
|
+
const requestTime = yield* getRequestTime();
|
|
4391
|
+
const userDetails = yield* getUserDetails();
|
|
4392
|
+
const availableAt = DateTime7.add(requestTime, {
|
|
4393
|
+
milliseconds: delayMs
|
|
4394
|
+
});
|
|
4395
|
+
const result = yield* db.insert(jobQueue).values({
|
|
4396
|
+
queue,
|
|
4397
|
+
jobPayload: payload,
|
|
4398
|
+
jobRetryLimit: maxAttempts,
|
|
4399
|
+
availableAt,
|
|
4400
|
+
lockedUntil: null,
|
|
4401
|
+
createdAt: requestTime,
|
|
4402
|
+
updatedAt: requestTime,
|
|
4403
|
+
createdBy: userDetails.by,
|
|
4404
|
+
updatedBy: userDetails.by
|
|
4405
|
+
}).returning({ id: jobQueue.id }).pipe(retryTransientSqliteError, Effect25.catchTag("SqlError", (error) => {
|
|
4406
|
+
const formattedMsg = formatSqlError(error);
|
|
4407
|
+
return logQueueFailure("enqueueWithDelay", formattedMsg, new EnqueueError({
|
|
4408
|
+
queue,
|
|
4409
|
+
message: `Database error: ${formattedMsg}`,
|
|
4410
|
+
cause: error
|
|
4411
|
+
}));
|
|
4412
|
+
}));
|
|
4413
|
+
const row = yield* returnedRow(result);
|
|
4414
|
+
yield* reportEnqueue(queue, row.id);
|
|
4415
|
+
return row.id;
|
|
4416
|
+
}),
|
|
4417
|
+
rawClaim: (name, visibilityTimeout) => queue.rawClaimBatch(name, 1, visibilityTimeout).pipe(Effect25.map(Option4.fromIterable)),
|
|
4418
|
+
rawClaimBatch: (queue, limit, visibilityTimeout) => Effect25.gen(function* () {
|
|
4419
|
+
yield* validateQueueName(queue);
|
|
4420
|
+
const sqlClient = yield* SqlClient.SqlClient;
|
|
4421
|
+
if (!Number.isSafeInteger(limit) || limit <= 0) {
|
|
4422
|
+
return yield* new ClaimError({
|
|
4423
|
+
queue,
|
|
4424
|
+
message: "Claim limit must be a positive safe integer"
|
|
4425
|
+
});
|
|
4426
|
+
}
|
|
4427
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4428
|
+
const now = yield* DateTime7.now;
|
|
4429
|
+
const timeout = visibilityTimeout ?? DEFAULT_VISIBILITY_TIMEOUT;
|
|
4430
|
+
const timeoutMs = Duration.toMillis(timeout);
|
|
4431
|
+
const lockedUntil = DateTime7.add(now, { milliseconds: timeoutMs });
|
|
4432
|
+
const availableJobConditions = and(isNull(jobQueue.terminalAt), or(eq(jobQueue.queue, queue), additionalClaimCondition?.(queue)), lte(jobQueue.availableAt, now), or(isNull(jobQueue.lockedUntil), lte(jobQueue.lockedUntil, now)), lt(jobQueue.jobAttempts, jobQueue.jobRetryLimit), eq(jobQueue._deleted, sql`0`));
|
|
4433
|
+
const candidate = yield* db.select({ id: jobQueue.id }).from(jobQueue).where(availableJobConditions).limit(1).pipe(retryTransientSqliteError, Effect25.catchTag("SqlError", (error) => {
|
|
4434
|
+
const formattedMsg = formatSqlError(error);
|
|
4435
|
+
return logQueueFailure("rawClaim.check", formattedMsg, new ClaimError({
|
|
4436
|
+
queue,
|
|
4437
|
+
message: `Database error: ${formattedMsg}`,
|
|
4438
|
+
cause: error
|
|
4439
|
+
}));
|
|
4440
|
+
}));
|
|
4441
|
+
if (!candidate[0]) {
|
|
4442
|
+
return [];
|
|
4443
|
+
}
|
|
4444
|
+
return yield* sqlClient.withTransaction(Effect25.gen(function* () {
|
|
4445
|
+
const nextJobId = sql`(
|
|
4446
|
+
select ${jobQueue.id}
|
|
4447
|
+
from ${jobQueue}
|
|
4448
|
+
where ${availableJobConditions}
|
|
4449
|
+
order by ${jobQueue.jobAttempts}, ${jobQueue.availableAt}, ${jobQueue.id}
|
|
4450
|
+
limit ${sql.raw(String(limit))}
|
|
4451
|
+
)`;
|
|
4452
|
+
const result = yield* db.update(jobQueue).set({
|
|
4453
|
+
lockedUntil,
|
|
4454
|
+
claimReceipt: sql`lower(hex(randomblob(16)))`,
|
|
4455
|
+
jobAttempts: sql`${jobQueue.jobAttempts} + 1`
|
|
4456
|
+
}).where(sql`${jobQueue.id} IN ${nextJobId}`).returning({
|
|
4457
|
+
id: jobQueue.id,
|
|
4458
|
+
queue: jobQueue.queue,
|
|
4459
|
+
jobPayload: jobQueue.jobPayload,
|
|
4460
|
+
jobAttempts: jobQueue.jobAttempts,
|
|
4461
|
+
jobRetryLimit: jobQueue.jobRetryLimit,
|
|
4462
|
+
availableAt: jobQueue.availableAt,
|
|
4463
|
+
claimReceipt: sql`${jobQueue.claimReceipt}`
|
|
4464
|
+
});
|
|
4465
|
+
return result.sort((left, right) => left.jobAttempts - right.jobAttempts || DateTime7.toEpochMillis(left.availableAt) - DateTime7.toEpochMillis(right.availableAt) || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0)).map((row) => ({
|
|
4466
|
+
jobId: row.id,
|
|
4467
|
+
receipt: row.claimReceipt,
|
|
4468
|
+
queue: row.queue,
|
|
4469
|
+
payload: row.jobPayload,
|
|
4470
|
+
attempts: row.jobAttempts,
|
|
4471
|
+
maxAttempts: row.jobRetryLimit,
|
|
4472
|
+
availableAt: row.availableAt,
|
|
4473
|
+
lockedUntil
|
|
4474
|
+
}));
|
|
4475
|
+
})).pipe(retryTransientSqliteError, Effect25.catchTag("SqlError", (error) => {
|
|
4476
|
+
const formattedMsg = formatSqlError(error);
|
|
4477
|
+
return logQueueFailure("rawClaim", formattedMsg, new ClaimError({
|
|
4478
|
+
queue,
|
|
4479
|
+
message: `Database error: ${formattedMsg}`,
|
|
4480
|
+
cause: error
|
|
4481
|
+
}));
|
|
4482
|
+
}));
|
|
4483
|
+
}),
|
|
4484
|
+
acknowledgeBatch: (claims) => Effect25.gen(function* () {
|
|
4485
|
+
const first = claims[0];
|
|
4486
|
+
if (!first)
|
|
4487
|
+
return [];
|
|
4488
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4489
|
+
const acknowledge = Effect25.gen(function* () {
|
|
4490
|
+
const deletedIds = [];
|
|
4491
|
+
for (let offset = 0;offset < claims.length; offset += ACKNOWLEDGE_BATCH_SIZE) {
|
|
4492
|
+
const pairs = claims.slice(offset, offset + ACKNOWLEDGE_BATCH_SIZE).map(({ jobId, receipt }) => sql`(${jobId}, ${receipt})`);
|
|
4493
|
+
const rows = yield* retryWithClaimTime((now) => db.delete(jobQueue).where(and(sql`(${jobQueue.id}, ${jobQueue.claimReceipt}) IN (VALUES ${sql.join(pairs, sql`, `)})`, gt(jobQueue.lockedUntil, now))).returning({ id: jobQueue.id }));
|
|
4494
|
+
deletedIds.push(...rows.map((row) => row.id));
|
|
4495
|
+
}
|
|
4496
|
+
return deletedIds;
|
|
4497
|
+
});
|
|
4498
|
+
const sqlClient = yield* SqlClient.SqlClient;
|
|
4499
|
+
return yield* (claims.length > ACKNOWLEDGE_BATCH_SIZE ? sqlClient.withTransaction(acknowledge) : acknowledge).pipe(Effect25.mapError((cause) => new AcknowledgeError({
|
|
4500
|
+
jobId: first.jobId,
|
|
4501
|
+
message: `Failed to acknowledge batch: ${formatSqlError(cause)}`,
|
|
4502
|
+
cause
|
|
4503
|
+
})));
|
|
4504
|
+
}),
|
|
4505
|
+
acknowledge: (jobId, receipt) => Effect25.gen(function* () {
|
|
4506
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4507
|
+
const result = yield* retryWithClaimTime((now) => db.delete(jobQueue).where(and(eq(jobQueue.id, jobId), eq(jobQueue.claimReceipt, receipt), gt(jobQueue.lockedUntil, now))).returning({ id: jobQueue.id })).pipe(Effect25.catchTag("SqlError", (error) => {
|
|
4508
|
+
const formattedMsg = formatSqlError(error);
|
|
4509
|
+
return logQueueFailure("acknowledge", formattedMsg, new AcknowledgeError({
|
|
4510
|
+
jobId,
|
|
4511
|
+
message: `Database error: ${formattedMsg}`,
|
|
4512
|
+
cause: error
|
|
4513
|
+
}));
|
|
4514
|
+
}));
|
|
4515
|
+
if (!result[0]) {
|
|
4516
|
+
const exists = yield* db.select({ id: jobQueue.id }).from(jobQueue).where(eq(jobQueue.id, jobId)).pipe(retryTransientSqliteError, mapClaimVerificationError(jobId));
|
|
4517
|
+
return yield* exists[0] ? new StaleJobClaimError({ jobId }) : new JobNotFoundError({ jobId });
|
|
4518
|
+
}
|
|
4519
|
+
}),
|
|
4520
|
+
fail: (jobId, receipt, options) => Effect25.gen(function* () {
|
|
4521
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4522
|
+
{
|
|
4523
|
+
const result = yield* retryWithClaimTime((now) => db.update(jobQueue).set({
|
|
4524
|
+
terminalAt: now,
|
|
4525
|
+
terminalReason: options?.reason ?? (options?.retryable === false ? "Non-retryable failure reported without a diagnostic reason" : "Attempt ended without a known handler outcome"),
|
|
4526
|
+
terminalOutcome: options?.retryable === false || options?.reason !== undefined ? "handler-failure" : "unknown",
|
|
4527
|
+
lockedUntil: null,
|
|
4528
|
+
claimReceipt: null
|
|
4529
|
+
}).where(and(eq(jobQueue.id, jobId), eq(jobQueue.claimReceipt, receipt), gt(jobQueue.lockedUntil, now), isNull(jobQueue.terminalAt), options?.retryable === false ? sql`1` : sql`${jobQueue.jobAttempts} >= ${jobQueue.jobRetryLimit}`)).returning({ queue: jobQueue.queue })).pipe(Effect25.catchTag("SqlError", (error) => {
|
|
4530
|
+
const formattedMsg = formatSqlError(error);
|
|
4531
|
+
return logQueueFailure("fail.terminal", formattedMsg, new AcknowledgeError({
|
|
4532
|
+
jobId,
|
|
4533
|
+
message: `Failed to dead-letter job: ${formattedMsg}`,
|
|
4534
|
+
cause: error
|
|
4535
|
+
}));
|
|
4536
|
+
}));
|
|
4537
|
+
if (result[0]) {
|
|
4538
|
+
yield* Effect25.logWarning("Queue job terminal disposition recorded", {
|
|
4539
|
+
jobId,
|
|
4540
|
+
queue: result[0].queue,
|
|
4541
|
+
outcome: options?.retryable === false || options?.reason !== undefined ? "handler-failure" : "unknown",
|
|
4542
|
+
reason: options?.reason
|
|
4543
|
+
});
|
|
4544
|
+
return;
|
|
4545
|
+
}
|
|
4546
|
+
if (options?.retryable === false) {
|
|
4547
|
+
const exists = yield* db.select({ id: jobQueue.id }).from(jobQueue).where(eq(jobQueue.id, jobId)).pipe(retryTransientSqliteError, mapClaimVerificationError(jobId));
|
|
4548
|
+
return yield* exists[0] ? new StaleJobClaimError({ jobId }) : new JobNotFoundError({ jobId });
|
|
4549
|
+
}
|
|
4550
|
+
}
|
|
4551
|
+
if (options?.releaseImmediately) {
|
|
4552
|
+
const result = yield* retryWithClaimTime((now) => db.update(jobQueue).set({ lockedUntil: now, claimReceipt: null }).where(and(eq(jobQueue.id, jobId), eq(jobQueue.claimReceipt, receipt), gt(jobQueue.lockedUntil, now))).returning({ id: jobQueue.id })).pipe(Effect25.catchTag("SqlError", (error) => {
|
|
4553
|
+
const formattedMsg = formatSqlError(error);
|
|
4554
|
+
return logQueueFailure("fail.releaseImmediately", formattedMsg, new AcknowledgeError({
|
|
4555
|
+
jobId,
|
|
4556
|
+
message: `Failed to mark job as failed: ${formattedMsg}`,
|
|
4557
|
+
cause: error
|
|
4558
|
+
}));
|
|
4559
|
+
}));
|
|
4560
|
+
if (!result[0]) {
|
|
4561
|
+
const exists = yield* db.select({ id: jobQueue.id }).from(jobQueue).where(eq(jobQueue.id, jobId)).pipe(retryTransientSqliteError, mapClaimVerificationError(jobId));
|
|
4562
|
+
return yield* exists[0] ? new StaleJobClaimError({ jobId }) : new JobNotFoundError({ jobId });
|
|
4563
|
+
}
|
|
4564
|
+
} else {
|
|
4565
|
+
const result = yield* Effect25.flatMap(DateTime7.now, (now) => db.select({ id: jobQueue.id }).from(jobQueue).where(and(eq(jobQueue.id, jobId), eq(jobQueue.claimReceipt, receipt), gt(jobQueue.lockedUntil, now)))).pipe(retryTransientSqliteError, Effect25.catchTag("SqlError", (error) => {
|
|
4566
|
+
const formattedMsg = formatSqlError(error);
|
|
4567
|
+
return logQueueFailure("fail.verify", formattedMsg, new AcknowledgeError({
|
|
4568
|
+
jobId,
|
|
4569
|
+
message: `Failed to verify job exists: ${formattedMsg}`,
|
|
4570
|
+
cause: error
|
|
4571
|
+
}));
|
|
4572
|
+
}));
|
|
4573
|
+
if (!result[0]) {
|
|
4574
|
+
const exists = yield* db.select({ id: jobQueue.id }).from(jobQueue).where(eq(jobQueue.id, jobId)).pipe(retryTransientSqliteError, mapClaimVerificationError(jobId));
|
|
4575
|
+
return yield* exists[0] ? new StaleJobClaimError({ jobId }) : new JobNotFoundError({ jobId });
|
|
4576
|
+
}
|
|
4577
|
+
}
|
|
4578
|
+
}),
|
|
4579
|
+
extendVisibility: (jobId, receipt, timeout) => Effect25.gen(function* () {
|
|
4580
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4581
|
+
const timeoutMs = Duration.toMillis(timeout);
|
|
4582
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) {
|
|
4583
|
+
return yield* new AcknowledgeError({
|
|
4584
|
+
jobId,
|
|
4585
|
+
message: "Visibility timeout must be a positive integer <= 2147483647 milliseconds"
|
|
4586
|
+
});
|
|
4587
|
+
}
|
|
4588
|
+
const result = yield* retryWithClaimTime((now) => db.update(jobQueue).set({
|
|
4589
|
+
lockedUntil: DateTime7.add(now, { milliseconds: timeoutMs })
|
|
4590
|
+
}).where(and(eq(jobQueue.id, jobId), eq(jobQueue.claimReceipt, receipt), gt(jobQueue.lockedUntil, now))).returning({ id: jobQueue.id })).pipe(Effect25.catchTag("SqlError", (error) => {
|
|
4591
|
+
const formattedMsg = formatSqlError(error);
|
|
4592
|
+
return logQueueFailure("extendVisibility", formattedMsg, new AcknowledgeError({
|
|
4593
|
+
jobId,
|
|
4594
|
+
message: `Failed to extend visibility: ${formattedMsg}`,
|
|
4595
|
+
cause: error
|
|
4596
|
+
}));
|
|
4597
|
+
}));
|
|
4598
|
+
if (!result[0]) {
|
|
4599
|
+
const exists = yield* db.select({
|
|
4600
|
+
lockedUntil: jobQueue.lockedUntil,
|
|
4601
|
+
claimReceipt: jobQueue.claimReceipt
|
|
4602
|
+
}).from(jobQueue).where(eq(jobQueue.id, jobId)).pipe(retryTransientSqliteError, Effect25.catchTag("SqlError", (error) => {
|
|
4603
|
+
const formattedMsg = formatSqlError(error);
|
|
4604
|
+
return logQueueFailure("extendVisibility.verify", formattedMsg, new AcknowledgeError({
|
|
4605
|
+
jobId,
|
|
4606
|
+
message: `Failed to verify job: ${formattedMsg}`,
|
|
4607
|
+
cause: error
|
|
4608
|
+
}));
|
|
4609
|
+
}));
|
|
4610
|
+
if (!exists[0]) {
|
|
4611
|
+
return yield* new JobNotFoundError({ jobId });
|
|
4612
|
+
}
|
|
4613
|
+
if (exists[0].claimReceipt !== receipt) {
|
|
4614
|
+
return yield* new StaleJobClaimError({ jobId });
|
|
4615
|
+
}
|
|
4616
|
+
return yield* new AcknowledgeError({
|
|
4617
|
+
jobId,
|
|
4618
|
+
message: "Cannot extend visibility of unlocked job"
|
|
4619
|
+
});
|
|
4620
|
+
}
|
|
4621
|
+
}),
|
|
4622
|
+
getStats: (queue) => Effect25.gen(function* () {
|
|
4623
|
+
yield* validateQueueName(queue);
|
|
4624
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4625
|
+
const now = yield* DateTime7.now;
|
|
4626
|
+
const nowMillis = DateTime7.toEpochMillis(now);
|
|
4627
|
+
const nowJulian = nowMillis / MILLISECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY;
|
|
4628
|
+
const stats = yield* db.select({
|
|
4629
|
+
pending: sql`COUNT(CASE
|
|
4630
|
+
WHEN ${jobQueue.terminalAt} IS NULL AND (${jobQueue.lockedUntil} IS NULL OR ${jobQueue.lockedUntil} <= ${nowJulian})
|
|
4631
|
+
AND ${jobQueue.jobAttempts} < ${jobQueue.jobRetryLimit}
|
|
4632
|
+
THEN 1 END)`,
|
|
4633
|
+
processing: sql`COUNT(CASE
|
|
4634
|
+
WHEN ${jobQueue.terminalAt} IS NULL AND ${jobQueue.lockedUntil} > ${nowJulian}
|
|
4635
|
+
THEN 1 END)`,
|
|
4636
|
+
deadLetter: sql`COUNT(CASE
|
|
4637
|
+
WHEN ${jobQueue.terminalAt} IS NOT NULL
|
|
4638
|
+
THEN 1 END)`
|
|
4639
|
+
}).from(jobQueue).where(and(eq(jobQueue.queue, queue), eq(jobQueue._deleted, sql`0`))).pipe(Effect25.mapError((cause) => new QueueStatsError({
|
|
4640
|
+
queue,
|
|
4641
|
+
message: "Queue statistics unavailable",
|
|
4642
|
+
cause
|
|
4643
|
+
})));
|
|
4644
|
+
return stats[0] ?? {
|
|
4645
|
+
pending: 0,
|
|
4646
|
+
processing: 0,
|
|
4647
|
+
deadLetter: 0
|
|
4648
|
+
};
|
|
4649
|
+
})
|
|
4650
|
+
};
|
|
4651
|
+
return QueueService.of(closeQueue(queue, context));
|
|
4652
|
+
}));
|
|
4653
|
+
var readSqliteQueueHealth = Effect25.gen(function* () {
|
|
4654
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4655
|
+
const now = DateTime7.toEpochMillis(yield* DateTime7.now);
|
|
4656
|
+
const rows = yield* db.select({
|
|
4657
|
+
jobId: jobQueue.id,
|
|
4658
|
+
queue: jobQueue.queue,
|
|
4659
|
+
availableAt: jobQueue.availableAt,
|
|
4660
|
+
lockedUntil: jobQueue.lockedUntil,
|
|
4661
|
+
attempts: jobQueue.jobAttempts,
|
|
4662
|
+
limit: jobQueue.jobRetryLimit,
|
|
4663
|
+
terminalAt: jobQueue.terminalAt
|
|
4664
|
+
}).from(jobQueue).where(eq(jobQueue._deleted, sql`0`));
|
|
4665
|
+
const queues = new Map;
|
|
4666
|
+
for (const row of rows) {
|
|
4667
|
+
const health = queues.get(row.queue) ?? {
|
|
4668
|
+
queue: row.queue,
|
|
4669
|
+
eligible: 0,
|
|
4670
|
+
delayed: 0,
|
|
4671
|
+
processing: 0,
|
|
4672
|
+
recoveryNeeded: 0,
|
|
4673
|
+
terminal: 0,
|
|
4674
|
+
oldestEligible: null
|
|
4675
|
+
};
|
|
4676
|
+
queues.set(row.queue, health);
|
|
4677
|
+
const lease = row.lockedUntil === null ? 0 : DateTime7.toEpochMillis(row.lockedUntil);
|
|
4678
|
+
const available = DateTime7.toEpochMillis(row.availableAt);
|
|
4679
|
+
if (row.terminalAt !== null)
|
|
4680
|
+
health.terminal++;
|
|
4681
|
+
else if (lease > now)
|
|
4682
|
+
health.processing++;
|
|
4683
|
+
else if (row.attempts >= row.limit)
|
|
4684
|
+
health.recoveryNeeded++;
|
|
4685
|
+
else if (available > now)
|
|
4686
|
+
health.delayed++;
|
|
4687
|
+
else {
|
|
4688
|
+
health.eligible++;
|
|
4689
|
+
const waitingMs = Math.max(0, now - Math.max(available, lease));
|
|
4690
|
+
if (health.oldestEligible === null || waitingMs > health.oldestEligible.waitingMs)
|
|
4691
|
+
health.oldestEligible = { jobId: row.jobId, waitingMs };
|
|
4692
|
+
}
|
|
4693
|
+
}
|
|
4694
|
+
return [...queues.values()];
|
|
4695
|
+
}).pipe(Effect25.mapError((cause) => new QueueStatsError({
|
|
4696
|
+
queue: "*",
|
|
4697
|
+
message: "Queue health unavailable",
|
|
4698
|
+
cause
|
|
4699
|
+
})));
|
|
4700
|
+
|
|
4701
|
+
class SqliteQueueMaintenance extends Context3.Service()("processfocus:internal-tag/sqlite-queue-service/SqliteQueueMaintenance") {
|
|
4702
|
+
}
|
|
4703
|
+
var MaintenanceLive = Layer26.effect(SqliteQueueMaintenance, Effect25.gen(function* () {
|
|
4704
|
+
const context = yield* Effect25.context();
|
|
4705
|
+
const provide = Effect25.updateContext((caller) => Context3.merge(context, caller));
|
|
4706
|
+
return SqliteQueueMaintenance.of({
|
|
4707
|
+
inspect: () => readSqliteQueueHealth.pipe(provide),
|
|
4708
|
+
recover: () => Effect25.gen(function* () {
|
|
4709
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4710
|
+
const rows = yield* retryWithClaimTime((now) => db.update(jobQueue).set({
|
|
4711
|
+
terminalAt: now,
|
|
4712
|
+
terminalReason: "Attempt budget exhausted without a recorded outcome (abandoned or legacy claim)",
|
|
4713
|
+
terminalOutcome: "unknown",
|
|
4714
|
+
lockedUntil: null,
|
|
4715
|
+
claimReceipt: null
|
|
4716
|
+
}).where(and(eq(jobQueue._deleted, sql`0`), isNull(jobQueue.terminalAt), sql`${jobQueue.jobAttempts} >= ${jobQueue.jobRetryLimit}`, or(isNull(jobQueue.lockedUntil), lte(jobQueue.lockedUntil, now)))).returning({ id: jobQueue.id }));
|
|
4717
|
+
return rows.length;
|
|
4718
|
+
}).pipe(provide, Effect25.mapError((cause) => new AcknowledgeError({
|
|
4719
|
+
jobId: "maintenance",
|
|
4720
|
+
message: "Failed to recover exhausted queue jobs",
|
|
4721
|
+
cause
|
|
4722
|
+
}))),
|
|
4723
|
+
redrive: (jobId) => Effect25.gen(function* () {
|
|
4724
|
+
const db = yield* TypedSqliteDrizzle;
|
|
4725
|
+
const client = yield* SqlClient.SqlClient;
|
|
4726
|
+
const accepted = yield* client.withTransaction(Effect25.gen(function* () {
|
|
4727
|
+
const [prior] = yield* db.select().from(jobQueue).where(and(eq(jobQueue.id, jobId), isNotNull(jobQueue.terminalAt)));
|
|
4728
|
+
if (!prior)
|
|
4729
|
+
return yield* new JobNotFoundError({ jobId });
|
|
4730
|
+
const now = yield* getRequestTime();
|
|
4731
|
+
const user = yield* getUserDetails();
|
|
4732
|
+
const rows = yield* db.insert(jobQueue).values({
|
|
4733
|
+
queue: prior.queue,
|
|
4734
|
+
jobPayload: prior.jobPayload,
|
|
4735
|
+
jobRetryLimit: prior.jobRetryLimit,
|
|
4736
|
+
availableAt: now,
|
|
4737
|
+
createdAt: now,
|
|
4738
|
+
updatedAt: now,
|
|
4739
|
+
createdBy: user.by,
|
|
4740
|
+
updatedBy: user.by,
|
|
4741
|
+
redrivenFrom: jobId
|
|
4742
|
+
}).returning({ id: jobQueue.id });
|
|
4743
|
+
return { id: (yield* returnedRow(rows)).id, queue: prior.queue };
|
|
4744
|
+
})).pipe(retryTransientSqliteError);
|
|
4745
|
+
yield* reportEnqueue(accepted.queue, accepted.id);
|
|
4746
|
+
return accepted.id;
|
|
4747
|
+
}).pipe(provide, Effect25.catchTag("SqlError", (cause) => new AcknowledgeError({
|
|
4748
|
+
jobId,
|
|
4749
|
+
message: "Failed to redrive terminal job",
|
|
4750
|
+
cause
|
|
4751
|
+
})))
|
|
4752
|
+
});
|
|
4753
|
+
}));
|
|
4754
|
+
var SqliteQueueServiceLive = Layer26.merge(QueueLive, MaintenanceLive);
|
|
4755
|
+
export { RequestTime, getRequestTime, SqliteCompletedJobOperationsLive, SqliteFileOperationsLive, SqliteFlowExecutionOperationsLive, SqliteGraphqlDbOperationsLive, SqliteScheduledFlowOperationsLive, SqliteQueueMaintenance, SqliteQueueServiceLive };
|