@frigear-nu/shifts 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -2
- package/dist/module.d.mts +709 -0
- package/dist/module.json +9 -0
- package/dist/module.mjs +253 -0
- package/dist/runtime/access.d.ts +2 -0
- package/dist/runtime/access.js +84 -0
- package/dist/runtime/app/components/ShiftBroadcastSlideover.d.vue.ts +19 -0
- package/dist/runtime/app/components/ShiftBroadcastSlideover.vue +142 -0
- package/dist/runtime/app/components/ShiftBroadcastSlideover.vue.d.ts +19 -0
- package/dist/runtime/app/components/ShiftBroadcastsCard.d.vue.ts +9 -0
- package/dist/runtime/app/components/ShiftBroadcastsCard.vue +74 -0
- package/dist/runtime/app/components/ShiftBroadcastsCard.vue.d.ts +9 -0
- package/dist/runtime/app/components/ShiftBulkSlideover.d.vue.ts +15 -0
- package/dist/runtime/app/components/ShiftBulkSlideover.vue +185 -0
- package/dist/runtime/app/components/ShiftBulkSlideover.vue.d.ts +15 -0
- package/dist/runtime/app/components/ShiftCheckInCard.d.vue.ts +13 -0
- package/dist/runtime/app/components/ShiftCheckInCard.vue +238 -0
- package/dist/runtime/app/components/ShiftCheckInCard.vue.d.ts +13 -0
- package/dist/runtime/app/components/ShiftCopySlideover.d.vue.ts +11 -0
- package/dist/runtime/app/components/ShiftCopySlideover.vue +71 -0
- package/dist/runtime/app/components/ShiftCopySlideover.vue.d.ts +11 -0
- package/dist/runtime/app/components/ShiftDayView.d.vue.ts +16 -0
- package/dist/runtime/app/components/ShiftDayView.vue +124 -0
- package/dist/runtime/app/components/ShiftDayView.vue.d.ts +16 -0
- package/dist/runtime/app/components/ShiftFeedSlideover.d.vue.ts +7 -0
- package/dist/runtime/app/components/ShiftFeedSlideover.vue +172 -0
- package/dist/runtime/app/components/ShiftFeedSlideover.vue.d.ts +7 -0
- package/dist/runtime/app/components/ShiftNowCard.d.vue.ts +6 -0
- package/dist/runtime/app/components/ShiftNowCard.vue +83 -0
- package/dist/runtime/app/components/ShiftNowCard.vue.d.ts +6 -0
- package/dist/runtime/app/components/ShiftPassFullscreen.d.vue.ts +13 -0
- package/dist/runtime/app/components/ShiftPassFullscreen.vue +79 -0
- package/dist/runtime/app/components/ShiftPassFullscreen.vue.d.ts +13 -0
- package/dist/runtime/app/components/ShiftPerkSlideover.d.vue.ts +14 -0
- package/dist/runtime/app/components/ShiftPerkSlideover.vue +103 -0
- package/dist/runtime/app/components/ShiftPerkSlideover.vue.d.ts +14 -0
- package/dist/runtime/app/components/ShiftPerksCard.d.vue.ts +8 -0
- package/dist/runtime/app/components/ShiftPerksCard.vue +66 -0
- package/dist/runtime/app/components/ShiftPerksCard.vue.d.ts +8 -0
- package/dist/runtime/app/components/ShiftQrScanner.d.vue.ts +10 -0
- package/dist/runtime/app/components/ShiftQrScanner.vue +44 -0
- package/dist/runtime/app/components/ShiftQrScanner.vue.d.ts +10 -0
- package/dist/runtime/app/components/ShiftRoleSlideover.d.vue.ts +15 -0
- package/dist/runtime/app/components/ShiftRoleSlideover.vue +88 -0
- package/dist/runtime/app/components/ShiftRoleSlideover.vue.d.ts +15 -0
- package/dist/runtime/app/components/ShiftScheduleSettingsFields.d.vue.ts +11 -0
- package/dist/runtime/app/components/ShiftScheduleSettingsFields.vue +61 -0
- package/dist/runtime/app/components/ShiftScheduleSettingsFields.vue.d.ts +11 -0
- package/dist/runtime/app/components/ShiftScheduleSlideover.d.vue.ts +12 -0
- package/dist/runtime/app/components/ShiftScheduleSlideover.vue +129 -0
- package/dist/runtime/app/components/ShiftScheduleSlideover.vue.d.ts +12 -0
- package/dist/runtime/app/components/ShiftSlideover.d.vue.ts +13 -0
- package/dist/runtime/app/components/ShiftSlideover.vue +353 -0
- package/dist/runtime/app/components/ShiftSlideover.vue.d.ts +13 -0
- package/dist/runtime/app/components/ShiftStationSlideover.d.vue.ts +15 -0
- package/dist/runtime/app/components/ShiftStationSlideover.vue +92 -0
- package/dist/runtime/app/components/ShiftStationSlideover.vue.d.ts +15 -0
- package/dist/runtime/app/composables/index.d.ts +6 -0
- package/dist/runtime/app/composables/index.js +5 -0
- package/dist/runtime/app/composables/useShiftsActions.d.ts +61 -0
- package/dist/runtime/app/composables/useShiftsActions.js +224 -0
- package/dist/runtime/app/composables/useShiftsFormat.d.ts +12 -0
- package/dist/runtime/app/composables/useShiftsFormat.js +14 -0
- package/dist/runtime/app/composables/useShiftsLinks.d.ts +12 -0
- package/dist/runtime/app/composables/useShiftsLinks.js +6 -0
- package/dist/runtime/app/composables/useShiftsTranslate.d.ts +5 -0
- package/dist/runtime/app/composables/useShiftsTranslate.js +12 -0
- package/dist/runtime/app/composables/useShiftsVenueFeatures.d.ts +17 -0
- package/dist/runtime/app/composables/useShiftsVenueFeatures.js +18 -0
- package/dist/runtime/app/dashboard/NextShift.d.vue.ts +3 -0
- package/dist/runtime/app/dashboard/NextShift.vue +69 -0
- package/dist/runtime/app/dashboard/NextShift.vue.d.ts +3 -0
- package/dist/runtime/app/dashboard/OpenSwaps.d.vue.ts +3 -0
- package/dist/runtime/app/dashboard/OpenSwaps.vue +69 -0
- package/dist/runtime/app/dashboard/OpenSwaps.vue.d.ts +3 -0
- package/dist/runtime/app/dashboard/TeamOnNow.d.vue.ts +3 -0
- package/dist/runtime/app/dashboard/TeamOnNow.vue +72 -0
- package/dist/runtime/app/dashboard/TeamOnNow.vue.d.ts +3 -0
- package/dist/runtime/app/pages/check-in.d.vue.ts +3 -0
- package/dist/runtime/app/pages/check-in.vue +93 -0
- package/dist/runtime/app/pages/check-in.vue.d.ts +3 -0
- package/dist/runtime/app/pages/lead.d.vue.ts +3 -0
- package/dist/runtime/app/pages/lead.vue +300 -0
- package/dist/runtime/app/pages/lead.vue.d.ts +3 -0
- package/dist/runtime/app/pages/shift.d.vue.ts +3 -0
- package/dist/runtime/app/pages/shift.vue +482 -0
- package/dist/runtime/app/pages/shift.vue.d.ts +3 -0
- package/dist/runtime/app/pages/shifts.d.vue.ts +3 -0
- package/dist/runtime/app/pages/shifts.vue +169 -0
- package/dist/runtime/app/pages/shifts.vue.d.ts +3 -0
- package/dist/runtime/app/pages/station.d.vue.ts +3 -0
- package/dist/runtime/app/pages/station.vue +104 -0
- package/dist/runtime/app/pages/station.vue.d.ts +3 -0
- package/dist/runtime/app/pages/swaps.d.vue.ts +3 -0
- package/dist/runtime/app/pages/swaps.vue +192 -0
- package/dist/runtime/app/pages/swaps.vue.d.ts +3 -0
- package/dist/runtime/app/tabs/Shifts.d.vue.ts +9 -0
- package/dist/runtime/app/tabs/Shifts.vue +487 -0
- package/dist/runtime/app/tabs/Shifts.vue.d.ts +9 -0
- package/dist/runtime/app/utils/admin-shifts.d.ts +42 -0
- package/dist/runtime/app/utils/admin-shifts.js +36 -0
- package/dist/runtime/dashboard.d.ts +8 -0
- package/dist/runtime/dashboard.js +30 -0
- package/dist/runtime/emails/shifts-broadcast.d.vue.ts +8 -0
- package/dist/runtime/emails/shifts-broadcast.vue +24 -0
- package/dist/runtime/emails/shifts-broadcast.vue.d.ts +8 -0
- package/dist/runtime/emails/shifts-reminder.d.vue.ts +12 -0
- package/dist/runtime/emails/shifts-reminder.vue +34 -0
- package/dist/runtime/emails/shifts-reminder.vue.d.ts +12 -0
- package/dist/runtime/emails/shifts-swap-accepted.d.vue.ts +11 -0
- package/dist/runtime/emails/shifts-swap-accepted.vue +32 -0
- package/dist/runtime/emails/shifts-swap-accepted.vue.d.ts +11 -0
- package/dist/runtime/emails/shifts-swap-completed.d.vue.ts +11 -0
- package/dist/runtime/emails/shifts-swap-completed.vue +32 -0
- package/dist/runtime/emails/shifts-swap-completed.vue.d.ts +11 -0
- package/dist/runtime/emails/shifts-swap-offered.d.vue.ts +11 -0
- package/dist/runtime/emails/shifts-swap-offered.vue +32 -0
- package/dist/runtime/emails/shifts-swap-offered.vue.d.ts +11 -0
- package/dist/runtime/emails/shifts-swap-pending.d.vue.ts +11 -0
- package/dist/runtime/emails/shifts-swap-pending.vue +32 -0
- package/dist/runtime/emails/shifts-swap-pending.vue.d.ts +11 -0
- package/dist/runtime/emails/shifts-swap-proposed.d.vue.ts +11 -0
- package/dist/runtime/emails/shifts-swap-proposed.vue +32 -0
- package/dist/runtime/emails/shifts-swap-proposed.vue.d.ts +11 -0
- package/dist/runtime/emails/shifts-swap-rejected.d.vue.ts +11 -0
- package/dist/runtime/emails/shifts-swap-rejected.vue +32 -0
- package/dist/runtime/emails/shifts-swap-rejected.vue.d.ts +11 -0
- package/dist/runtime/i18n/lang/da.json +626 -0
- package/dist/runtime/i18n/lang/en.json +626 -0
- package/dist/runtime/menus.d.ts +2 -0
- package/dist/runtime/menus.js +17 -0
- package/dist/runtime/notifications.d.ts +9 -0
- package/dist/runtime/notifications.js +36 -0
- package/dist/runtime/server/db/schema.postgresql.d.ts +2151 -0
- package/dist/runtime/server/db/schema.postgresql.js +228 -0
- package/dist/runtime/server/db/schema.sqlite.d.ts +2263 -0
- package/dist/runtime/server/db/schema.sqlite.js +228 -0
- package/dist/runtime/server/digest-email.d.ts +17 -0
- package/dist/runtime/server/digest-email.js +42 -0
- package/dist/runtime/server/plugins/station-key.d.ts +2 -0
- package/dist/runtime/server/plugins/station-key.js +5 -0
- package/dist/runtime/server/plugins/teams.d.ts +2 -0
- package/dist/runtime/server/plugins/teams.js +19 -0
- package/dist/runtime/server/policies.d.ts +2 -0
- package/dist/runtime/server/policies.js +41 -0
- package/dist/runtime/server/reminder-email.d.ts +67 -0
- package/dist/runtime/server/reminder-email.js +109 -0
- package/dist/runtime/server/routes/admin/assignment.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/assignment.delete.js +10 -0
- package/dist/runtime/server/routes/admin/assignments.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/assignments.post.js +11 -0
- package/dist/runtime/server/routes/admin/broadcasts.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/broadcasts.get.js +8 -0
- package/dist/runtime/server/routes/admin/broadcasts.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/broadcasts.post.js +9 -0
- package/dist/runtime/server/routes/admin/candidates.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/candidates.get.js +10 -0
- package/dist/runtime/server/routes/admin/operation-teams.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/operation-teams.get.js +9 -0
- package/dist/runtime/server/routes/admin/perk.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/perk.delete.js +10 -0
- package/dist/runtime/server/routes/admin/perk.patch.d.ts +2 -0
- package/dist/runtime/server/routes/admin/perk.patch.js +10 -0
- package/dist/runtime/server/routes/admin/perks.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/perks.get.js +9 -0
- package/dist/runtime/server/routes/admin/perks.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/perks.post.js +10 -0
- package/dist/runtime/server/routes/admin/role.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/role.delete.js +11 -0
- package/dist/runtime/server/routes/admin/role.patch.d.ts +2 -0
- package/dist/runtime/server/routes/admin/role.patch.js +11 -0
- package/dist/runtime/server/routes/admin/roles.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/roles.get.js +9 -0
- package/dist/runtime/server/routes/admin/roles.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/roles.post.js +10 -0
- package/dist/runtime/server/routes/admin/schedule-copy.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedule-copy.post.js +12 -0
- package/dist/runtime/server/routes/admin/schedule-publish.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedule-publish.post.js +9 -0
- package/dist/runtime/server/routes/admin/schedule.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedule.delete.js +10 -0
- package/dist/runtime/server/routes/admin/schedule.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedule.get.js +9 -0
- package/dist/runtime/server/routes/admin/schedule.patch.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedule.patch.js +10 -0
- package/dist/runtime/server/routes/admin/schedules.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedules.get.js +10 -0
- package/dist/runtime/server/routes/admin/schedules.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/schedules.post.js +9 -0
- package/dist/runtime/server/routes/admin/shift.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/shift.delete.js +10 -0
- package/dist/runtime/server/routes/admin/shift.patch.d.ts +2 -0
- package/dist/runtime/server/routes/admin/shift.patch.js +10 -0
- package/dist/runtime/server/routes/admin/shifts-bulk.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/shifts-bulk.post.js +10 -0
- package/dist/runtime/server/routes/admin/shifts.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/shifts.get.js +10 -0
- package/dist/runtime/server/routes/admin/station.delete.d.ts +2 -0
- package/dist/runtime/server/routes/admin/station.delete.js +11 -0
- package/dist/runtime/server/routes/admin/station.patch.d.ts +2 -0
- package/dist/runtime/server/routes/admin/station.patch.js +11 -0
- package/dist/runtime/server/routes/admin/stations.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/stations.get.js +9 -0
- package/dist/runtime/server/routes/admin/stations.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/stations.post.js +10 -0
- package/dist/runtime/server/routes/admin/swap-cancel.post.d.ts +2 -0
- package/dist/runtime/server/routes/admin/swap-cancel.post.js +10 -0
- package/dist/runtime/server/routes/admin/swaps.get.d.ts +2 -0
- package/dist/runtime/server/routes/admin/swaps.get.js +10 -0
- package/dist/runtime/server/routes/feed/feed.get.d.ts +2 -0
- package/dist/runtime/server/routes/feed/feed.get.js +9 -0
- package/dist/runtime/server/routes/lead/attended.post.d.ts +2 -0
- package/dist/runtime/server/routes/lead/attended.post.js +11 -0
- package/dist/runtime/server/routes/lead/broadcast.post.d.ts +2 -0
- package/dist/runtime/server/routes/lead/broadcast.post.js +12 -0
- package/dist/runtime/server/routes/lead/check-in.post.d.ts +2 -0
- package/dist/runtime/server/routes/lead/check-in.post.js +9 -0
- package/dist/runtime/server/routes/lead/exceptions.get.d.ts +2 -0
- package/dist/runtime/server/routes/lead/exceptions.get.js +8 -0
- package/dist/runtime/server/routes/lead/no-show.post.d.ts +2 -0
- package/dist/runtime/server/routes/lead/no-show.post.js +11 -0
- package/dist/runtime/server/routes/lead/now.get.d.ts +2 -0
- package/dist/runtime/server/routes/lead/now.get.js +9 -0
- package/dist/runtime/server/routes/lead/on-duty.get.d.ts +2 -0
- package/dist/runtime/server/routes/lead/on-duty.get.js +10 -0
- package/dist/runtime/server/routes/lead/stations.get.d.ts +2 -0
- package/dist/runtime/server/routes/lead/stations.get.js +8 -0
- package/dist/runtime/server/routes/lead/team-shifts.get.d.ts +2 -0
- package/dist/runtime/server/routes/lead/team-shifts.get.js +9 -0
- package/dist/runtime/server/routes/lead/team-swaps.get.d.ts +2 -0
- package/dist/runtime/server/routes/lead/team-swaps.get.js +9 -0
- package/dist/runtime/server/routes/me/check-in.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/check-in.post.js +11 -0
- package/dist/runtime/server/routes/me/earned-perk-claim.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/earned-perk-claim.post.js +10 -0
- package/dist/runtime/server/routes/me/earned-perks.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/earned-perks.get.js +9 -0
- package/dist/runtime/server/routes/me/feed-token.delete.d.ts +2 -0
- package/dist/runtime/server/routes/me/feed-token.delete.js +7 -0
- package/dist/runtime/server/routes/me/feed-token.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/feed-token.get.js +6 -0
- package/dist/runtime/server/routes/me/feed-token.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/feed-token.post.js +7 -0
- package/dist/runtime/server/routes/me/leads.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/leads.get.js +5 -0
- package/dist/runtime/server/routes/me/now.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/now.get.js +5 -0
- package/dist/runtime/server/routes/me/pass.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/pass.get.js +11 -0
- package/dist/runtime/server/routes/me/settle.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/settle.post.js +14 -0
- package/dist/runtime/server/routes/me/shift.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/shift.get.js +10 -0
- package/dist/runtime/server/routes/me/shifts.get.d.ts +2 -0
- package/dist/runtime/server/routes/me/shifts.get.js +6 -0
- package/dist/runtime/server/routes/me/swap.delete.d.ts +2 -0
- package/dist/runtime/server/routes/me/swap.delete.js +11 -0
- package/dist/runtime/server/routes/me/swap.post.d.ts +2 -0
- package/dist/runtime/server/routes/me/swap.post.js +11 -0
- package/dist/runtime/server/routes/stations/token.get.d.ts +2 -0
- package/dist/runtime/server/routes/stations/token.get.js +12 -0
- package/dist/runtime/server/routes/swaps/approve.post.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/approve.post.js +9 -0
- package/dist/runtime/server/routes/swaps/list.get.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/list.get.js +5 -0
- package/dist/runtime/server/routes/swaps/offer-accept.post.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/offer-accept.post.js +9 -0
- package/dist/runtime/server/routes/swaps/offer-reject.post.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/offer-reject.post.js +9 -0
- package/dist/runtime/server/routes/swaps/offer.delete.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/offer.delete.js +11 -0
- package/dist/runtime/server/routes/swaps/offer.post.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/offer.post.js +11 -0
- package/dist/runtime/server/routes/swaps/reject.post.d.ts +2 -0
- package/dist/runtime/server/routes/swaps/reject.post.js +9 -0
- package/dist/runtime/server/swap-email.d.ts +28 -0
- package/dist/runtime/server/swap-email.js +49 -0
- package/dist/runtime/server/tasks/close-shifts.d.ts +2 -0
- package/dist/runtime/server/tasks/close-shifts.js +9 -0
- package/dist/runtime/server/tasks/send-reminders.d.ts +2 -0
- package/dist/runtime/server/tasks/send-reminders.js +9 -0
- package/dist/runtime/server/utils/shifts-admin.d.ts +67 -0
- package/dist/runtime/server/utils/shifts-admin.js +312 -0
- package/dist/runtime/server/utils/shifts-assign.d.ts +89 -0
- package/dist/runtime/server/utils/shifts-assign.js +264 -0
- package/dist/runtime/server/utils/shifts-automation.d.ts +37 -0
- package/dist/runtime/server/utils/shifts-automation.js +171 -0
- package/dist/runtime/server/utils/shifts-broadcasts.d.ts +38 -0
- package/dist/runtime/server/utils/shifts-broadcasts.js +113 -0
- package/dist/runtime/server/utils/shifts-core.d.ts +78 -0
- package/dist/runtime/server/utils/shifts-core.js +142 -0
- package/dist/runtime/server/utils/shifts-dto.d.ts +32 -0
- package/dist/runtime/server/utils/shifts-dto.js +127 -0
- package/dist/runtime/server/utils/shifts-emails.d.ts +16 -0
- package/dist/runtime/server/utils/shifts-emails.js +44 -0
- package/dist/runtime/server/utils/shifts-exceptions.d.ts +7 -0
- package/dist/runtime/server/utils/shifts-exceptions.js +32 -0
- package/dist/runtime/server/utils/shifts-feed.d.ts +16 -0
- package/dist/runtime/server/utils/shifts-feed.js +73 -0
- package/dist/runtime/server/utils/shifts-notify.d.ts +40 -0
- package/dist/runtime/server/utils/shifts-notify.js +22 -0
- package/dist/runtime/server/utils/shifts-on-duty.d.ts +12 -0
- package/dist/runtime/server/utils/shifts-on-duty.js +37 -0
- package/dist/runtime/server/utils/shifts-perks.d.ts +46 -0
- package/dist/runtime/server/utils/shifts-perks.js +183 -0
- package/dist/runtime/server/utils/shifts-reminders.d.ts +30 -0
- package/dist/runtime/server/utils/shifts-reminders.js +102 -0
- package/dist/runtime/server/utils/shifts-schemas.d.ts +318 -0
- package/dist/runtime/server/utils/shifts-schemas.js +177 -0
- package/dist/runtime/server/utils/shifts-station-key.d.ts +7 -0
- package/dist/runtime/server/utils/shifts-station-key.js +22 -0
- package/dist/runtime/server/utils/shifts-stations.d.ts +28 -0
- package/dist/runtime/server/utils/shifts-stations.js +109 -0
- package/dist/runtime/server/utils/shifts-swaps.d.ts +114 -0
- package/dist/runtime/server/utils/shifts-swaps.js +559 -0
- package/dist/runtime/server/utils/shifts-views.d.ts +62 -0
- package/dist/runtime/server/utils/shifts-views.js +212 -0
- package/dist/runtime/utils/api.d.ts +108 -0
- package/dist/runtime/utils/api.js +111 -0
- package/dist/runtime/utils/checkin.d.ts +59 -0
- package/dist/runtime/utils/checkin.js +57 -0
- package/dist/runtime/utils/guards.d.ts +21 -0
- package/dist/runtime/utils/guards.js +36 -0
- package/dist/runtime/utils/ics.d.ts +32 -0
- package/dist/runtime/utils/ics.js +56 -0
- package/dist/runtime/utils/index.d.ts +16 -0
- package/dist/runtime/utils/index.js +15 -0
- package/dist/runtime/utils/links.d.ts +30 -0
- package/dist/runtime/utils/links.js +18 -0
- package/dist/runtime/utils/reminders.d.ts +27 -0
- package/dist/runtime/utils/reminders.js +28 -0
- package/dist/runtime/utils/settings.d.ts +28 -0
- package/dist/runtime/utils/settings.js +18 -0
- package/dist/runtime/utils/station-key.d.ts +9 -0
- package/dist/runtime/utils/station-key.js +12 -0
- package/dist/runtime/utils/status.d.ts +23 -0
- package/dist/runtime/utils/status.js +46 -0
- package/dist/runtime/utils/time.d.ts +22 -0
- package/dist/runtime/utils/time.js +14 -0
- package/dist/types.d.mts +5 -0
- package/package.json +131 -3
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { and, asc, eq, gt, gte, inArray, isNull, lt, ne } from "drizzle-orm";
|
|
3
|
+
import { apiError, conflict, notFound } from "@frigear-nu/module-kit/server";
|
|
4
|
+
import { newCheckInCode, newId } from "../../utils/index.js";
|
|
5
|
+
import { effectiveCapacity, shiftCapacityWarnings } from "../../utils/guards.js";
|
|
6
|
+
import { ACTIVE_ASSIGNMENT_STATUSES, canMoveAssignment } from "../../utils/status.js";
|
|
7
|
+
import { checkInRuleFor, checkLocation } from "../../utils/checkin.js";
|
|
8
|
+
import { addDays, dayKey, zonedTimeToUtc } from "@frigear-nu/module-kit/time";
|
|
9
|
+
import { toShiftAssignmentDto, toShiftDto } from "./shifts-dto.js";
|
|
10
|
+
import {
|
|
11
|
+
findShiftAssignmentEntry,
|
|
12
|
+
shiftsActiveAssignmentOf,
|
|
13
|
+
shiftsAssigneeDtos,
|
|
14
|
+
shiftsConfig,
|
|
15
|
+
shiftsEligibility,
|
|
16
|
+
shiftsFilledCount,
|
|
17
|
+
shiftsFire,
|
|
18
|
+
shiftsGuardWarningsFor,
|
|
19
|
+
shiftsRoleById,
|
|
20
|
+
shiftsRoleOfOr400
|
|
21
|
+
} from "./shifts-core.js";
|
|
22
|
+
import { shiftsCancelSwapsOf } from "./shifts-swaps.js";
|
|
23
|
+
import { shiftsEarnPerks, shiftsRevokeEarnedPerks } from "./shifts-perks.js";
|
|
24
|
+
import { findShiftStation, shiftsVerifyStationToken } from "./shifts-stations.js";
|
|
25
|
+
export function shiftsPassWindow(event, shift) {
|
|
26
|
+
const { checkInOpensMinutes } = shiftsConfig(event);
|
|
27
|
+
return { opensAt: new Date(shift.startsAt.getTime() - checkInOpensMinutes * 6e4), closesAt: shift.endsAt };
|
|
28
|
+
}
|
|
29
|
+
export function shiftsCheckInOpen(event, shift, now = /* @__PURE__ */ new Date()) {
|
|
30
|
+
const { opensAt, closesAt } = shiftsPassWindow(event, shift);
|
|
31
|
+
return now.getTime() >= opensAt.getTime() && now.getTime() <= closesAt.getTime();
|
|
32
|
+
}
|
|
33
|
+
export async function shiftsWriteAssignment(before, patch) {
|
|
34
|
+
const [row] = await db.update(schema.shiftAssignments).set(patch).where(and(
|
|
35
|
+
eq(schema.shiftAssignments.id, before.id),
|
|
36
|
+
eq(schema.shiftAssignments.status, before.status),
|
|
37
|
+
eq(schema.shiftAssignments.userId, before.userId)
|
|
38
|
+
)).returning();
|
|
39
|
+
return row;
|
|
40
|
+
}
|
|
41
|
+
async function shiftsPlaceOf(shiftId, assignmentId) {
|
|
42
|
+
const rows = await db.select({ id: schema.shiftAssignments.id }).from(schema.shiftAssignments).where(and(
|
|
43
|
+
eq(schema.shiftAssignments.shiftId, shiftId),
|
|
44
|
+
inArray(schema.shiftAssignments.status, [...ACTIVE_ASSIGNMENT_STATUSES])
|
|
45
|
+
)).orderBy(asc(schema.shiftAssignments.createdAt), asc(schema.shiftAssignments.id));
|
|
46
|
+
return rows.findIndex((row) => row.id === assignmentId);
|
|
47
|
+
}
|
|
48
|
+
async function shiftsAssignmentChanged(event, assignment, previous, auto) {
|
|
49
|
+
await shiftsFire("shifts:assignment:changed", { event, assignment: toShiftAssignmentDto(assignment), previous: previous ? toShiftAssignmentDto(previous) : null, ...auto ? { auto } : {} });
|
|
50
|
+
}
|
|
51
|
+
export async function shiftsAssign(event, entry, input, by, pii) {
|
|
52
|
+
const { shift, schedule } = entry;
|
|
53
|
+
const roleId = input.shiftRoleId ?? shift.shiftRoleId ?? null;
|
|
54
|
+
const role = roleId ? await shiftsRoleOfOr400(schedule.id, shift.teamId, roleId) : null;
|
|
55
|
+
const eligibility = await shiftsEligibility(event, input.userId, shift.teamId, role);
|
|
56
|
+
if (!eligibility.eligible) {
|
|
57
|
+
throw apiError(409, "not_eligible", eligibility.reason === "role" ? "This person's team role is below what the shift role needs." : "This person holds no role on the shift's team (approved crew, or a member added in Teams).", { reason: eligibility.reason });
|
|
58
|
+
}
|
|
59
|
+
if (await shiftsActiveAssignmentOf(shift.id, input.userId)) throw apiError(409, "already_assigned", "This person is on the shift already.");
|
|
60
|
+
const capacity = effectiveCapacity(shift, schedule);
|
|
61
|
+
const full = () => apiError(409, "shift_full", `The shift takes ${capacity} people.`, { capacity });
|
|
62
|
+
if (capacity !== null && !input.force && await shiftsFilledCount(shift.id) >= capacity) throw full();
|
|
63
|
+
const warnings = await shiftsGuardWarningsFor(event, input.userId, entry);
|
|
64
|
+
const [row] = await db.insert(schema.shiftAssignments).values({
|
|
65
|
+
id: newId("sha"),
|
|
66
|
+
shiftId: shift.id,
|
|
67
|
+
userId: input.userId,
|
|
68
|
+
shiftRoleId: roleId,
|
|
69
|
+
status: "assigned",
|
|
70
|
+
checkInCode: newCheckInCode(),
|
|
71
|
+
assignedBy: by
|
|
72
|
+
}).returning();
|
|
73
|
+
const assignment = row;
|
|
74
|
+
const mine = await db.select({ id: schema.shiftAssignments.id }).from(schema.shiftAssignments).where(and(
|
|
75
|
+
eq(schema.shiftAssignments.shiftId, shift.id),
|
|
76
|
+
eq(schema.shiftAssignments.userId, input.userId),
|
|
77
|
+
inArray(schema.shiftAssignments.status, [...ACTIVE_ASSIGNMENT_STATUSES])
|
|
78
|
+
)).orderBy(asc(schema.shiftAssignments.createdAt), asc(schema.shiftAssignments.id));
|
|
79
|
+
if (mine.length > 1 && mine[0].id !== assignment.id) {
|
|
80
|
+
await db.delete(schema.shiftAssignments).where(eq(schema.shiftAssignments.id, assignment.id));
|
|
81
|
+
throw apiError(409, "already_assigned", "This person is on the shift already.");
|
|
82
|
+
}
|
|
83
|
+
const filled = await shiftsFilledCount(shift.id);
|
|
84
|
+
if (capacity !== null && !input.force && filled > capacity && await shiftsPlaceOf(shift.id, assignment.id) >= capacity) {
|
|
85
|
+
await db.delete(schema.shiftAssignments).where(eq(schema.shiftAssignments.id, assignment.id));
|
|
86
|
+
throw full();
|
|
87
|
+
}
|
|
88
|
+
warnings.push(...shiftCapacityWarnings(filled, capacity, schedule.minPerShift));
|
|
89
|
+
await shiftsAssignmentChanged(event, assignment, null);
|
|
90
|
+
const [dto] = await shiftsAssigneeDtos([assignment], pii);
|
|
91
|
+
return { assignment: dto, warnings };
|
|
92
|
+
}
|
|
93
|
+
export async function shiftsCancelAssignment(event, entry) {
|
|
94
|
+
const { assignment } = entry;
|
|
95
|
+
if (assignment.status === "cancelled") return assignment;
|
|
96
|
+
if (!canMoveAssignment(assignment.status, "cancelled")) {
|
|
97
|
+
throw apiError(409, "invalid_transition", `An ${assignment.status} assignment cannot be cancelled.`);
|
|
98
|
+
}
|
|
99
|
+
const written = await shiftsWriteAssignment(assignment, { status: "cancelled" });
|
|
100
|
+
if (!written) {
|
|
101
|
+
const current = await findShiftAssignmentEntry(assignment.id);
|
|
102
|
+
if (current?.assignment.status === "cancelled") return current.assignment;
|
|
103
|
+
throw conflict("The assignment changed meanwhile. Try again.");
|
|
104
|
+
}
|
|
105
|
+
await shiftsCancelSwapsOf(event, written.id);
|
|
106
|
+
await shiftsAssignmentChanged(event, written, assignment);
|
|
107
|
+
return written;
|
|
108
|
+
}
|
|
109
|
+
export async function shiftsMarkAttendance(event, entry, to, by, options = {}) {
|
|
110
|
+
const { assignment } = entry;
|
|
111
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
112
|
+
const from = assignment.status;
|
|
113
|
+
if (from === to) return assignment;
|
|
114
|
+
if (!canMoveAssignment(from, to)) throw apiError(409, "invalid_transition", `An ${from} assignment cannot be marked ${to === "no_show" ? "a no-show" : to}.`);
|
|
115
|
+
const { opensAt } = shiftsPassWindow(event, entry.shift);
|
|
116
|
+
if (now.getTime() < opensAt.getTime()) {
|
|
117
|
+
throw apiError(409, "outside_window", "Attendance can be marked once check-in for the shift opens.", { opensAt: opensAt.toISOString() });
|
|
118
|
+
}
|
|
119
|
+
const checksIn = to === "attended" && !assignment.checkedInAt;
|
|
120
|
+
const patch = { status: to };
|
|
121
|
+
if (checksIn) Object.assign(patch, { checkedInAt: now, checkedInBy: by, checkInMethod: "lead" });
|
|
122
|
+
const written = await shiftsWriteAssignment(assignment, patch);
|
|
123
|
+
if (!written) throw conflict("The assignment changed meanwhile. Try again.");
|
|
124
|
+
if (from === "assigned") await shiftsCancelSwapsOf(event, written.id);
|
|
125
|
+
if (to === "no_show" && from === "attended") await shiftsRevokeEarnedPerks(event, written.id);
|
|
126
|
+
if (to === "attended") await shiftsEarnPerks(event, [{ assignment: written, shift: entry.shift, schedule: entry.schedule }], now);
|
|
127
|
+
await shiftsFire("shifts:attendance:marked", { event, assignment: toShiftAssignmentDto(written), by, ...options.auto ? { auto: true } : {}, ...checksIn ? { method: "lead" } : {} });
|
|
128
|
+
await shiftsAssignmentChanged(event, written, assignment, options.auto);
|
|
129
|
+
return written;
|
|
130
|
+
}
|
|
131
|
+
async function shiftsClaimCheckIn(event, assignment, by, method, now) {
|
|
132
|
+
const [claimed] = await db.update(schema.shiftAssignments).set({ status: "attended", checkedInAt: now, checkedInBy: by, checkInMethod: method }).where(and(
|
|
133
|
+
eq(schema.shiftAssignments.id, assignment.id),
|
|
134
|
+
eq(schema.shiftAssignments.userId, assignment.userId),
|
|
135
|
+
isNull(schema.shiftAssignments.checkedInAt),
|
|
136
|
+
inArray(schema.shiftAssignments.status, ["assigned", "no_show"])
|
|
137
|
+
)).returning();
|
|
138
|
+
if (!claimed) return void 0;
|
|
139
|
+
if (assignment.status === "assigned") await shiftsCancelSwapsOf(event, claimed.id);
|
|
140
|
+
await shiftsFire("shifts:attendance:marked", { event, assignment: toShiftAssignmentDto(claimed), by, method });
|
|
141
|
+
await shiftsAssignmentChanged(event, claimed, assignment);
|
|
142
|
+
return claimed;
|
|
143
|
+
}
|
|
144
|
+
export async function shiftsDailyCascade(event, first, by, now) {
|
|
145
|
+
const { timeZone } = shiftsConfig(event);
|
|
146
|
+
const day = dayKey(now, timeZone);
|
|
147
|
+
const dayStart = zonedTimeToUtc(day, "00:00", timeZone);
|
|
148
|
+
const dayEnd = zonedTimeToUtc(addDays(day, 1), "00:00", timeZone);
|
|
149
|
+
const [earlier] = await db.select({ id: schema.shiftAssignments.id }).from(schema.shiftAssignments).where(and(
|
|
150
|
+
eq(schema.shiftAssignments.userId, first.userId),
|
|
151
|
+
ne(schema.shiftAssignments.id, first.id),
|
|
152
|
+
gte(schema.shiftAssignments.checkedInAt, dayStart),
|
|
153
|
+
lt(schema.shiftAssignments.checkedInAt, now)
|
|
154
|
+
)).limit(1);
|
|
155
|
+
if (earlier) return [];
|
|
156
|
+
const rows = await db.select({ assignment: schema.shiftAssignments, shift: schema.shifts, schedule: schema.shiftSchedules }).from(schema.shiftAssignments).innerJoin(schema.shifts, eq(schema.shifts.id, schema.shiftAssignments.shiftId)).innerJoin(schema.shiftSchedules, eq(schema.shiftSchedules.id, schema.shifts.scheduleId)).where(and(
|
|
157
|
+
eq(schema.shiftAssignments.userId, first.userId),
|
|
158
|
+
ne(schema.shiftAssignments.id, first.id),
|
|
159
|
+
eq(schema.shiftAssignments.status, "assigned"),
|
|
160
|
+
isNull(schema.shiftAssignments.checkedInAt),
|
|
161
|
+
eq(schema.shiftSchedules.status, "published"),
|
|
162
|
+
gte(schema.shifts.startsAt, dayStart),
|
|
163
|
+
lt(schema.shifts.startsAt, dayEnd)
|
|
164
|
+
)).orderBy(asc(schema.shifts.startsAt)).limit(24);
|
|
165
|
+
const done = [];
|
|
166
|
+
for (const { assignment, shift, schedule } of rows) {
|
|
167
|
+
if (!checkInRuleFor(schedule.checkIn, shift.teamId).modes.includes("daily")) continue;
|
|
168
|
+
if (!shiftsCheckInOpen(event, shift, now)) continue;
|
|
169
|
+
if (!await shiftsStillEligible(event, assignment, shift.teamId)) continue;
|
|
170
|
+
if (await shiftsClaimCheckIn(event, assignment, by, "daily", now)) done.push(assignment.id);
|
|
171
|
+
}
|
|
172
|
+
return done;
|
|
173
|
+
}
|
|
174
|
+
export async function shiftsAssignmentByCode(code) {
|
|
175
|
+
const [found] = await db.select({ id: schema.shiftAssignments.id }).from(schema.shiftAssignments).where(eq(schema.shiftAssignments.checkInCode, code)).limit(1);
|
|
176
|
+
return found ? findShiftAssignmentEntry(found.id) : void 0;
|
|
177
|
+
}
|
|
178
|
+
export async function shiftsCheckIn(event, teamId, code, by, pii) {
|
|
179
|
+
const entry = await shiftsAssignmentByCode(code);
|
|
180
|
+
if (!entry || entry.shift.teamId !== teamId) throw notFound("Unknown check-in code.");
|
|
181
|
+
const { assignment, shift, schedule } = entry;
|
|
182
|
+
if (assignment.status === "cancelled") throw apiError(409, "assignment_cancelled", "This assignment was cancelled.");
|
|
183
|
+
if (!await shiftsStillEligible(event, assignment, shift.teamId)) {
|
|
184
|
+
await shiftsCancelFutureAssignments(event, assignment.userId, shift.teamId, (row) => shiftsStillEligible(event, row, shift.teamId));
|
|
185
|
+
throw apiError(409, "not_eligible", "This person no longer holds a role on the team.");
|
|
186
|
+
}
|
|
187
|
+
const respond = async (row, alreadyCheckedIn, alsoCheckedIn = []) => {
|
|
188
|
+
const [dto] = await shiftsAssigneeDtos([row], pii);
|
|
189
|
+
return { ok: true, alreadyCheckedIn, checkedInAt: (row.checkedInAt ?? /* @__PURE__ */ new Date()).toISOString(), assignment: dto, shift: toShiftDto(shift, schedule), alsoCheckedIn };
|
|
190
|
+
};
|
|
191
|
+
if (assignment.status === "attended" && assignment.checkedInAt) return respond(assignment, true);
|
|
192
|
+
if (!shiftsCheckInOpen(event, shift)) {
|
|
193
|
+
const { opensAt, closesAt } = shiftsPassWindow(event, shift);
|
|
194
|
+
throw apiError(409, "outside_window", "Check-in for this shift is not open now.", { opensAt: opensAt.toISOString(), closesAt: closesAt.toISOString() });
|
|
195
|
+
}
|
|
196
|
+
const now = /* @__PURE__ */ new Date();
|
|
197
|
+
const claimed = await shiftsClaimCheckIn(event, assignment, by, "lead", now);
|
|
198
|
+
if (!claimed) {
|
|
199
|
+
const current = await findShiftAssignmentEntry(assignment.id);
|
|
200
|
+
if (current?.assignment.status === "attended") return respond(current.assignment, true);
|
|
201
|
+
throw conflict("The assignment changed meanwhile. Try again.");
|
|
202
|
+
}
|
|
203
|
+
return respond(claimed, false, await shiftsDailyCascade(event, claimed, by, now));
|
|
204
|
+
}
|
|
205
|
+
export async function shiftsSelfCheckIn(event, entry, input, now = /* @__PURE__ */ new Date()) {
|
|
206
|
+
const { assignment, shift, schedule } = entry;
|
|
207
|
+
const rule = checkInRuleFor(schedule.checkIn, shift.teamId);
|
|
208
|
+
if (!rule.modes.includes(input.mode)) throw apiError(409, "mode_disabled", `Checking in by ${input.mode} is not on for this shift.`, { modes: rule.modes });
|
|
209
|
+
if (input.mode === "station") {
|
|
210
|
+
const stationId = await shiftsVerifyStationToken(event, input.token, now.getTime());
|
|
211
|
+
const station = await findShiftStation(stationId);
|
|
212
|
+
if (!station || station.scheduleId !== schedule.id || station.teamId !== shift.teamId) throw apiError(409, "wrong_station", "This station is not one of your team's on this schedule.");
|
|
213
|
+
} else {
|
|
214
|
+
if (!rule.location) throw apiError(409, "no_location", "No check-in place is set for this shift.");
|
|
215
|
+
const check = checkLocation(rule.location, { lat: input.latitude, lng: input.longitude }, input.accuracy);
|
|
216
|
+
if (!check.ok) {
|
|
217
|
+
throw check.reason === "inaccurate" ? apiError(409, "inaccurate_position", "Your position is not accurate enough. Try again outside, or ask a lead.", { radius: check.radius }) : apiError(409, "outside_location", "You are not at the check-in place.", { distance: check.distance, radius: check.radius });
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (assignment.status === "cancelled") throw apiError(409, "assignment_cancelled", "This assignment was cancelled.");
|
|
221
|
+
const respond = (row, alreadyCheckedIn, alsoCheckedIn = []) => ({
|
|
222
|
+
ok: true,
|
|
223
|
+
alreadyCheckedIn,
|
|
224
|
+
checkedInAt: (row.checkedInAt ?? now).toISOString(),
|
|
225
|
+
method: row.checkInMethod ?? input.mode,
|
|
226
|
+
assignment: toShiftAssignmentDto(row),
|
|
227
|
+
alsoCheckedIn
|
|
228
|
+
});
|
|
229
|
+
if (assignment.status === "attended" && assignment.checkedInAt) return respond(assignment, true);
|
|
230
|
+
if (!await shiftsStillEligible(event, assignment, shift.teamId)) throw apiError(409, "not_eligible", "You no longer hold a role on the team.");
|
|
231
|
+
if (!shiftsCheckInOpen(event, shift, now)) {
|
|
232
|
+
const { opensAt, closesAt } = shiftsPassWindow(event, shift);
|
|
233
|
+
throw apiError(409, "outside_window", "Check-in for this shift is not open now.", { opensAt: opensAt.toISOString(), closesAt: closesAt.toISOString() });
|
|
234
|
+
}
|
|
235
|
+
const claimed = await shiftsClaimCheckIn(event, assignment, assignment.userId, input.mode, now);
|
|
236
|
+
if (!claimed) {
|
|
237
|
+
const current = await findShiftAssignmentEntry(assignment.id);
|
|
238
|
+
if (current?.assignment.status === "attended" && current.assignment.userId === assignment.userId) return respond(current.assignment, true);
|
|
239
|
+
throw conflict("The assignment changed meanwhile. Try again.");
|
|
240
|
+
}
|
|
241
|
+
return respond(claimed, false, await shiftsDailyCascade(event, claimed, assignment.userId, now));
|
|
242
|
+
}
|
|
243
|
+
export async function shiftsCancelFutureAssignments(event, userId, teamId, keep) {
|
|
244
|
+
const rows = await db.select({ assignment: schema.shiftAssignments }).from(schema.shiftAssignments).innerJoin(schema.shifts, eq(schema.shifts.id, schema.shiftAssignments.shiftId)).where(and(
|
|
245
|
+
eq(schema.shiftAssignments.userId, userId),
|
|
246
|
+
eq(schema.shifts.teamId, teamId),
|
|
247
|
+
eq(schema.shiftAssignments.status, "assigned"),
|
|
248
|
+
gt(schema.shifts.startsAt, /* @__PURE__ */ new Date())
|
|
249
|
+
));
|
|
250
|
+
let cancelled = 0;
|
|
251
|
+
for (const { assignment } of rows) {
|
|
252
|
+
if (keep && await keep(assignment)) continue;
|
|
253
|
+
const entry = await findShiftAssignmentEntry(assignment.id);
|
|
254
|
+
if (!entry || entry.assignment.status !== "assigned") continue;
|
|
255
|
+
await shiftsCancelAssignment(event, entry).then(() => cancelled++).catch((error) => {
|
|
256
|
+
console.error(`[shifts] assignment ${assignment.id} could not be cancelled`, error);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
return cancelled;
|
|
260
|
+
}
|
|
261
|
+
export async function shiftsStillEligible(event, assignment, teamId) {
|
|
262
|
+
const role = await shiftsRoleById(assignment.shiftRoleId);
|
|
263
|
+
return (await shiftsEligibility(event, assignment.userId, teamId, role)).eligible;
|
|
264
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { H3Event } from 'h3';
|
|
2
|
+
export type ShiftsCloseRunDto = {
|
|
3
|
+
/** Ended shifts this run closed. */
|
|
4
|
+
closed: number;
|
|
5
|
+
/** Earned perks made (new, or restored). */
|
|
6
|
+
earned: number;
|
|
7
|
+
/** Assignments marked `no_show` by `autoNoShow`. */
|
|
8
|
+
noShows: number;
|
|
9
|
+
/** Digest messages that went out (one per lead). */
|
|
10
|
+
digests: number;
|
|
11
|
+
/** Exceptions claimed for a digest this run. */
|
|
12
|
+
exceptions: number;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* The `shifts:close-shifts` task (every five minutes by default). Three steps, each idempotent on both dialects and
|
|
16
|
+
* bounded by `automation.batchSize` (the next run takes the rest); every lookup by a list of ids runs in chunks below
|
|
17
|
+
* D1's 100 bound parameters:
|
|
18
|
+
* 1. **Shift end.** Ended shifts of published schedules not closed yet: their `attended` assignments earn their
|
|
19
|
+
* perks (the unique `(perkId, assignmentId)` key makes a second one a no-op), then the shift is marked
|
|
20
|
+
* `closedAt`. Nobody else changes: there is no `completed` status.
|
|
21
|
+
* 2. **Auto no-show.** On schedules with `autoNoShow`, assignments still `assigned` without a check-in
|
|
22
|
+
* `autoNoShowMinutes` after the start (of shifts that started in the last 24 hours) become `no_show`, as the system
|
|
23
|
+
* (`by: null`, hooks with `auto: true` and `event: undefined`).
|
|
24
|
+
* 3. **Digest.** The new exceptions (no-shows, people still not checked in `autoNoShowMinutes` after the start on
|
|
25
|
+
* schedules without auto no-show, and no-shows whose earned perk was claimed) are claimed in `shift_digest_items` (unique
|
|
26
|
+
* per kind and assignment: each is sent once) and go out as one message per lead: to the team's leads on duty, else
|
|
27
|
+
* its leads, else the coordinators of the operation (the explicit holders of the top role of a ladder on one of its
|
|
28
|
+
* teams), through `shiftsNotify` on the `shifts.digest` topic. Fires `shifts:digest:sent` per message.
|
|
29
|
+
*/
|
|
30
|
+
export declare function shiftsCloseShifts(now?: Date, event?: H3Event, override?: {
|
|
31
|
+
batchSize?: number;
|
|
32
|
+
}): Promise<ShiftsCloseRunDto>;
|
|
33
|
+
/**
|
|
34
|
+
* Who gets a team's digest: its leads on shift now; else its leads (explicit members at or above the ladder's
|
|
35
|
+
* `leadFrom`); else the coordinators of the operation (explicit holders of the top role of a ladder on one of its teams).
|
|
36
|
+
*/
|
|
37
|
+
export declare function shiftsDigestRecipients(event: H3Event | undefined, teamId: string, operationId: string, now: Date): Promise<number[]>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { and, asc, eq, exists, gte, inArray, isNotNull, isNull, lte, notExists, sql } from "drizzle-orm";
|
|
3
|
+
import { ladderKeys, roleAtLeast } from "@frigear-nu/teams/utils";
|
|
4
|
+
import { newId, translate } from "../../utils/index.js";
|
|
5
|
+
import { normalizeAutomationBatch } from "../../utils/checkin.js";
|
|
6
|
+
import { buildShiftDigestEmail } from "../digest-email.js";
|
|
7
|
+
import { formatShiftWhen } from "../reminder-email.js";
|
|
8
|
+
import { shiftsConfig, shiftsFire, shiftsLocalesOfMany, shiftsTeamsById, shiftsUsersById } from "./shifts-core.js";
|
|
9
|
+
import { shiftsMarkAttendance } from "./shifts-assign.js";
|
|
10
|
+
import { shiftsEarnPerks } from "./shifts-perks.js";
|
|
11
|
+
import { shiftsLeadsOnDuty } from "./shifts-views.js";
|
|
12
|
+
import { shiftsNotify } from "./shifts-notify.js";
|
|
13
|
+
import { SHIFTS_TOPICS } from "../../notifications.js";
|
|
14
|
+
import { chunkParams } from "@frigear-nu/module-kit/server";
|
|
15
|
+
const HOUR = 36e5;
|
|
16
|
+
let shiftsWarnedNoOrigin = false;
|
|
17
|
+
export async function shiftsCloseShifts(now = /* @__PURE__ */ new Date(), event, override = {}) {
|
|
18
|
+
const config = shiftsConfig(event);
|
|
19
|
+
const batchSize = override.batchSize ? normalizeAutomationBatch(override.batchSize) : config.automation.batchSize;
|
|
20
|
+
const result = { closed: 0, earned: 0, noShows: 0, digests: 0, exceptions: 0 };
|
|
21
|
+
const ended = await db.select({ shift: schema.shifts, operationId: schema.shiftSchedules.operationId }).from(schema.shifts).innerJoin(schema.shiftSchedules, eq(schema.shiftSchedules.id, schema.shifts.scheduleId)).where(and(lte(schema.shifts.endsAt, now), isNull(schema.shifts.closedAt), eq(schema.shiftSchedules.status, "published"))).orderBy(asc(schema.shifts.endsAt), asc(schema.shifts.id)).limit(batchSize);
|
|
22
|
+
for (const part of chunkParams(ended)) {
|
|
23
|
+
const byShift = new Map(part.map((row) => [row.shift.id, row]));
|
|
24
|
+
const attended = await db.select().from(schema.shiftAssignments).where(and(inArray(schema.shiftAssignments.shiftId, [...byShift.keys()]), eq(schema.shiftAssignments.status, "attended")));
|
|
25
|
+
try {
|
|
26
|
+
result.earned += await shiftsEarnPerks(event, attended.map((assignment) => ({
|
|
27
|
+
assignment,
|
|
28
|
+
shift: byShift.get(assignment.shiftId).shift,
|
|
29
|
+
schedule: { operationId: byShift.get(assignment.shiftId).operationId }
|
|
30
|
+
})), now);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
console.error("[shifts] the perks of ended shifts could not be given out", error);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const closed = await db.update(schema.shifts).set({ closedAt: now }).where(and(inArray(schema.shifts.id, [...byShift.keys()]), isNull(schema.shifts.closedAt))).returning({ id: schema.shifts.id });
|
|
36
|
+
result.closed += closed.length;
|
|
37
|
+
}
|
|
38
|
+
const autoSchedules = await db.select().from(schema.shiftSchedules).where(and(eq(schema.shiftSchedules.autoNoShow, true), eq(schema.shiftSchedules.status, "published"))).orderBy(asc(schema.shiftSchedules.id)).limit(100);
|
|
39
|
+
let left = batchSize;
|
|
40
|
+
for (const schedule of autoSchedules) {
|
|
41
|
+
if (left <= 0) break;
|
|
42
|
+
const cutoff = new Date(now.getTime() - schedule.autoNoShowMinutes * 6e4);
|
|
43
|
+
const rows = await db.select({ assignment: schema.shiftAssignments, shift: schema.shifts }).from(schema.shiftAssignments).innerJoin(schema.shifts, eq(schema.shifts.id, schema.shiftAssignments.shiftId)).where(and(
|
|
44
|
+
eq(schema.shifts.scheduleId, schedule.id),
|
|
45
|
+
eq(schema.shiftAssignments.status, "assigned"),
|
|
46
|
+
isNull(schema.shiftAssignments.checkedInAt),
|
|
47
|
+
lte(schema.shifts.startsAt, cutoff),
|
|
48
|
+
gte(schema.shifts.startsAt, new Date(now.getTime() - 24 * HOUR))
|
|
49
|
+
)).orderBy(asc(schema.shifts.startsAt), asc(schema.shiftAssignments.id)).limit(left);
|
|
50
|
+
left -= rows.length;
|
|
51
|
+
for (const { assignment, shift } of rows) {
|
|
52
|
+
try {
|
|
53
|
+
await shiftsMarkAttendance(void 0, { assignment, shift, schedule }, "no_show", null, { auto: true, now });
|
|
54
|
+
result.noShows++;
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.warn(`[shifts] assignment ${assignment.id} was not marked a no-show`, error);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const claimedBefore = (kind) => notExists(db.select({ one: sql`1` }).from(schema.shiftDigestItems).where(and(
|
|
61
|
+
eq(schema.shiftDigestItems.assignmentId, schema.shiftAssignments.id),
|
|
62
|
+
eq(schema.shiftDigestItems.kind, kind)
|
|
63
|
+
)));
|
|
64
|
+
const recent = gte(schema.shifts.startsAt, new Date(now.getTime() - 48 * HOUR));
|
|
65
|
+
const select = () => db.select({ assignment: schema.shiftAssignments, shift: schema.shifts, operationId: schema.shiftSchedules.operationId, autoNoShow: schema.shiftSchedules.autoNoShow, autoNoShowMinutes: schema.shiftSchedules.autoNoShowMinutes }).from(schema.shiftAssignments).innerJoin(schema.shifts, eq(schema.shifts.id, schema.shiftAssignments.shiftId)).innerJoin(schema.shiftSchedules, eq(schema.shiftSchedules.id, schema.shifts.scheduleId));
|
|
66
|
+
const candidates = [];
|
|
67
|
+
const noShows = await select().where(and(eq(schema.shiftSchedules.status, "published"), eq(schema.shiftAssignments.status, "no_show"), recent, claimedBefore("no_show"))).orderBy(asc(schema.shifts.startsAt)).limit(batchSize);
|
|
68
|
+
candidates.push(...noShows.map((row) => ({ ...row, kind: "no_show" })));
|
|
69
|
+
const claimedNoShows = await select().where(and(
|
|
70
|
+
eq(schema.shiftSchedules.status, "published"),
|
|
71
|
+
eq(schema.shiftAssignments.status, "no_show"),
|
|
72
|
+
exists(db.select({ one: sql`1` }).from(schema.shiftEarnedPerks).where(and(eq(schema.shiftEarnedPerks.assignmentId, schema.shiftAssignments.id), isNotNull(schema.shiftEarnedPerks.claimedAt)))),
|
|
73
|
+
claimedBefore("claimed_no_show")
|
|
74
|
+
)).orderBy(asc(schema.shifts.startsAt)).limit(batchSize);
|
|
75
|
+
candidates.push(...claimedNoShows.map((row) => ({ ...row, kind: "claimed_no_show" })));
|
|
76
|
+
const missing = await select().where(and(
|
|
77
|
+
eq(schema.shiftSchedules.status, "published"),
|
|
78
|
+
eq(schema.shiftSchedules.autoNoShow, false),
|
|
79
|
+
eq(schema.shiftAssignments.status, "assigned"),
|
|
80
|
+
isNull(schema.shiftAssignments.checkedInAt),
|
|
81
|
+
lte(schema.shifts.startsAt, now),
|
|
82
|
+
gte(schema.shifts.startsAt, new Date(now.getTime() - 24 * HOUR)),
|
|
83
|
+
claimedBefore("not_checked_in")
|
|
84
|
+
)).orderBy(asc(schema.shifts.startsAt)).limit(batchSize);
|
|
85
|
+
candidates.push(...missing.filter((row) => row.shift.startsAt.getTime() + row.autoNoShowMinutes * 6e4 <= now.getTime()).map((row) => ({ ...row, kind: "not_checked_in" })));
|
|
86
|
+
const claimed = [];
|
|
87
|
+
for (const candidate of candidates.slice(0, batchSize)) {
|
|
88
|
+
const [row] = await db.insert(schema.shiftDigestItems).values({
|
|
89
|
+
id: newId("sdi"),
|
|
90
|
+
kind: candidate.kind,
|
|
91
|
+
assignmentId: candidate.assignment.id,
|
|
92
|
+
teamId: candidate.shift.teamId,
|
|
93
|
+
sentAt: now
|
|
94
|
+
}).onConflictDoNothing().returning({ id: schema.shiftDigestItems.id });
|
|
95
|
+
if (row) claimed.push(candidate);
|
|
96
|
+
}
|
|
97
|
+
result.exceptions = claimed.length;
|
|
98
|
+
if (!claimed.length) return result;
|
|
99
|
+
const byTeam = /* @__PURE__ */ new Map();
|
|
100
|
+
for (const item of claimed) byTeam.set(item.shift.teamId, [...byTeam.get(item.shift.teamId) ?? [], item]);
|
|
101
|
+
const byRecipient = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const [teamId, items] of byTeam) {
|
|
103
|
+
let recipients = [];
|
|
104
|
+
try {
|
|
105
|
+
recipients = await shiftsDigestRecipients(event, teamId, items[0].operationId, now);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error(`[shifts] the digest recipients of team ${teamId} could not be found`, error);
|
|
108
|
+
}
|
|
109
|
+
for (const userId of recipients) byRecipient.set(userId, [...byRecipient.get(userId) ?? [], ...items]);
|
|
110
|
+
}
|
|
111
|
+
if (!byRecipient.size) return result;
|
|
112
|
+
const [users, teams] = await Promise.all([
|
|
113
|
+
shiftsUsersById([...byRecipient.keys(), ...claimed.map((item) => item.assignment.userId)]),
|
|
114
|
+
shiftsTeamsById([...byTeam.keys()])
|
|
115
|
+
]);
|
|
116
|
+
const locales = await shiftsLocalesOfMany([...byRecipient].map(([userId, items]) => ({ userId, teamId: items[0].shift.teamId })));
|
|
117
|
+
const origin = configuredAuthSiteOrigin(event);
|
|
118
|
+
if (!origin && !shiftsWarnedNoOrigin) {
|
|
119
|
+
shiftsWarnedNoOrigin = true;
|
|
120
|
+
console.warn("[shifts] no site origin is configured: digests go out without a link");
|
|
121
|
+
}
|
|
122
|
+
const leadPath = useRuntimeConfig(event).public.shifts?.pages?.lead;
|
|
123
|
+
for (const [userId, items] of byRecipient) {
|
|
124
|
+
try {
|
|
125
|
+
const recipient = users.get(userId);
|
|
126
|
+
const locale = locales.get(`${userId}:${items[0].shift.teamId}`) ?? "en";
|
|
127
|
+
const lines = items.map((item) => ({
|
|
128
|
+
kind: item.kind,
|
|
129
|
+
name: users.get(item.assignment.userId)?.name ?? `#${item.assignment.userId}`,
|
|
130
|
+
team: translate(teams.get(item.shift.teamId)?.name ?? item.shift.teamId, locale, "en"),
|
|
131
|
+
when: formatShiftWhen(item.shift.startsAt, locale, config.timeZone)
|
|
132
|
+
}));
|
|
133
|
+
const url = leadPath && origin ? `${origin}${leadPath.replace(":teamId", encodeURIComponent(items[0].shift.teamId))}` : void 0;
|
|
134
|
+
const email = buildShiftDigestEmail({ email: recipient?.email ?? null, name: recipient?.name ?? "", lines, url, locale });
|
|
135
|
+
const { channels } = await shiftsNotify(void 0, userId, {
|
|
136
|
+
topic: SHIFTS_TOPICS.digest,
|
|
137
|
+
email,
|
|
138
|
+
push: email ? { title: email.subject, body: lines.length === 1 ? `${lines[0].name}: ${lines[0].team} ${lines[0].when}` : email.subject, ...url ? { url } : {} } : void 0,
|
|
139
|
+
label: `the digest of user ${userId}`
|
|
140
|
+
});
|
|
141
|
+
if (!channels.length) continue;
|
|
142
|
+
result.digests++;
|
|
143
|
+
await shiftsFire("shifts:digest:sent", { event: void 0, userId, items: items.map((item) => ({ kind: item.kind, assignmentId: item.assignment.id, teamId: item.shift.teamId })), channels });
|
|
144
|
+
} catch (error) {
|
|
145
|
+
console.error(`[shifts] the digest of user ${userId} could not be handled`, error);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
export async function shiftsDigestRecipients(event, teamId, operationId, now) {
|
|
151
|
+
const onDuty = await shiftsLeadsOnDuty(event, teamId, now, new Date(now.getTime() + 1));
|
|
152
|
+
if (onDuty.length) return onDuty.map((person) => person.userId);
|
|
153
|
+
const ladders = await loadTeamLadders(event);
|
|
154
|
+
const members = await db.select({ userId: schema.teamMembers.userId, role: schema.teamMembers.role, kind: schema.teams.kind }).from(schema.teamMembers).innerJoin(schema.teams, eq(schema.teams.id, schema.teamMembers.teamId)).where(eq(schema.teamMembers.teamId, teamId)).limit(1e3);
|
|
155
|
+
const leads = [];
|
|
156
|
+
for (const member of members) {
|
|
157
|
+
const ladder = ladders[member.kind];
|
|
158
|
+
if (!ladder?.leadFrom || !roleAtLeast(ladderKeys(ladder), member.role, ladder.leadFrom)) continue;
|
|
159
|
+
if (await isTeamLead(event, member.userId, teamId)) leads.push(member.userId);
|
|
160
|
+
if (leads.length >= 20) break;
|
|
161
|
+
}
|
|
162
|
+
if (leads.length) return leads;
|
|
163
|
+
const operationMembers = await db.select({ userId: schema.teamMembers.userId, role: schema.teamMembers.role, kind: schema.teams.kind, teamId: schema.teams.id }).from(schema.teamMembers).innerJoin(schema.teams, eq(schema.teams.id, schema.teamMembers.teamId)).where(and(eq(schema.teams.ownerType, "operation"), eq(schema.teams.ownerId, operationId))).limit(5e3);
|
|
164
|
+
const coordinators = /* @__PURE__ */ new Set();
|
|
165
|
+
for (const member of operationMembers) {
|
|
166
|
+
const top = ladders[member.kind]?.roles.at(-1)?.key;
|
|
167
|
+
if (top && member.role === top && await isTeamLead(event, member.userId, member.teamId)) coordinators.add(member.userId);
|
|
168
|
+
if (coordinators.size >= 20) break;
|
|
169
|
+
}
|
|
170
|
+
return [...coordinators];
|
|
171
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { H3Event } from 'h3';
|
|
2
|
+
import type { z } from 'zod';
|
|
3
|
+
import type { ShiftBroadcastDto, ShiftBroadcastResultDto } from '../../../types.js';
|
|
4
|
+
import type { shiftsBroadcastInput } from './shifts-schemas.js';
|
|
5
|
+
type BroadcastInput = z.output<typeof shiftsBroadcastInput>;
|
|
6
|
+
/** The most people one broadcast reaches: a bigger audience is a 400 `audience_too_large` (split it by team). */
|
|
7
|
+
export declare const SHIFTS_BROADCAST_CAP = 500;
|
|
8
|
+
/** A person a broadcast reaches, with the team they were found through (their locale comes from it). */
|
|
9
|
+
export type ShiftsBroadcastRecipient = {
|
|
10
|
+
userId: number;
|
|
11
|
+
teamId: string;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Who a broadcast goes to. With `shiftId`: the people holding a place on that shift (it must belong to the operation,
|
|
15
|
+
* and to `teamId` when that is given; `teamRole` cannot be combined with it). Otherwise the active explicit members of
|
|
16
|
+
* the operation's teams (`teamId` narrows to one team) whose role is at least `teamRole` on their team kind's ladder.
|
|
17
|
+
* One entry per person.
|
|
18
|
+
*/
|
|
19
|
+
export declare function shiftsBroadcastRecipients(event: H3Event, operationId: string, audience: BroadcastInput['audience']): Promise<{
|
|
20
|
+
recipients: ShiftsBroadcastRecipient[];
|
|
21
|
+
teamId: string | null;
|
|
22
|
+
shiftId: string | null;
|
|
23
|
+
}>;
|
|
24
|
+
/**
|
|
25
|
+
* Sends a broadcast: resolves the audience (400 `audience_empty` for nobody, 400 `audience_too_large` past
|
|
26
|
+
* `SHIFTS_BROADCAST_CAP`), the people and their locales (so a failure there leaves no history row), stores it, then emails
|
|
27
|
+
* each person (and texts the ones with a phone number when `sms` is among the channels) the subject and message in their
|
|
28
|
+
* own locale. SMS is opt-in per broadcast because it costs money. A delivery that fails is logged and skipped: the
|
|
29
|
+
* broadcast stands.
|
|
30
|
+
*
|
|
31
|
+
* Delivery runs in Cloudflare's `waitUntil` when the app runs on Workers, so the request returns once the
|
|
32
|
+
* row is stored, with `delivery: 'queued'` and no counts; the totals, failures included, are logged when it ends. Without
|
|
33
|
+
* one (Node) it is awaited and `sent` says how many went out. Fires `shifts:broadcast:sent` once delivery is over.
|
|
34
|
+
*/
|
|
35
|
+
export declare function shiftsSendBroadcast(event: H3Event, input: BroadcastInput, by: number): Promise<ShiftBroadcastResultDto>;
|
|
36
|
+
/** The broadcasts of an operation, newest first (the last 100). */
|
|
37
|
+
export declare function shiftsListBroadcasts(operationId: string): Promise<ShiftBroadcastDto[]>;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { db, schema } from "@nuxthub/db";
|
|
2
|
+
import { and, desc, eq, inArray } from "drizzle-orm";
|
|
3
|
+
import { apiError, chunkParams, validationError } from "@frigear-nu/module-kit/server";
|
|
4
|
+
import { ladderKeys, roleAtLeast } from "@frigear-nu/teams/utils";
|
|
5
|
+
import { newId, translate } from "../../utils/index.js";
|
|
6
|
+
import { ACTIVE_ASSIGNMENT_STATUSES } from "../../utils/status.js";
|
|
7
|
+
import { buildShiftBroadcastEmail, buildShiftBroadcastSms } from "../reminder-email.js";
|
|
8
|
+
import { toShiftBroadcastDto } from "./shifts-dto.js";
|
|
9
|
+
import { shiftsNotify } from "./shifts-notify.js";
|
|
10
|
+
import { SHIFTS_TOPICS } from "../../notifications.js";
|
|
11
|
+
import { findShiftEntry, shiftsFire, shiftsLocalesOfMany, shiftsOperationTeamOr400, shiftsUsersById } from "./shifts-core.js";
|
|
12
|
+
export const SHIFTS_BROADCAST_CAP = 500;
|
|
13
|
+
export async function shiftsBroadcastRecipients(event, operationId, audience) {
|
|
14
|
+
const people = /* @__PURE__ */ new Map();
|
|
15
|
+
if (audience.shiftId) {
|
|
16
|
+
if (audience.teamRole) throw validationError([{ path: ["audience", "teamRole"], message: "A team role cannot be combined with a shift." }]);
|
|
17
|
+
const entry = await findShiftEntry(audience.shiftId);
|
|
18
|
+
if (!entry || entry.schedule.operationId !== operationId) {
|
|
19
|
+
throw validationError([{ path: ["audience", "shiftId"], message: "The shift must belong to the operation." }], "Unknown shift");
|
|
20
|
+
}
|
|
21
|
+
if (audience.teamId && audience.teamId !== entry.shift.teamId) {
|
|
22
|
+
throw validationError([{ path: ["audience", "shiftId"], message: "The shift belongs to another team." }], "Unknown shift");
|
|
23
|
+
}
|
|
24
|
+
const rows = await db.select({ userId: schema.shiftAssignments.userId }).from(schema.shiftAssignments).where(and(
|
|
25
|
+
eq(schema.shiftAssignments.shiftId, entry.shift.id),
|
|
26
|
+
inArray(schema.shiftAssignments.status, [...ACTIVE_ASSIGNMENT_STATUSES])
|
|
27
|
+
));
|
|
28
|
+
for (const row of rows) people.set(row.userId, { userId: row.userId, teamId: entry.shift.teamId });
|
|
29
|
+
return { recipients: [...people.values()], teamId: entry.shift.teamId, shiftId: entry.shift.id };
|
|
30
|
+
}
|
|
31
|
+
const teams = audience.teamId ? [await shiftsOperationTeamOr400(operationId, audience.teamId, "audience.teamId")] : await db.select().from(schema.teams).where(and(eq(schema.teams.ownerType, "operation"), eq(schema.teams.ownerId, operationId)));
|
|
32
|
+
if (teams.length) {
|
|
33
|
+
const [memberLists, ladders] = await Promise.all([
|
|
34
|
+
// In chunks: D1 binds at most 100 parameters per statement.
|
|
35
|
+
Promise.all(chunkParams(teams.map((team) => team.id)).map((part) => db.select({ teamId: schema.teamMembers.teamId, userId: schema.teamMembers.userId, role: schema.teamMembers.role, status: schema.teamMembers.status }).from(schema.teamMembers).where(inArray(schema.teamMembers.teamId, part)).limit(5e3))),
|
|
36
|
+
loadTeamLadders(event)
|
|
37
|
+
]);
|
|
38
|
+
const members = memberLists.flat();
|
|
39
|
+
const kindOf = new Map(teams.map((team) => [team.id, team.kind]));
|
|
40
|
+
for (const member of members) {
|
|
41
|
+
if (!teamMemberStatusGrants(member.status) || people.has(member.userId)) continue;
|
|
42
|
+
if (audience.teamRole) {
|
|
43
|
+
const ladder = ladders[kindOf.get(member.teamId) ?? ""];
|
|
44
|
+
if (!ladder || !roleAtLeast(ladderKeys(ladder), member.role, audience.teamRole)) continue;
|
|
45
|
+
}
|
|
46
|
+
people.set(member.userId, { userId: member.userId, teamId: member.teamId });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return { recipients: [...people.values()], teamId: audience.teamId ?? null, shiftId: null };
|
|
50
|
+
}
|
|
51
|
+
export async function shiftsSendBroadcast(event, input, by) {
|
|
52
|
+
const { recipients, teamId, shiftId } = await shiftsBroadcastRecipients(event, input.operationId, input.audience);
|
|
53
|
+
if (!recipients.length) throw apiError(400, "audience_empty", "Nobody matches this audience.");
|
|
54
|
+
if (recipients.length > SHIFTS_BROADCAST_CAP) {
|
|
55
|
+
throw apiError(400, "audience_too_large", `A broadcast reaches at most ${SHIFTS_BROADCAST_CAP} people: this one reaches ${recipients.length}. Narrow it to a team, a role or a shift.`, { cap: SHIFTS_BROADCAST_CAP, recipients: recipients.length });
|
|
56
|
+
}
|
|
57
|
+
const [users, locales] = await Promise.all([shiftsUsersById(recipients.map((item) => item.userId)), shiftsLocalesOfMany(recipients)]);
|
|
58
|
+
const [row] = await db.insert(schema.shiftBroadcasts).values({
|
|
59
|
+
id: newId("shb"),
|
|
60
|
+
operationId: input.operationId,
|
|
61
|
+
teamId,
|
|
62
|
+
shiftId,
|
|
63
|
+
teamRole: input.audience.teamRole ?? null,
|
|
64
|
+
channels: input.channels,
|
|
65
|
+
subject: input.subject,
|
|
66
|
+
message: input.message,
|
|
67
|
+
recipientCount: recipients.length,
|
|
68
|
+
sentBy: by
|
|
69
|
+
}).returning();
|
|
70
|
+
const broadcast = toShiftBroadcastDto(row);
|
|
71
|
+
const sent = { email: 0, sms: 0, push: 0 };
|
|
72
|
+
const failed = { email: 0, sms: 0, push: 0 };
|
|
73
|
+
const deliver = async (recipient) => {
|
|
74
|
+
const user = users.get(recipient.userId);
|
|
75
|
+
const locale = locales.get(`${recipient.userId}:${recipient.teamId}`) ?? "en";
|
|
76
|
+
const subject = translate(input.subject, locale, "en");
|
|
77
|
+
const message = translate(input.message, locale, "en");
|
|
78
|
+
const email = input.channels.includes("email") ? buildShiftBroadcastEmail({ email: user?.email ?? null, name: user?.name ?? "", subject, message, locale }) : null;
|
|
79
|
+
const sms = input.channels.includes("sms") ? buildShiftBroadcastSms({ phone: user?.phone ?? null, subject, message }) : null;
|
|
80
|
+
const { channels, failed: lost } = await shiftsNotify(event, recipient.userId, {
|
|
81
|
+
topic: SHIFTS_TOPICS.broadcast,
|
|
82
|
+
email,
|
|
83
|
+
sms,
|
|
84
|
+
// A notification on the phone belongs with the email: a sender who only ticked SMS did not ask for one.
|
|
85
|
+
push: input.channels.includes("email") ? { title: subject, body: message.length > 200 ? `${message.slice(0, 197)}...` : message } : void 0,
|
|
86
|
+
label: `the broadcast ${row.id} to user ${recipient.userId}`
|
|
87
|
+
});
|
|
88
|
+
for (const channel of channels) sent[channel]++;
|
|
89
|
+
for (const channel of lost) failed[channel]++;
|
|
90
|
+
};
|
|
91
|
+
const run = async () => {
|
|
92
|
+
for (let index = 0; index < recipients.length; index += 10) {
|
|
93
|
+
await Promise.all(recipients.slice(index, index + 10).map(deliver));
|
|
94
|
+
}
|
|
95
|
+
console.info(`[shifts] broadcast ${row.id} delivered: ${sent.email} emails, ${sent.sms} texts and ${sent.push} pushes sent, ${failed.email} emails, ${failed.sms} texts and ${failed.push} pushes failed`);
|
|
96
|
+
await shiftsFire("shifts:broadcast:sent", { event, broadcast });
|
|
97
|
+
};
|
|
98
|
+
const waitUntil = shiftsWaitUntil(event);
|
|
99
|
+
if (waitUntil) {
|
|
100
|
+
waitUntil(run().catch((error) => console.error(`[shifts] the delivery of broadcast ${row.id} failed`, error)));
|
|
101
|
+
return { ...broadcast, sent, delivery: "queued" };
|
|
102
|
+
}
|
|
103
|
+
await run();
|
|
104
|
+
return { ...broadcast, sent, delivery: "done" };
|
|
105
|
+
}
|
|
106
|
+
function shiftsWaitUntil(event) {
|
|
107
|
+
const context = event.context.cloudflare?.context;
|
|
108
|
+
return typeof context?.waitUntil === "function" ? (promise) => context.waitUntil(promise) : void 0;
|
|
109
|
+
}
|
|
110
|
+
export async function shiftsListBroadcasts(operationId) {
|
|
111
|
+
const rows = await db.select().from(schema.shiftBroadcasts).where(eq(schema.shiftBroadcasts.operationId, operationId)).orderBy(desc(schema.shiftBroadcasts.createdAt), desc(schema.shiftBroadcasts.id)).limit(100);
|
|
112
|
+
return rows.map(toShiftBroadcastDto);
|
|
113
|
+
}
|