Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions meteor-backend/server/agenda.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { MongoInternals } from 'meteor/mongo';
import { Agenda } from 'agenda';
import { MongoBackend } from '@agendajs/mongo-backend';
import { ClockEvents, rawDb, isValidId } from './collections';
import { computeWorkSeconds, findBreaksForEvent, stopActiveClock } from './clock-core';
import { closeShift, computeWorkSeconds, findBreaksForEvent } from './clock-core';
import { createNotification } from './notify-core';

const { ObjectId } = MongoInternals.NpmModules.mongodb.module;
Expand All @@ -31,6 +31,13 @@ const AUTO_CLOCKOUT_WORK_SECS = 8 * 3600; // 8h in work seconds

let _agenda;

// Resolves once initAgenda has built the instance, so a cancel queued earlier
// in startup (the duplicate-shift cleanup in clock.js) still runs.
let _resolveAgendaReady;
const agendaReady = new Promise((resolve) => {
_resolveAgendaReady = resolve;
});

export function getAgenda() {
return _agenda;
}
Expand Down Expand Up @@ -60,6 +67,7 @@ export async function initAgenda() {
processEvery: '30 seconds',
defaultLockLifetime: 10_000,
});
_resolveAgendaReady(_agenda);

// ── Job: 4h "Take a Break" reminder ──────────────────────────────────────
_agenda.define('shift-4h-reminder', async (job) => {
Expand Down Expand Up @@ -109,7 +117,7 @@ export async function initAgenda() {

// ── Job: 8h auto-clockout (agreed) ───────────────────────────────────────
_agenda.define('shift-auto-clockout', async (job) => {
const { clockEventId, userId, teamId } = job.attrs.data;
const { clockEventId } = job.attrs.data;
const event = await findOpenEvent(clockEventId);
if (!event) return; // already clocked out
if (!event.autoClockoutAgreed) return; // user changed their mind
Expand All @@ -124,13 +132,13 @@ export async function initAgenda() {
return;
}

await stopActiveClock(userId, teamId, now);
await closeShift(event, now); // this shift only — other teams keep running
await job.remove(); // one-shot: remove so it doesn't re-fire
});

// ── Job: 8h missed auto-clockout ─────────────────────────────────────────
_agenda.define('shift-missed-clockout', async (job) => {
const { clockEventId, userId, teamId } = job.attrs.data;
const { clockEventId, userId } = job.attrs.data;
const event = await findOpenEvent(clockEventId);
if (!event) return; // already clocked out
if (event.shiftReminderResponse === 'disagreed') return; // respected "Continue Working"
Expand All @@ -146,7 +154,7 @@ export async function initAgenda() {
return;
}

await stopActiveClock(userId, teamId, now);
await closeShift(event, now); // this shift only — other teams keep running

// Rewrite the existing shift-end-reminder notification in-place to describe
// the auto-clock-out outcome (keeps exactly one inbox entry).
Expand Down Expand Up @@ -254,10 +262,10 @@ export async function scheduleMissedClockout(clockEventId, userId, teamId, start

/** Cancel all pending jobs for a clock event (manual clock-out or delete). */
export async function cancelClockJobs(clockEventId) {
await _agenda.cancel({ data: { clockEventId } });
await (_agenda ?? (await agendaReady)).cancel({ data: { clockEventId } });
}

/** Cancel a single named job for a clock event. */
export async function cancelClockJobsByName(clockEventId, name) {
await _agenda.cancel({ name, data: { clockEventId } });
await (_agenda ?? (await agendaReady)).cancel({ name, data: { clockEventId } });
}
62 changes: 46 additions & 16 deletions meteor-backend/server/clock-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* the close-out. No Meteor method/DDP context here — plain async helpers.
*/
import { ClockEvents, ClockBreaks } from './collections';
import { closeAllForUser } from './timer-core';
import { closeTimersForShift } from './timer-core';

/** 20-minute threshold: breaks >= this are non-compensable meal breaks (deducted). */
export const MEAL_BREAK_THRESHOLD_SECONDS = 20 * 60;
Expand Down Expand Up @@ -208,33 +208,63 @@ export function toPublicClockEvent(event, breaks) {
}

/**
* Close the user's active clock event in a team: close any running ticket
* timers, auto-classify any open break, compute accumulatedTime (span minus
* meal breaks), and set endTime. Returns the updated event doc, or null when
* there was nothing open. Mirrors ClockService.stop / clock.stop.
* Every open shift the user has, one per team at most (the unique open-shift
* index on `clockevents` guarantees it), oldest first.
*
* The one place "is this person on the clock?" is answered: a lookup with
* `findOne({ userId, endTime: null })` would hand back whichever shift Mongo
* found first once the user is clocked in to two teams.
*/
export async function stopActiveClock(userId, teamId, now = Date.now()) {
const event = await ClockEvents.findOneAsync({ userId, teamId, endTime: null });
if (!event) return null;
export function findOpenShifts(userId) {
return ClockEvents.find({ userId, endTime: null }, { sort: { startTime: 1 } }).fetchAsync();
}

const eventId = event._id.toHexString();
/**
* The user's open shift in one team, or null. A missing team is null rather
* than "any team": the driver drops an undefined `teamId` from the filter.
*/
export async function findOpenShift(userId, teamId) {
if (typeof teamId !== 'string' || !teamId) return null;
return ClockEvents.findOneAsync({ userId, teamId, endTime: null });
}

/**
* Close one shift at `now`: stop the ticket timers running inside it, close
* and auto-classify its open break, compute accumulatedTime (span minus meal
* breaks) and set endTime.
*
* Only this shift is touched — clocking out of one team leaves the user's other
* teams' shifts and ticket timers running. Returns `{ event, breaks }` with the
* closed event, or null when the shift had already been closed by someone else
* (a second tab, the auto clock-out). Cancelling the shift's Agenda jobs is left
* to the caller: agenda.js imports this module. Shared by `clock.stop`, the
* Agenda auto clock-out and the startup duplicate-shift cleanup.
*/
export async function closeShift(event, now) {
const eventId = hexId(event._id);

// Close any running timer sessions for this user (mirrors clock.stop).
await closeAllForUser(userId, now);
await closeTimersForShift(event.userId, eventId, now);
Comment on lines +243 to +246

const openBreak = await ClockBreaks.findOneAsync({ clockEventId: eventId, endTime: null });
if (openBreak) {
const durationSeconds = Math.floor((now - openBreak.startTime) / 1000);
// A break opened after `now` (only possible when closing a shift in the
// past) ends where it began rather than before it.
const breakEnd = Math.max(now, openBreak.startTime);
const durationSeconds = Math.floor((breakEnd - openBreak.startTime) / 1000);
await ClockBreaks.updateAsync(openBreak._id, {
$set: { endTime: now, ...classifyBreak(durationSeconds) },
$set: { endTime: breakEnd, ...classifyBreak(durationSeconds) },
});
}

const breaks = await findBreaksForEvent(eventId);
const shiftSpan = Math.floor((now - event.startTime) / 1000);
const shiftSpan = Math.max(0, Math.floor((now - event.startTime) / 1000));
const deducted = computeDeductedBreakSeconds(breaks, now);
const accumulatedTime = Math.max(0, shiftSpan - deducted);

await ClockEvents.updateAsync(event._id, { $set: { endTime: now, accumulatedTime } });
return ClockEvents.findOneAsync(event._id);
const modified = await ClockEvents.updateAsync(
{ _id: event._id, endTime: null },
{ $set: { endTime: now, accumulatedTime } }
);
if (!modified) return null;
return { event: await ClockEvents.findOneAsync(event._id), breaks };
}
Loading
Loading