Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.
TypeScript ai-agentai-resume-analyzerapplication-trackerapplication-tracking-systematscareerjob-applicationjob-automationjob-huntingjob-searchjob-seeker-toolsjob-trackerjob-trackingjobsearchjobseekersmcpollamaresumeresume-reviewself-hosted
refactor(activity): restructure actions into separate modules for better organization and maintainability
Khuram Niaz568b05637e47
diff --git a/src/actions/activity.actions.ts b/src/actions/activity.actions.tsindex 865b98c..5e5f215 100644--- a/src/actions/activity.actions.ts+++ b/src/actions/activity.actions.ts@@ -1,554 +1,24 @@-"use server";-import prisma from "@/lib/db";-import { handleError } from "@/lib/utils";-import { Activity } from "@/models/activity.model";-import { AddActivityFormSchema } from "@/models/addActivityForm.schema";-import { getCurrentUser } from "@/utils/user.utils";-import { APP_CONSTANTS } from "@/lib/constants";-import { z } from "zod";-import { revalidatePath } from "next/cache";-import { differenceInMinutes } from "date-fns";--// One shape for every action that returns the running activity, so the client-// can never receive a copy missing its break state.-const RUNNING_ACTIVITY_SELECT = {- id: true,- activityName: true,- startTime: true,- endTime: true,- description: true,- createdAt: true,- activityType: true,- breakMinutes: true,- breakStartedAt: true,- breakPlannedMins: true,-};--const clampBreakMinutes = (minutes: number) =>- Math.min(- Math.max(minutes, APP_CONSTANTS.ACTIVITY_BREAK_MIN_MINUTES),- APP_CONSTANTS.ACTIVITY_BREAK_MAX_MINUTES,- );--// Rounded, not floored: repeated short breaks would otherwise be lost entirely.-const breakMinutesSince = (start: Date, now: Date = new Date()) =>- Math.max(0, Math.round((now.getTime() - start.getTime()) / 60000));--export const getAllActivityTypes = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const activityTypes = await prisma.activityType.findMany({- where: {- createdBy: user.id,- },- });- return activityTypes;- } catch (error) {- const msg = "Failed to fetch all activity types. ";- return handleError(error, msg);- }-};--export const createActivityType = async (- label: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const value = label.trim().toLowerCase();-- const upsertedActivityType = await prisma.activityType.upsert({- where: { value_createdBy: { value, createdBy: user.id } },- update: { label },- create: { label, value, createdBy: user.id },- });-- return upsertedActivityType;- } catch (error) {- const msg = "Failed to create activity type. ";- console.error(msg, error);- throw new Error(msg);- }-};--export const getActivitiesList = async (- page: number = 1,- limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,- search?: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const offset = (page - 1) * limit;-- const whereClause: any = {- userId: user.id,- endTime: {- not: null,- },- };-- if (search) {- whereClause.OR = [- { activityName: { contains: search } },- { description: { contains: search } },- { activityType: { label: { contains: search } } },- ];- }-- const [data, total] = await Promise.all([- prisma.activity.findMany({- where: whereClause,- select: {- id: true,- activityName: true,- startTime: true,- endTime: true,- duration: true,- description: true,- createdAt: true,- activityType: true,- },- orderBy: {- createdAt: "desc",- },- skip: offset,- take: limit,- }),- prisma.activity.count({- where: whereClause,- }),- ]);-- return {- success: true,- data,- total,- };- } catch (error) {- const msg = "Failed to fetch activities list. ";- return handleError(error, msg);- }-};--export const createActivity = async (- data: Activity-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const {- activityName,- activityType,- startTime,- endTime,- duration,- description,- } = data;-- const activity = await prisma.activity.create({- data: {- activityName,- activityTypeId: activityType as string,- userId: user.id,- startTime,- endTime,- duration,- description,- },- });- revalidatePath("/dashboard");- return { activity, success: true };- } catch (error) {- const msg = "Failed to create activity. ";- return handleError(error, msg);- }-};--export const deleteActivityById = async (- activityId: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const res = await prisma.activity.delete({- where: {- id: activityId,- userId: user.id,- },- });- revalidatePath("/dashboard");- return { res, success: true };- } catch (error) {- const msg = "Failed to delete job.";- return handleError(error, msg);- }-};--export const startActivityById = async (- activityId: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- // Check for existing active activity to prevent concurrent activities- const existingActive = await prisma.activity.findFirst({- where: {- userId: user.id,- endTime: null,- },- });-- if (existingActive) {- return {- success: false,- message: "An activity is already in progress. Stop it before starting a new one.",- };- }-- const activity = await prisma.activity.findFirst({- where: {- id: activityId,- userId: user.id,- },- });-- if (!activity) {- throw new Error("Activity not found");- }- const { activityName, activityTypeId, description } = activity;-- const newActivity = await prisma.activity.create({- data: {- activityName,- activityTypeId,- userId: user.id,- startTime: new Date(),- endTime: null,- description,- },- select: RUNNING_ACTIVITY_SELECT,- });- return { newActivity, success: true };- } catch (error) {- const msg = "Failed to start activity. ";- return handleError(error, msg);- }-};--export const stopActivityById = async (- activityId: string,- endTime: Date,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- // endTime: null — this must never reach an already-saved row, because the- // discard branch below deletes.- const activity = await prisma.activity.findFirst({- where: { id: activityId, userId: user.id, endTime: null },- });-- if (!activity) {- throw new Error("Activity not found");- }-- // Time spent away is never billed as work, even if the user never resumed.- const breakMinutes =- activity.breakMinutes +- (activity.breakStartedAt- ? breakMinutesSince(activity.breakStartedAt, endTime)- : 0);-- // Subtract before capping: capping first double-penalised anything past 8h- // of wall clock and could zero out a real day's work (decision 7).- const workedMinutes =- differenceInMinutes(endTime, activity.startTime) - breakMinutes;- const duration = Math.min(- Math.max(workedMinutes, 0),- APP_CONSTANTS.ACTIVITY_MAX_DURATION_MINUTES,- );-- if (duration < APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES) {- await prisma.activity.delete({- where: { id: activityId, userId: user.id },- });- revalidatePath("/dashboard");- return { success: true, discarded: true };- }-- const stopped = await prisma.activity.update({- where: { id: activityId, userId: user.id },- data: {- endTime,- duration,- breakMinutes,- breakStartedAt: null,- breakPlannedMins: null,- },- });-- revalidatePath("/dashboard");- return { activity: stopped, success: true, discarded: false };- } catch (error) {- const msg = "Failed to stop activity. ";- return handleError(error, msg);- }-};--export const getCurrentActivity = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const activity = await prisma.activity.findFirst({- where: {- userId: user.id,- endTime: null,- },- select: RUNNING_ACTIVITY_SELECT,- });-- if (!activity) {- return { success: false };- }-- return { activity, success: true };- } catch (error) {- const msg = "Failed to get current activity. ";- return handleError(error, msg);- }-};--export const getActivityTypeList = async (- page: number = 1,- limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }-- const skip = (page - 1) * limit;- const whereClause = { createdBy: user.id };-- const [total, durationSums] = await Promise.all([- prisma.activityType.count({ where: whereClause }),- prisma.activity.groupBy({- by: ["activityTypeId"],- where: { userId: user.id, endTime: { not: null } },- _sum: { duration: true },- }),- ]);-- const durationMap = new Map(- durationSums.map((d) => [d.activityTypeId, d._sum.duration ?? 0]),- );-- // Fetch all activity types with counts, then sort by total duration- const allTypes = await prisma.activityType.findMany({- where: whereClause,- select: {- id: true,- label: true,- value: true,- _count: { select: { Activities: true, Tasks: true } },- },- });-- const sorted = allTypes- .map((t) => ({ ...t, totalDuration: durationMap.get(t.id) ?? 0 }))- .sort((a, b) => b.totalDuration - a.totalDuration);-- const data = sorted.slice(skip, skip + limit);-- return { data, total };- } catch (error) {- const msg = "Failed to fetch activity type list. ";- return handleError(error, msg);- }-};--export const deleteActivityTypeById = async (- activityTypeId: string,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();- if (!user) {- throw new Error("Not authenticated");- }-- const [activities, tasks] = await Promise.all([- prisma.activity.count({ where: { activityTypeId, userId: user.id } }),- prisma.task.count({ where: { activityTypeId, userId: user.id } }),- ]);-- if (activities > 0 || tasks > 0) {- const links = [- activities > 0 ? `${activities} activity(ies)` : "",- tasks > 0 ? `${tasks} task(s)` : "",- ]- .filter(Boolean)- .join(" and ");-- throw new Error(- `Activity type cannot be deleted because it is linked to ${links}.`,- );- }-- const res = await prisma.activityType.delete({- where: { id: activityTypeId, createdBy: user.id },- });-- return { res, success: true };- } catch (error) {- const msg = "Failed to delete activity type.";- return handleError(error, msg);- }-};--export const startBreak = async (- activityId: string,- plannedMinutes: number,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const activity = await prisma.activity.findFirst({- where: { id: activityId, userId: user.id, endTime: null },- });-- if (!activity) {- throw new Error("Activity not found");- }-- if (activity.breakStartedAt) {- return { success: false, message: "A break is already in progress." };- }-- const updated = await prisma.activity.update({- where: { id: activityId, userId: user.id },- data: {- breakStartedAt: new Date(),- breakPlannedMins: clampBreakMinutes(plannedMinutes),- },- select: RUNNING_ACTIVITY_SELECT,- });-- return { activity: updated, success: true };- } catch (error) {- const msg = "Failed to start break. ";- return handleError(error, msg);- }-};--export const endBreak = async (- activityId: string,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const activity = await prisma.activity.findFirst({- where: { id: activityId, userId: user.id, endTime: null },- select: RUNNING_ACTIVITY_SELECT,- });-- if (!activity) {- throw new Error("Activity not found");- }-- // Resuming twice (two tabs, or a retry) must not double-count.- if (!activity.breakStartedAt) {- return { activity, success: true };- }-- const updated = await prisma.activity.update({- where: { id: activityId, userId: user.id },- data: {- breakMinutes:- activity.breakMinutes + breakMinutesSince(activity.breakStartedAt),- breakStartedAt: null,- breakPlannedMins: null,- },- select: RUNNING_ACTIVITY_SELECT,- });-- return { activity: updated, success: true };- } catch (error) {- const msg = "Failed to end break. ";- return handleError(error, msg);- }-};--export const updateBreakLength = async (- activityId: string,- plannedMinutes: number,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const activity = await prisma.activity.findFirst({- where: { id: activityId, userId: user.id, endTime: null },- });-- if (!activity?.breakStartedAt) {- return { success: false, message: "No break is in progress." };- }-- const updated = await prisma.activity.update({- where: { id: activityId, userId: user.id },- data: { breakPlannedMins: clampBreakMinutes(plannedMinutes) },- select: RUNNING_ACTIVITY_SELECT,- });-- return { activity: updated, success: true };- } catch (error) {- const msg = "Failed to update break length. ";- return handleError(error, msg);- }-};+// Barrel for the activity server actions, split into src/actions/activity/.+// Each module below carries its own "use server"; this file only re-exports so+// the long-standing "@/actions/activity.actions" import path keeps working.++export {+ getActivitiesList,+ createActivity,+ deleteActivityById,+} from "./activity/activities";++export {+ startActivityById,+ stopActivityById,+ getCurrentActivity,+} from "./activity/timer";++export { startBreak, endBreak, updateBreakLength } from "./activity/breaks";++export {+ getAllActivityTypes,+ createActivityType,+ getActivityTypeList,+ deleteActivityTypeById,+} from "./activity/activityTypes";diff --git a/src/actions/activity/activities.ts b/src/actions/activity/activities.tsnew file mode 100644index 0000000..3334eb6--- /dev/null+++ b/src/actions/activity/activities.ts@@ -0,0 +1,112 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { APP_CONSTANTS } from "@/lib/constants";+import { Activity } from "@/models/activity.model";+import { revalidatePath } from "next/cache";+import { ACTIVITY_LIST_SELECT, requireUser } from "./shared";++export const getActivitiesList = async (+ page: number = 1,+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,+ search?: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const offset = (page - 1) * limit;++ const whereClause: any = {+ userId: user.id,+ endTime: {+ not: null,+ },+ };++ if (search) {+ whereClause.OR = [+ { activityName: { contains: search } },+ { description: { contains: search } },+ { activityType: { label: { contains: search } } },+ ];+ }++ const [data, total] = await Promise.all([+ prisma.activity.findMany({+ where: whereClause,+ select: ACTIVITY_LIST_SELECT,+ orderBy: {+ createdAt: "desc",+ },+ skip: offset,+ take: limit,+ }),+ prisma.activity.count({+ where: whereClause,+ }),+ ]);++ return {+ success: true,+ data,+ total,+ };+ } catch (error) {+ const msg = "Failed to fetch activities list. ";+ return handleError(error, msg);+ }+};++export const createActivity = async (+ data: Activity+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const {+ activityName,+ activityType,+ startTime,+ endTime,+ duration,+ description,+ } = data;++ const activity = await prisma.activity.create({+ data: {+ activityName,+ activityTypeId: activityType as string,+ userId: user.id,+ startTime,+ endTime,+ duration,+ description,+ },+ });+ revalidatePath("/dashboard");+ return { activity, success: true };+ } catch (error) {+ const msg = "Failed to create activity. ";+ return handleError(error, msg);+ }+};++export const deleteActivityById = async (+ activityId: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const res = await prisma.activity.delete({+ where: {+ id: activityId,+ userId: user.id,+ },+ });+ revalidatePath("/dashboard");+ return { res, success: true };+ } catch (error) {+ const msg = "Failed to delete job.";+ return handleError(error, msg);+ }+};diff --git a/src/actions/activity/activityTypes.ts b/src/actions/activity/activityTypes.tsnew file mode 100644index 0000000..23eb832--- /dev/null+++ b/src/actions/activity/activityTypes.ts@@ -0,0 +1,125 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { APP_CONSTANTS } from "@/lib/constants";+import { requireUser } from "./shared";++export const getAllActivityTypes = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const activityTypes = await prisma.activityType.findMany({+ where: {+ createdBy: user.id,+ },+ });+ return activityTypes;+ } catch (error) {+ const msg = "Failed to fetch all activity types. ";+ return handleError(error, msg);+ }+};++export const createActivityType = async (+ label: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const value = label.trim().toLowerCase();++ const upsertedActivityType = await prisma.activityType.upsert({+ where: { value_createdBy: { value, createdBy: user.id } },+ update: { label },+ create: { label, value, createdBy: user.id },+ });++ return upsertedActivityType;+ } catch (error) {+ const msg = "Failed to create activity type. ";+ console.error(msg, error);+ throw new Error(msg);+ }+};++export const getActivityTypeList = async (+ page: number = 1,+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const skip = (page - 1) * limit;+ const whereClause = { createdBy: user.id };++ const [total, durationSums] = await Promise.all([+ prisma.activityType.count({ where: whereClause }),+ prisma.activity.groupBy({+ by: ["activityTypeId"],+ where: { userId: user.id, endTime: { not: null } },+ _sum: { duration: true },+ }),+ ]);++ const durationMap = new Map(+ durationSums.map((d) => [d.activityTypeId, d._sum.duration ?? 0]),+ );++ // Fetch all activity types with counts, then sort by total duration+ const allTypes = await prisma.activityType.findMany({+ where: whereClause,+ select: {+ id: true,+ label: true,+ value: true,+ _count: { select: { Activities: true, Tasks: true } },+ },+ });++ const sorted = allTypes+ .map((t) => ({ ...t, totalDuration: durationMap.get(t.id) ?? 0 }))+ .sort((a, b) => b.totalDuration - a.totalDuration);++ const data = sorted.slice(skip, skip + limit);++ return { data, total };+ } catch (error) {+ const msg = "Failed to fetch activity type list. ";+ return handleError(error, msg);+ }+};++export const deleteActivityTypeById = async (+ activityTypeId: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const [activities, tasks] = await Promise.all([+ prisma.activity.count({ where: { activityTypeId, userId: user.id } }),+ prisma.task.count({ where: { activityTypeId, userId: user.id } }),+ ]);++ if (activities > 0 || tasks > 0) {+ const links = [+ activities > 0 ? `${activities} activity(ies)` : "",+ tasks > 0 ? `${tasks} task(s)` : "",+ ]+ .filter(Boolean)+ .join(" and ");++ throw new Error(+ `Activity type cannot be deleted because it is linked to ${links}.`,+ );+ }++ const res = await prisma.activityType.delete({+ where: { id: activityTypeId, createdBy: user.id },+ });++ return { res, success: true };+ } catch (error) {+ const msg = "Failed to delete activity type.";+ return handleError(error, msg);+ }+};diff --git a/src/actions/activity/breaks.ts b/src/actions/activity/breaks.tsnew file mode 100644index 0000000..e512de5--- /dev/null+++ b/src/actions/activity/breaks.ts@@ -0,0 +1,110 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import {+ RUNNING_ACTIVITY_SELECT,+ breakMinutesSince,+ clampBreakMinutes,+ requireUser,+} from "./shared";++export const startBreak = async (+ activityId: string,+ plannedMinutes: number,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const activity = await prisma.activity.findFirst({+ where: { id: activityId, userId: user.id, endTime: null },+ });++ if (!activity) {+ throw new Error("Activity not found");+ }++ if (activity.breakStartedAt) {+ return { success: false, message: "A break is already in progress." };+ }++ const updated = await prisma.activity.update({+ where: { id: activityId, userId: user.id },+ data: {+ breakStartedAt: new Date(),+ breakPlannedMins: clampBreakMinutes(plannedMinutes),+ },+ select: RUNNING_ACTIVITY_SELECT,+ });++ return { activity: updated, success: true };+ } catch (error) {+ const msg = "Failed to start break. ";+ return handleError(error, msg);+ }+};++export const endBreak = async (+ activityId: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const activity = await prisma.activity.findFirst({+ where: { id: activityId, userId: user.id, endTime: null },+ select: RUNNING_ACTIVITY_SELECT,+ });++ if (!activity) {+ throw new Error("Activity not found");+ }++ // Resuming twice (two tabs, or a retry) must not double-count.+ if (!activity.breakStartedAt) {+ return { activity, success: true };+ }++ const updated = await prisma.activity.update({+ where: { id: activityId, userId: user.id },+ data: {+ breakMinutes:+ activity.breakMinutes + breakMinutesSince(activity.breakStartedAt),+ breakStartedAt: null,+ breakPlannedMins: null,+ },+ select: RUNNING_ACTIVITY_SELECT,+ });++ return { activity: updated, success: true };+ } catch (error) {+ const msg = "Failed to end break. ";+ return handleError(error, msg);+ }+};++export const updateBreakLength = async (+ activityId: string,+ plannedMinutes: number,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const activity = await prisma.activity.findFirst({+ where: { id: activityId, userId: user.id, endTime: null },+ });++ if (!activity?.breakStartedAt) {+ return { success: false, message: "No break is in progress." };+ }++ const updated = await prisma.activity.update({+ where: { id: activityId, userId: user.id },+ data: { breakPlannedMins: clampBreakMinutes(plannedMinutes) },+ select: RUNNING_ACTIVITY_SELECT,+ });++ return { activity: updated, success: true };+ } catch (error) {+ const msg = "Failed to update break length. ";+ return handleError(error, msg);+ }+};diff --git a/src/actions/activity/shared.ts b/src/actions/activity/shared.tsnew file mode 100644index 0000000..abaa439--- /dev/null+++ b/src/actions/activity/shared.ts@@ -0,0 +1,50 @@+import { APP_CONSTANTS } from "@/lib/constants";+import { getCurrentUser } from "@/utils/user.utils";++// Not a "use server" module: it exports selects and sync helpers, so it stays+// internal to src/actions/activity/ and is never imported by a client component.++export const requireUser = async () => {+ const user = await getCurrentUser();+ if (!user) {+ throw new Error("Not authenticated");+ }+ return user;+};++// One shape for every action that returns the running activity, so the client+// can never receive a copy missing its break state.+export const RUNNING_ACTIVITY_SELECT = {+ id: true,+ activityName: true,+ startTime: true,+ endTime: true,+ description: true,+ createdAt: true,+ activityType: true,+ breakMinutes: true,+ breakStartedAt: true,+ breakPlannedMins: true,+};++// Completed activities carry duration but no break state+export const ACTIVITY_LIST_SELECT = {+ id: true,+ activityName: true,+ startTime: true,+ endTime: true,+ duration: true,+ description: true,+ createdAt: true,+ activityType: true,+};++export const clampBreakMinutes = (minutes: number) =>+ Math.min(+ Math.max(minutes, APP_CONSTANTS.ACTIVITY_BREAK_MIN_MINUTES),+ APP_CONSTANTS.ACTIVITY_BREAK_MAX_MINUTES,+ );++// Rounded, not floored: repeated short breaks would otherwise be lost entirely.+export const breakMinutesSince = (start: Date, now: Date = new Date()) =>+ Math.max(0, Math.round((now.getTime() - start.getTime()) / 60000));diff --git a/src/actions/activity/timer.ts b/src/actions/activity/timer.tsnew file mode 100644index 0000000..f07e5d3--- /dev/null+++ b/src/actions/activity/timer.ts@@ -0,0 +1,145 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { APP_CONSTANTS } from "@/lib/constants";+import { revalidatePath } from "next/cache";+import { differenceInMinutes } from "date-fns";+import {+ RUNNING_ACTIVITY_SELECT,+ breakMinutesSince,+ requireUser,+} from "./shared";++export const startActivityById = async (+ activityId: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ // Check for existing active activity to prevent concurrent activities+ const existingActive = await prisma.activity.findFirst({+ where: {+ userId: user.id,+ endTime: null,+ },+ });++ if (existingActive) {+ return {+ success: false,+ message: "An activity is already in progress. Stop it before starting a new one.",+ };+ }++ const activity = await prisma.activity.findFirst({+ where: {+ id: activityId,+ userId: user.id,+ },+ });++ if (!activity) {+ throw new Error("Activity not found");+ }+ const { activityName, activityTypeId, description } = activity;++ const newActivity = await prisma.activity.create({+ data: {+ activityName,+ activityTypeId,+ userId: user.id,+ startTime: new Date(),+ endTime: null,+ description,+ },+ select: RUNNING_ACTIVITY_SELECT,+ });+ return { newActivity, success: true };+ } catch (error) {+ const msg = "Failed to start activity. ";+ return handleError(error, msg);+ }+};++export const stopActivityById = async (+ activityId: string,+ endTime: Date,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ // endTime: null — this must never reach an already-saved row, because the+ // discard branch below deletes.+ const activity = await prisma.activity.findFirst({+ where: { id: activityId, userId: user.id, endTime: null },+ });++ if (!activity) {+ throw new Error("Activity not found");+ }++ // Time spent away is never billed as work, even if the user never resumed.+ const breakMinutes =+ activity.breakMinutes ++ (activity.breakStartedAt+ ? breakMinutesSince(activity.breakStartedAt, endTime)+ : 0);++ // Subtract before capping: capping first double-penalised anything past 8h+ // of wall clock and could zero out a real day's work (decision 7).+ const workedMinutes =+ differenceInMinutes(endTime, activity.startTime) - breakMinutes;+ const duration = Math.min(+ Math.max(workedMinutes, 0),+ APP_CONSTANTS.ACTIVITY_MAX_DURATION_MINUTES,+ );++ if (duration < APP_CONSTANTS.ACTIVITY_MIN_DURATION_MINUTES) {+ await prisma.activity.delete({+ where: { id: activityId, userId: user.id },+ });+ revalidatePath("/dashboard");+ return { success: true, discarded: true };+ }++ const stopped = await prisma.activity.update({+ where: { id: activityId, userId: user.id },+ data: {+ endTime,+ duration,+ breakMinutes,+ breakStartedAt: null,+ breakPlannedMins: null,+ },+ });++ revalidatePath("/dashboard");+ return { activity: stopped, success: true, discarded: false };+ } catch (error) {+ const msg = "Failed to stop activity. ";+ return handleError(error, msg);+ }+};++export const getCurrentActivity = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const activity = await prisma.activity.findFirst({+ where: {+ userId: user.id,+ endTime: null,+ },+ select: RUNNING_ACTIVITY_SELECT,+ });++ if (!activity) {+ return { success: false };+ }++ return { activity, success: true };+ } catch (error) {+ const msg = "Failed to get current activity. ";+ return handleError(error, msg);+ }+};