Skip to content
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import { describe, expect, it } from "vitest";
import {
emptyBreakdown,
hasLoggedHours,
timeCardDraftErrors,
totalHours,
} from "@features/csm-timecards/utils/timeCardTotals";

describe("timeCardTotals", () => {
it("emptyBreakdown is all zeros and sums to 0", () => {
expect(totalHours(emptyBreakdown())).toBe(0);
expect(hasLoggedHours(emptyBreakdown())).toBe(false);
});

it("sums activity buckets without float drift", () => {
expect(
totalHours({
analysisDebugging: 0.1,
reproduce: 1.5,
settingUp: 0.2,
providingSolution: 0.5,
answering: 0,
}),
).toBe(2.3);
});

it("detects logged hours", () => {
expect(hasLoggedHours({ ...emptyBreakdown(), answering: 0.25 })).toBe(true);
});

describe("timeCardDraftErrors", () => {
const valid = {
date: "2026-06-27",
breakdown: { ...emptyBreakdown(), analysisDebugging: 1 },
workLogComment: "Investigated root cause.",
approverId: "lead-1",
};

it("passes a complete draft", () => {
expect(timeCardDraftErrors(valid)).toEqual({});
});

it("flags every missing required field", () => {
const errors = timeCardDraftErrors({
date: "",
breakdown: emptyBreakdown(),
workLogComment: " ",
approverId: undefined,
});
expect(errors.date).toBeDefined();
expect(errors.hours).toBeDefined();
expect(errors.workLogComment).toBeDefined();
expect(errors.approver).toBeDefined();
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import { describe, expect, it } from "vitest";
import {
weekEndOf,
weekLabel,
weekStartOf,
} from "@features/csm-timecards/utils/timeSheetWeek";

const utcDay = (iso: string): number =>
new Date(`${iso}T00:00:00Z`).getUTCDay();

describe("timeSheetWeek", () => {
it("weekStartOf returns the Monday of the week", () => {
// 2026-06-27 is a Saturday.
expect(utcDay(weekStartOf("2026-06-27"))).toBe(1); // Monday
});

it("is idempotent on a week start", () => {
const ws = weekStartOf("2026-06-27");
expect(weekStartOf(ws)).toBe(ws);
});

it("weekEndOf is the following Sunday, 6 days later", () => {
const ws = weekStartOf("2026-06-27");
const we = weekEndOf(ws);
expect(utcDay(we)).toBe(0); // Sunday
expect(weekStartOf(we)).toBe(ws); // the end maps back to the same start
});

it("weekLabel renders a readable range", () => {
const ws = weekStartOf("2026-06-27");
expect(weekLabel(ws)).toMatch(/2026/);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import {
ACTIVITY_KEYS,
type ActivityBreakdown,
} from "@features/csm-timecards/types/timeCards";

/** A fresh breakdown with every activity at zero hours. */
export function emptyBreakdown(): ActivityBreakdown {
return {
analysisDebugging: 0,
reproduce: 0,
settingUp: 0,
providingSolution: 0,
answering: 0,
};
}

/** Round to 2 decimals to avoid float drift in summed hours (e.g. 0.1 + 0.2). */
export function roundHours(value: number): number {
return Math.round(value * 100) / 100;
}

/** Total hours across all activity buckets. */
export function totalHours(breakdown: ActivityBreakdown): number {
return roundHours(
ACTIVITY_KEYS.reduce((sum, key) => sum + (breakdown[key] || 0), 0),
);
}

/** True when at least one activity bucket has positive hours. */
export function hasLoggedHours(breakdown: ActivityBreakdown): boolean {
return ACTIVITY_KEYS.some((key) => (breakdown[key] || 0) > 0);
}

/** Field-level validation errors for the log dialog, keyed by field name. */
export interface TimeCardDraftErrors {
date?: string;
hours?: string;
workLogComment?: string;
approver?: string;
}

export interface TimeCardDraft {
date: string;
breakdown: ActivityBreakdown;
workLogComment: string;
approverId?: string;
}

/**
* Validate a log-time draft. Returns an errors object; an empty object means the
* draft is submittable. Mirrors the ServiceNow required fields (Date, Task —
* preset from the case, Work Log Comment, Approver) plus a "log some time" rule.
*/
export function timeCardDraftErrors(draft: TimeCardDraft): TimeCardDraftErrors {
const errors: TimeCardDraftErrors = {};
if (!draft.date) errors.date = "Pick a date.";
if (!hasLoggedHours(draft.breakdown)) {
errors.hours = "Log time against at least one activity.";
}
if (!draft.workLogComment.trim()) {
errors.workLogComment = "Add a work log comment.";
}
if (!draft.approverId) errors.approver = "Choose an approver.";
return errors;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

import type {
CsmTimeCard,
CsmTimeSheet,
TimeCardState,
TimeSheetState,
} from "@features/csm-timecards/types/timeCards";

/** Actions that can be taken on a card or sheet. */
export type TimecardAction =
| "edit"
| "delete"
| "submit"
| "resubmit"
| "approve"
| "reject"
| "recall"
| "process";

/** The capabilities of the current user relative to the target. */
export interface TimecardRoleCtx {
/** The signed-in user owns the card/sheet. */
isOwner: boolean;
/** The signed-in user may approve (team-lead/approver, or admin). */
isApprover: boolean;
/** The signed-in user is a time-card admin. */
isAdmin: boolean;
}

/** States in which the owner (or admin) may edit a card. */
export const EDITABLE_STATES: TimeCardState[] = ["pending", "rejected", "recalled"];

/**
* Allowed actions on a single card given its state and the user's role. Single
* source of truth for which buttons render (mirrors the cases `nextStates`
* pattern). The owner edits/submits; an approver approves/rejects/recalls; an
* admin can do both plus process.
*/
export function cardActions(
state: TimeCardState,
role: TimecardRoleCtx,
): TimecardAction[] {
const canEdit = role.isOwner || role.isAdmin;
const canApprove = role.isApprover || role.isAdmin;
switch (state) {
case "pending":
return canEdit ? ["edit", "delete", "submit"] : [];
case "rejected":
case "recalled":
return canEdit ? ["edit", "delete", "resubmit"] : [];
case "submitted":
return canApprove ? ["approve", "reject"] : [];
case "approved":
return [
...(canApprove ? (["recall"] as TimecardAction[]) : []),
...(role.isAdmin ? (["process"] as TimecardAction[]) : []),
];
case "processed":
default:
return [];
}
}

/** Roll a sheet's cards up into a single status for display. */
export function sheetStatus(cards: CsmTimeCard[]): TimeSheetState {
if (cards.some((c) => c.state === "rejected")) return "rejected";
if (cards.some((c) => c.state === "recalled")) return "recalled";
if (cards.some((c) => c.state === "submitted")) return "submitted";
if (
cards.length > 0 &&
cards.every((c) => c.state === "approved" || c.state === "processed")
) {
return "approved";
}
return "open";
}

/** Sheet-level actions (a subset of {@link TimecardAction}). */
export type SheetAction = "submit" | "approve" | "reject" | "recall";

/** Sheet-level actions available to the user. */
export function sheetActions(
sheet: CsmTimeSheet,
role: TimecardRoleCtx,
): SheetAction[] {
const actions: SheetAction[] = [];
const canEdit = role.isOwner || role.isAdmin;
const canApprove = role.isApprover || role.isAdmin;
if (canEdit && sheet.cards.some((c) => EDITABLE_STATES.includes(c.state))) {
actions.push("submit");
}
if (canApprove && sheet.cards.some((c) => c.state === "submitted")) {
actions.push("approve"); // "approve remaining"
actions.push("reject"); // "reject remaining"
}
if (canApprove && sheet.cards.some((c) => c.state === "approved")) {
actions.push("recall");
}
return actions;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Copyright (c) 2026 WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

// ISO-week helpers (weeks run Monday–Sunday). Dates are handled as plain
// YYYY-MM-DD strings in UTC to avoid timezone drift in week boundaries.

function toUtcDate(iso: string): Date {
return new Date(`${iso.slice(0, 10)}T00:00:00Z`);
}

function isoOf(d: Date): string {
return d.toISOString().slice(0, 10);
}

/** The Monday (YYYY-MM-DD) of the ISO week containing `iso`. */
export function weekStartOf(iso: string): string {
const d = toUtcDate(iso);
// getUTCDay: 0=Sun..6=Sat. Days since Monday = (day + 6) % 7.
const sinceMonday = (d.getUTCDay() + 6) % 7;
d.setUTCDate(d.getUTCDate() - sinceMonday);
return isoOf(d);
}

/** The Sunday (YYYY-MM-DD) ending the week that starts on `weekStart`. */
export function weekEndOf(weekStart: string): string {
const d = toUtcDate(weekStart);
d.setUTCDate(d.getUTCDate() + 6);
return isoOf(d);
}

/** Stable key for a week — the Monday date. */
export function weekKey(iso: string): string {
return weekStartOf(iso);
}

/**
* Today's date as YYYY-MM-DD in the user's **local** timezone. Use this for the
* default log date and "current week" so an engineer logging at 1 AM local time
* gets the local calendar day, not the UTC one (which can be the day before).
*/
export function localTodayIso(): string {
const now = new Date();
const local = new Date(now.getTime() - now.getTimezoneOffset() * 60_000);
return local.toISOString().slice(0, 10);
}

/** Human label, e.g. "Jun 23 – 29, 2026" (or spanning months/years). */
export function weekLabel(weekStart: string): string {
const start = toUtcDate(weekStart);
const end = toUtcDate(weekEndOf(weekStart));
const mon = (d: Date): string =>
d.toLocaleDateString("en-US", { month: "short", timeZone: "UTC" });
const day = (d: Date): number => d.getUTCDate();
const year = end.getUTCFullYear();
if (mon(start) === mon(end)) {
return `${mon(start)} ${day(start)} – ${day(end)}, ${year}`;
}
return `${mon(start)} ${day(start)} – ${mon(end)} ${day(end)}, ${year}`;
}