Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

29.1 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import type { ServiceContext } from "@carbon/api/service-fn.server";
import type { Database, Json } from "@carbon/database";
import { getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
import { datetime, searchFilter } from "@carbon/utils";
import { getDayOfWeek, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
import type { DataType } from "~/modules/shared/types";
import type { Employee } from "~/modules/users/types";
import { getEmployees } from "~/modules/users/users.service";
import type { GenericQueryFilters, Paging } from "~/utils/query";
import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
  departmentValidator,
  employeeJobValidator,
  holidayValidator,
  shiftValidator
} from "./people.models";

export async function deleteAttribute(
  client: SupabaseClient<Database>,
  attributeId: string
) {
  return client
    .from("userAttribute")
    .update({ active: false })
    .eq("id", attributeId);
}

export async function deleteAttributeCategory(
  client: SupabaseClient<Database>,
  attributeCategoryId: string
) {
  return client
    .from("userAttributeCategory")
    .update({ active: false })
    .eq("id", attributeCategoryId);
}

export async function deleteDepartment(
  client: SupabaseClient<Database>,
  departmentId: string
) {
  return client.from("department").delete().eq("id", departmentId);
}

export async function deleteHoliday(
  client: SupabaseClient<Database>,
  holidayId: string
) {
  return client.from("holiday").delete().eq("id", holidayId);
}

export async function deleteShift(
  client: SupabaseClient<Database>,
  shiftId: string
) {
  // TODO: Set all employeeShifts to null
  return client.from("shift").update({ active: false }).eq("id", shiftId);
}

export async function getAttribute(
  client: SupabaseClient<Database>,
  attributeId: string
) {
  return client
    .from("userAttribute")
    .select("*, userAttributeCategory(name)")
    .eq("id", attributeId)
    .eq("active", true)
    .single();
}

async function getAttributes(
  client: SupabaseClient<Database>,
  companyId: string,
  userIds: string[]
) {
  return client
    .from("userAttributeCategory")
    .select(
      `*,
      userAttribute(id, name, listOptions, canSelfManage,
        attributeDataType(id, isBoolean, isDate, isNumeric, isText, isUser, isFile),
        userAttributeValue(
          id, userId, valueBoolean, valueDate, valueNumeric, valueText, valueUser, valueFile, user!userAttributeValue_userId_fkey(id, fullName, avatarUrl)
        )
      )`
    )
    .eq("companyId", companyId)
    .eq("userAttribute.active", true)
    .in("userAttribute.userAttributeValue.userId", userIds)
    .order("sortOrder", { foreignTable: "userAttribute", ascending: true });
}

export const ATTRIBUTE_CATEGORIES_PAGING: Paging = {
  defaultSorts: [{ column: "name", ascending: true }]
};

export async function getAttributeCategories(
  client: SupabaseClient<Database>,
  companyId: string,
  args?: { search: string | null } & GenericQueryFilters
) {
  let query = client
    .from("userAttributeCategory")
    .select("*, userAttribute(id, name, attributeDataType(id))", {
      count: listCount(args)
    })
    .eq("companyId", companyId)
    .eq("active", true)
    .eq("userAttribute.active", true);

  if (args?.search) {
    query = query.ilike("name", `%${args.search}%`);
  }

  if (args) {
    query = setGenericQueryFilters(query, args, ATTRIBUTE_CATEGORIES_PAGING);
  }

  return query;
}

export async function getAttributeCategory(
  client: SupabaseClient<Database>,
  id: string
) {
  return client
    .from("userAttributeCategory")
    .select(
      `*,
      userAttribute(
        id, name, sortOrder,
        attributeDataType(id, label, isBoolean, isDate, isList, isNumeric, isText, isUser, isFile))
      `,
      {
        count: "exact"
      }
    )
    .eq("id", id)
    .eq("active", true)
    .eq("userAttribute.active", true)
    .single();
}

export async function getAttributeDataTypes(client: SupabaseClient<Database>) {
  return client.from("attributeDataType").select("*");
}

export async function getDepartment(
  client: SupabaseClient<Database>,
  departmentId: string
) {
  return client.from("department").select("*").eq("id", departmentId).single();
}

export async function getDepartments(
  client: SupabaseClient<Database>,
  companyId: string,
  args?: GenericQueryFilters & { search: string | null }
) {
  let query = client
    .from("department")
    .select(`*, department(id, name)`, {
      count: LIST_COUNT
    })
    .eq("companyId", companyId);

  if (args?.search) {
    query = query.ilike("name", `%${args.search}%`);
  }

  if (args) {
    query = setGenericQueryFilters(query, args, [
      { column: "name", ascending: true }
    ]);
  }

  return query;
}

export async function getDepartmentsList(
  client: SupabaseClient<Database>,
  companyId: string
) {
  return client
    .from("department")
    .select(`id, name`)
    .eq("companyId", companyId)
    .order("name");
}

export async function getDepartmentsTree(
  client: SupabaseClient<Database>,
  companyId: string
) {
  return client
    .from("department")
    .select("id, name, parentDepartmentId")
    .eq("companyId", companyId)
    .order("name");
}

export async function getEmployeeJob(
  client: SupabaseClient<Database>,
  employeeId: string,
  companyId: string
) {
  return client
    .from("employeeJob")
    .select("*")
    .eq("id", employeeId)
    .eq("companyId", companyId)
    .single();
}

export async function getEmployeeSummary(
  client: SupabaseClient<Database>,
  employeeId: string,
  companyId: string
) {
  return client
    .from("employeeSummary")
    .select("*")
    .eq("id", employeeId)
    .eq("companyId", companyId)
    .single();
}

export async function getHoliday(
  client: SupabaseClient<Database>,
  holidayId: string
) {
  return client.from("holiday").select("*").eq("id", holidayId).single();
}

export const HOLIDAYS_PAGING: Paging = {
  defaultSorts: [{ column: "date", ascending: true }]
};

export async function getHolidays(
  client: SupabaseClient<Database>,
  companyId: string,
  args?: GenericQueryFilters & { search: string | null }
) {
  let query = client
    .from("holiday")
    .select("*", {
      count: listCount(args)
    })
    .eq("companyId", companyId);

  if (args?.search) {
    query = query.ilike("name", `%${args.search}%`);
  }

  if (args) {
    query = setGenericQueryFilters(query, args, HOLIDAYS_PAGING);
  }

  return query;
}

export function getHolidayYears(
  client: SupabaseClient<Database>,
  companyId: string
) {
  return client.from("holidayYears").select("year").eq("companyId", companyId);
}

type UserAttributeId = string;

export type PersonAttributeValue = {
  userAttributeValueId: string;
  value: boolean | string | number;
  dataType?: DataType;
  user?: {
    id: string;
    fullName: string | null;
    avatarUrl: string | null;
  } | null;
};

type PersonAttributes = Record<UserAttributeId, PersonAttributeValue>;

type Person = Employee & {
  attributes: PersonAttributes;
};

export async function getPeople(
  client: SupabaseClient<Database>,
  companyId: string,
  args: GenericQueryFilters & {
    search: string | null;
  }
) {
  const employees = await getEmployees(client, companyId, args);
  if (employees.error) return employees;

  if (!employees.data) throw new Error("Failed to get employee data");

  const userIds = employees.data.reduce<string[]>((acc, employee) => {
    if (employee.id) acc.push(employee.id);
    return acc;
  }, []);

  const attributeCategories = await getAttributes(client, companyId, userIds);
  if (attributeCategories.error) return attributeCategories;

  const people: Person[] = employees.data.map((employee) => {
    const userId = employee.id;

    const employeeAttributes =
      attributeCategories.data.reduce<PersonAttributes>((acc, category) => {
        if (!category.userAttribute || !Array.isArray(category.userAttribute))
          return acc;
        category.userAttribute.forEach((attribute) => {
          if (
            attribute.userAttributeValue &&
            Array.isArray(attribute.userAttributeValue) &&
            !Array.isArray(attribute.attributeDataType)
          ) {
            const userAttributeId = attribute.id;
            const userAttributeValue = attribute.userAttributeValue.find(
              (attributeValue) => attributeValue.userId === userId
            );
            const value =
              typeof userAttributeValue?.valueBoolean === "boolean"
                ? userAttributeValue.valueBoolean
                : userAttributeValue?.valueDate ||
                  userAttributeValue?.valueNumeric ||
                  userAttributeValue?.valueText ||
                  userAttributeValue?.valueUser ||
                  userAttributeValue?.valueFile;

            if (value && userAttributeValue?.id) {
              acc[userAttributeId] = {
                userAttributeValueId: userAttributeValue.id,
                dataType: attribute.attributeDataType?.id as DataType,
                value,
                user: !Array.isArray(userAttributeValue.user)
                  ? userAttributeValue.user
                  : undefined
              };
            }
          }
        });
        return acc;
      }, {});

    return {
      ...employee,
      attributes: employeeAttributes
    };
  });

  return {
    count: employees.count,
    data: people,
    error: null
  };
}

export async function getContacts(
  client: SupabaseClient<Database>,
  companyId: string,
  args: GenericQueryFilters & {
    search: string | null;
  }
) {
  let query = client
    .from("contact")
    .select("*", { count: LIST_COUNT })
    .eq("companyId", companyId);

  if (args.search) {
    query = query.or(
      searchFilter(["firstName", "lastName", "email"], args.search)
    );
  }

  query = setGenericQueryFilters(query, args, [
    { column: "lastName", ascending: true }
  ]);

  const contacts = await query;

  if (!contacts.data) throw new Error("Failed to get contacts data");

  return {
    count: contacts.count,
    data: contacts.data,
    error: null
  };
}
export async function getShift(
  client: SupabaseClient<Database>,
  shiftId: string
) {
  return client
    .from("shifts")
    .select("*")
    .eq("id", shiftId)
    .eq("active", true)
    .single();
}

export const SHIFTS_PAGING: Paging = {
  defaultSorts: [{ column: "locationId", ascending: true }]
};

export async function getShifts(
  client: SupabaseClient<Database>,
  companyId: string,
  args: GenericQueryFilters & { search: string | null }
) {
  let query = client
    .from("shifts")
    .select("*", {
      count: listCount(args)
    })
    .eq("companyId", companyId)
    .eq("active", true);

  if (args?.search) {
    query = query.ilike("name", `%${args.search}%`);
  }

  query = setGenericQueryFilters(query, args, SHIFTS_PAGING);
  return query;
}

export async function getShiftsList(
  client: SupabaseClient<Database>,
  companyId: string,
  locationId: string | null
) {
  let query = client
    .from("shift")
    .select(`id, name`)
    .eq("companyId", companyId)
    .eq("active", true);

  if (locationId) {
    query = query.eq("locationId", locationId);
  }

  return query.order("name");
}

export async function getEmployeeShifts(
  client: SupabaseClient<Database>,
  companyId: string
) {
  return client
    .from("employeeShift")
    .select("employeeId, shiftId")
    .eq("companyId", companyId);
}

export async function getEmployeeDepartments(
  client: SupabaseClient<Database>,
  companyId: string
) {
  return client
    .from("employeeJob")
    .select("id, departmentId")
    .eq("companyId", companyId);
}

export async function getShiftsWithTimes(
  client: SupabaseClient<Database>,
  companyId: string,
  locationId: string
) {
  return client
    .from("shift")
    .select(
      "id, name, startTime, endTime, monday, tuesday, wednesday, thursday, friday, saturday, sunday"
    )
    .eq("companyId", companyId)
    .eq("locationId", locationId)
    .eq("active", true)
    .order("name");
}

/**
 * Active shifts by id, with their times. A work center can be linked to a
 * shift of another location, which `getShiftsWithTimes` does not return.
 */
export async function getShiftsWithTimesByIds(
  client: SupabaseClient<Database>,
  companyId: string,
  shiftIds: string[]
) {
  return client
    .from("shift")
    .select(
      "id, name, startTime, endTime, monday, tuesday, wednesday, thursday, friday, saturday, sunday"
    )
    .eq("companyId", companyId)
    .in("id", shiftIds)
    .eq("active", true);
}

export async function insertAttribute(
  client: SupabaseClient<Database>,
  attribute: {
    name: string;
    attributeDataTypeId: number;
    userAttributeCategoryId: string;
    listOptions?: string[];
    canSelfManage: boolean;
    createdBy: string;
  }
) {
  // TODO: there's got to be a better way to get the max
  const sortOrders = await client
    .from("userAttribute")
    .select("sortOrder")
    .eq("userAttributeCategoryId", attribute.userAttributeCategoryId);

  if (sortOrders.error) return sortOrders;
  const maxSortOrder = sortOrders.data.reduce((max, item) => {
    return Math.max(max, item.sortOrder);
  }, 0);

  return client
    .from("userAttribute")
    .upsert([{ ...attribute, sortOrder: maxSortOrder + 1 }])
    .select("id")
    .single();
}

export async function insertAttributeCategory(
  client: SupabaseClient<Database>,
  attributeCategory: {
    name: string;
    emoji?: string;
    public: boolean;
    companyId: string;
    createdBy: string;
  }
) {
  return client
    .from("userAttributeCategory")
    .upsert([attributeCategory])
    .select("id")
    .single();
}

export async function insertEmployeeJob(
  client: SupabaseClient<Database>,
  job: {
    id: string;
    companyId: string;
    locationId: string;
  }
) {
  return client.from("employeeJob").insert(job).select("*").single();
}

export async function updateAttribute(
  client: SupabaseClient<Database>,
  attribute: {
    id?: string;
    name: string;
    listOptions?: string[];
    canSelfManage: boolean;
    updatedBy: string;
  }
) {
  if (!attribute.id) throw new Error("id is required");
  return client
    .from("userAttribute")
    .update(
      sanitize({
        name: attribute.name,
        listOptions: attribute.listOptions,
        canSelfManage: attribute.canSelfManage,
        updatedBy: attribute.updatedBy
      })
    )
    .eq("id", attribute.id);
}

export async function updateAttributeCategory(
  client: SupabaseClient<Database>,
  attributeCategory: {
    id: string;
    name: string;
    emoji?: string;
    public: boolean;
    updatedBy: string;
  }
) {
  const { id, ...update } = attributeCategory;
  return client
    .from("userAttributeCategory")
    .update(sanitize(update))
    .eq("id", id);
}

export async function updateAttributeSortOrder(
  client: SupabaseClient<Database>,
  updates: {
    id: string;
    sortOrder: number;
    updatedBy: string;
  }[]
) {
  const updatePromises = updates.map(({ id, sortOrder, updatedBy }) =>
    client.from("userAttribute").update({ sortOrder, updatedBy }).eq("id", id)
  );
  return Promise.all(updatePromises);
}

/** People's job updates go through `updatePersonJob`, which also reschedules. */
export async function updateEmployeeJob(
  db: Kysely<KyselyDatabase>,
  employeeId: string,
  employeeJob: z.infer<typeof employeeJobValidator> & {
    companyId: string;
    updatedBy: string;
    customFields?: Json;
  }
) {
  // One Kysely transaction: the employeeJob update and the employeeShift
  // sync commit or roll back together. Kysely also bypasses RLS, so the
  // sync no longer silently no-ops for users without people_create/
  // people_delete — `updatePersonJob`'s people update gate is the auth gate.
  try {
    // sanitize() turns any absent field into null, and locationId is NOT NULL,
    // so a caller that omits it (the API/MCP tool leaves it optional) would
    // otherwise wipe a set location. Never write a falsy locationId — drop it
    // from the payload so the existing value is preserved.
    const sanitized = sanitize(employeeJob);
    // An explicit allow-list, never the caller's object: the API passes
    // `employeeJob` through with whatever keys were sent, and a spread into
    // Kysely's `.set()` (no RLS) would reach any column — `companyId` included.
    const updatePayload = {
      title: sanitized.title,
      startDate: sanitized.startDate,
      ...(sanitized.locationId ? { locationId: sanitized.locationId } : {}),
      shiftId: sanitized.shiftId,
      departmentId: sanitized.departmentId,
      managerId: sanitized.managerId,
      ...("customFields" in sanitized
        ? { customFields: sanitized.customFields }
        : {}),
      updatedBy: sanitized.updatedBy
    };

    const { companyId } = employeeJob;

    await db.transaction().execute(async (trx) => {
      // Kysely bypasses RLS and every id below comes from the caller, so each
      // one is re-read under companyId: the single-column FKs would accept a
      // location, shift, department or manager from any company.
      const [employee, location, shift, department, manager] =
        await Promise.all([
          trx
            .selectFrom("employee")
            .select("id")
            .where("id", "=", employeeId)
            .where("companyId", "=", companyId)
            .executeTakeFirst(),
          updatePayload.locationId
            ? trx
                .selectFrom("location")
                .select("id")
                .where("id", "=", updatePayload.locationId)
                .where("companyId", "=", companyId)
                .executeTakeFirst()
            : null,
          employeeJob.shiftId
            ? trx
                .selectFrom("shift")
                .select("id")
                .where("id", "=", employeeJob.shiftId)
                .where("companyId", "=", companyId)
                .executeTakeFirst()
            : null,
          employeeJob.departmentId
            ? trx
                .selectFrom("department")
                .select("id")
                .where("id", "=", employeeJob.departmentId)
                .where("companyId", "=", companyId)
                .executeTakeFirst()
            : null,
          employeeJob.managerId
            ? trx
                .selectFrom("employee")
                .select("id")
                .where("id", "=", employeeJob.managerId)
                .where("companyId", "=", companyId)
                .executeTakeFirst()
            : null
        ]);
      if (!employee) throw new Error("Employee not found");
      if (updatePayload.locationId && !location) {
        throw new Error("Location not found");
      }
      if (employeeJob.shiftId && !shift) throw new Error("Shift not found");
      if (employeeJob.departmentId && !department) {
        throw new Error("Department not found");
      }
      if (employeeJob.managerId && !manager) {
        throw new Error("Manager not found");
      }

      const updated = await trx
        .updateTable("employeeJob")
        .set(updatePayload)
        .where("id", "=", employeeId)
        .where("companyId", "=", companyId)
        .executeTakeFirst();
      // No row means the employee is not in this company — stop before the
      // employeeShift insert below writes a row for a foreign user id.
      if (Number(updated.numUpdatedRows) === 0) {
        throw new Error("Employee not found");
      }

      // The scheduler reads shift assignments from employeeShift (see
      // getEmployeeShiftWindows in the schedule engine), NOT from
      // employeeJob.shiftId — keep them in sync so assigning a shift here
      // actually constrains ability-gated scheduling.
      await trx
        .deleteFrom("employeeShift")
        .where("employeeId", "=", employeeId)
        .where("companyId", "=", employeeJob.companyId)
        .execute();

      if (employeeJob.shiftId) {
        await trx
          .insertInto("employeeShift")
          .values({
            employeeId,
            shiftId: employeeJob.shiftId,
            companyId: employeeJob.companyId
          })
          .execute();
      }
    });
    return { data: null, error: null };
  } catch (err) {
    return { data: null, error: err as Error };
  }
}

export async function upsertDepartment(
  client: SupabaseClient<Database>,
  department:
    | (Omit<z.infer<typeof departmentValidator>, "id"> & {
        companyId: string;
        createdBy: string;
        customFields?: Json;
      })
    | (Omit<z.infer<typeof departmentValidator>, "id"> & {
        id: string;
        updatedBy: string;
        customFields?: Json;
      })
) {
  if ("id" in department) {
    return client
      .from("department")
      .update(sanitize(department))
      .eq("id", department.id);
  }
  return client.from("department").insert(department).select("*").single();
}

export async function upsertHoliday(
  client: SupabaseClient<Database>,
  holiday:
    | (Omit<z.infer<typeof holidayValidator>, "id"> & {
        companyId: string;
        createdBy: string;
        customFields?: Json;
      })
    | (Omit<z.infer<typeof holidayValidator>, "id"> & {
        id: string;
        updatedBy: string;
        customFields?: Json;
      })
) {
  if ("createdBy" in holiday) {
    return client.from("holiday").insert(holiday).select("*").single();
  }
  return client.from("holiday").update(sanitize(holiday)).eq("id", holiday.id);
}

/** Shifts are saved through `people_createShift` / `people_updateShift`. */
export async function upsertShift(
  client: SupabaseClient<Database>,
  shift:
    | (Omit<z.infer<typeof shiftValidator>, "id"> & {
        createdBy: string;
        companyId: string;
        customFields?: Json;
      })
    | (Omit<z.infer<typeof shiftValidator>, "id"> & {
        id: string;
        companyId: string;
        updatedBy: string;
        customFields?: Json;
      })
) {
  if ("createdBy" in shift) {
    return client.from("shift").insert([shift]).select("*").single();
  }
  const { companyId, ...update } = shift;
  // No row back means the shift is not this company's or the caller may not
  // update it: RLS filters an UPDATE silently.
  return client
    .from("shift")
    .update(sanitize(update))
    .eq("id", shift.id)
    .eq("companyId", companyId)
    .select("id")
    .maybeSingle();
}

/** Clocking in goes through `clockInPerson` / `clockInSelf`. */
export async function clockIn(
  client: SupabaseClient<Database>,
  args: {
    employeeId: string;
    companyId: string;
    createdBy: string;
  }
) {
  const existing = await getOpenClockEntry(
    client,
    args.employeeId,
    args.companyId
  );
  if (existing.data) {
    return { data: null, error: { message: "Already clocked in" } };
  }

  return client.from("timeCardEntry").insert({
    employeeId: args.employeeId,
    companyId: args.companyId,
    createdBy: args.createdBy
  });
}

/** Clocking out goes through `clockOutPerson` / `clockOutSelf`. */
export async function clockOut(
  client: SupabaseClient<Database>,
  args: {
    employeeId: string;
    companyId: string;
    updatedBy: string;
    clockOut?: string;
    note?: string;
  }
) {
  const open = await getOpenClockEntry(client, args.employeeId, args.companyId);
  if (!open.data) {
    return { data: null, error: { message: "Not currently clocked in" } };
  }

  return client
    .from("timeCardEntry")
    .update(
      sanitize({
        clockOut: args.clockOut ?? datetime.timestamp(),
        note: args.note,
        updatedBy: args.updatedBy,
        updatedAt: datetime.timestamp()
      })
    )
    .eq("id", open.data.id);
}

export async function createTimeCardEntry(
  client: SupabaseClient<Database>,
  entry: {
    employeeId: string;
    companyId: string;
    clockIn: string;
    clockOut?: string | null;
    note?: string | null;
    createdBy: string;
  }
) {
  return client
    .from("timeCardEntry")
    .insert(sanitize(entry))
    .select("id")
    .single();
}

export async function deleteTimeCardEntry(
  client: SupabaseClient<Database>,
  entryId: string
) {
  return client.from("timeCardEntry").delete().eq("id", entryId);
}

export async function getClockedInEmployees(
  client: SupabaseClient<Database>,
  companyId: string
) {
  return client
    .from("timeCardEntries")
    .select("*")
    .eq("companyId", companyId)
    .is("clockOut", null)
    .order("clockIn", { ascending: true });
}

export async function getOpenClockEntry(
  client: SupabaseClient<Database>,
  employeeId: string,
  companyId: string
) {
  return client
    .from("timeCardEntry")
    .select("*")
    .eq("employeeId", employeeId)
    .eq("companyId", companyId)
    .is("clockOut", null)
    .maybeSingle();
}

export async function getScheduledEmployeesToday(
  client: SupabaseClient<Database>,
  companyId: string
) {
  // Deactivation keeps the employeeJob row (and its shift), so the roster is
  // narrowed to active employees. employeeJob has no FK to employee to embed.
  const [{ data }, { data: activeEmployees }] = await Promise.all([
    client
      .from("employeeJob")
      .select(
        "id, shiftId, shift:shift(id, name, startTime, endTime, sunday, monday, tuesday, wednesday, thursday, friday, saturday)"
      )
      .eq("companyId", companyId)
      .not("shiftId", "is", null),
    client
      .from("employee")
      .select("id")
      .eq("companyId", companyId)
      .eq("active", true)
  ]);

  if (!data || !activeEmployees) return [];
  const activeIds = new Set(activeEmployees.map((e) => e.id));

  const dayNames = [
    "sunday",
    "monday",
    "tuesday",
    "wednesday",
    "thursday",
    "friday",
    "saturday"
  ] as const;
  // "Today" on the company calendar — at 01:00 Monday local, UTC is still on
  // Sunday and must not roster Sunday's shift. en-US: 0 = Sunday.
  const tz = await getCompanyTimeZone(client, companyId);
  const dayName = dayNames[getDayOfWeek(today(tz), "en-US")];

  return data.filter((ej) => {
    const shift = ej.shift as Record<string, unknown> | null;
    return activeIds.has(ej.id) && shift && shift[dayName] === true;
  });
}

export async function getTimeCardEntry(
  client: SupabaseClient<Database>,
  entryId: string
) {
  return client.from("timeCardEntry").select("*").eq("id", entryId).single();
}

export async function getTimeCardEntries(
  client: SupabaseClient<Database>,
  args: {
    employeeId: string;
    companyId: string;
    from?: string;
    to?: string;
  }
) {
  let query = client
    .from("timeCardEntry")
    .select("*")
    .eq("employeeId", args.employeeId)
    .eq("companyId", args.companyId)
    .order("clockIn", { ascending: false });

  if (args.from) {
    query = query.gte("clockIn", args.from);
  }
  if (args.to) {
    query = query.lte("clockIn", args.to);
  }

  return query;
}

export const TIMECARD_ENTRIES_PAGING: Paging = {
  defaultSorts: [{ column: "clockIn", ascending: false }]
};

export async function getTimecardEntries(
  client: SupabaseClient<Database>,
  companyId: string,
  args: GenericQueryFilters & { search: string | null }
) {
  let query = client
    .from("timeCardEntries")
    .select("*", { count: listCount(args) })
    .eq("companyId", companyId);

  if (args.search) {
    query = query.or(searchFilter(["firstName", "lastName"], args.search));
  }

  query = setGenericQueryFilters(query, args, TIMECARD_ENTRIES_PAGING);

  return query;
}

export async function getWeeklyHoursForEmployees(
  client: SupabaseClient<Database>,
  companyId: string,
  employeeIds: string[]
): Promise<Record<string, number>> {
  // Week starts Monday 00:00 on the company calendar (one payroll boundary
  // per books), not the server's.
  const tz = await getCompanyTimeZone(client, companyId);
  const { from } = datetime.weekBounds(tz);

  const { data: entries } = await client
    .from("timeCardEntry")
    .select("employeeId, clockIn, clockOut")
    .eq("companyId", companyId)
    .in("employeeId", employeeIds)
    .gte("clockIn", from);

  const weeklyMs: Record<string, number> = {};
  for (const entry of entries ?? []) {
    const end = entry.clockOut
      ? new Date(entry.clockOut).getTime()
      : Date.now();
    const ms = end - new Date(entry.clockIn).getTime();
    weeklyMs[entry.employeeId] = (weeklyMs[entry.employeeId] ?? 0) + ms;
  }

  return weeklyMs;
}

export async function updateTimeCardEntry(
  client: SupabaseClient<Database>,
  args: {
    entryId: string;
    clockIn?: string;
    clockOut?: string | null;
    note?: string | null;
    updatedBy: string;
  }
) {
  return client
    .from("timeCardEntry")
    .update(
      sanitize({
        clockIn: args.clockIn,
        clockOut: args.clockOut,
        note: args.note,
        updatedBy: args.updatedBy,
        updatedAt: datetime.timestamp()
      })
    )
    .eq("id", args.entryId);
}
/**
 * A time card helper's refusal ("Already clocked in") carries no database
 * code; a database error does.
 */
export function timeCardError(
  ctx: ServiceContext,
  error: { message: string; code?: string },
  message: string
) {
  return "code" in error
    ? ctx.error("internal", message, error)
    : ctx.error("rule", error.message);
}