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 task actions into separate modules for better organization and maintainability; add company actions for CRUD operations; implement dashboard actions for activity and job statistics; introduce shared utility functions for date handling.
Khuram Niaz6a1d6c855552
diff --git a/src/actions/company.actions.ts b/src/actions/company.actions.tsindex 55579dd..28dc4d5 100644--- a/src/actions/company.actions.ts+++ b/src/actions/company.actions.ts@@ -1,347 +1,15 @@-"use server";-import prisma from "@/lib/db";-import { handleError } from "@/lib/utils";-import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";-import { AddCompanyFormSchema } from "@/models/addCompanyForm.schema";-import { getCurrentUser } from "@/utils/user.utils";-import { APP_CONSTANTS } from "@/lib/constants";-import { revalidatePath } from "next/cache";-import { z } from "zod";--export const getCompanyList = async (- page: number = 1,- limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,- countBy?: string,- search?: string,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }- const skip = (page - 1) * limit;-- const whereClause: any = {- createdBy: user.id,- };-- if (search) {- whereClause.label = { contains: search };- }-- const [data, total, rejectedCounts, totalCounts] = await Promise.all([- prisma.company.findMany({- where: whereClause,- skip,- take: limit,- ...(countBy- ? {- select: {- id: true,- label: true,- value: true,- logoUrl: true,- _count: {- select: {- jobsApplied: {- where: {- applied: true,- },- },- },- },- },- }- : {}),- orderBy: {- jobsApplied: {- _count: "desc",- },- },- }),- prisma.company.count({- where: whereClause,- }),- countBy- ? prisma.job.groupBy({- by: ["companyId"],- where: {- userId: user.id,- Status: { value: "rejected" },- },- _count: { id: true },- })- : Promise.resolve([]),- countBy- ? prisma.job.groupBy({- by: ["companyId"],- where: {- userId: user.id,- },- _count: { id: true },- })- : Promise.resolve([]),- ]);-- const rejectedMap = new Map(- (rejectedCounts as { companyId: string; _count: { id: number } }[]).map(- (r) => [r.companyId, r._count.id],- ),- );-- const totalMap = new Map(- (totalCounts as { companyId: string; _count: { id: number } }[]).map(- (r) => [r.companyId, r._count.id],- ),- );-- const dataWithRejected = countBy- ? (data as any[]).map((company) => ({- ...company,- _count: {- ...(company._count ?? {}),- jobsRejected: rejectedMap.get(company.id) ?? 0,- jobsTotal: totalMap.get(company.id) ?? 0,- },- }))- : data;-- return { data: dataWithRejected, total };- } catch (error) {- const msg = "Failed to fetch company list. ";- return handleError(error, msg);- }-};--export const getAllCompanies = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const comapnies = await prisma.company.findMany({- where: {- createdBy: user.id,- },- });- return comapnies;- } catch (error) {- const msg = "Failed to fetch all companies. ";- return handleError(error, msg);- }-};--const isValidImageUrl = (url: string): boolean => {- if (!url) return true;- if (url.startsWith("/")) return true;- try {- const urlObj = new URL(url);- if (!["http:", "https:"].includes(urlObj.protocol)) {- return false;- }- return true;- } catch {- return false;- }-};--export const addCompany = async (- data: z.infer<typeof AddCompanyFormSchema>,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const { company, logoUrl } = data;-- // Validate image URL- if (logoUrl && !isValidImageUrl(logoUrl)) {- throw new Error(- "Invalid logo URL. Only http and https protocols are allowed.",- );- }-- const value = canonicalizeEntityValue(company.trim(), { stripLegalSuffix: true });-- const companyExists = await prisma.company.findFirst({- where: {- value,- createdBy: user.id,- },- });-- if (companyExists) {- throw new Error("Company already exists!");- }-- const res = await prisma.company.create({- data: {- createdBy: user.id,- value,- label: company,- logoUrl,- },- });- revalidatePath("/dashboard/myjobs", "page");- return { success: true, data: res };- } catch (error) {- const msg = "Failed to create company.";- return handleError(error, msg);- }-};--export const updateCompany = async (- data: z.infer<typeof AddCompanyFormSchema>,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const { id, company, logoUrl, createdBy } = data;-- if (!id) {- throw new Error("Company id is required");- }-- // Validate image URL- if (logoUrl && !isValidImageUrl(logoUrl)) {- throw new Error(- "Invalid logo URL. Only http and https protocols are allowed.",- );- }-- const existingCompany = await prisma.company.findFirst({- where: {- id,- createdBy: user.id,- },- });-- if (!existingCompany) {- throw new Error("Company not found");- }-- const trimmedLabel = company.trim();-- // Only recompute the match key when the label actually changed. Some- // rows (e.g. mock-seeded companies) intentionally hold a `value` that- // isn't derivable from their label — recomputing on every save would- // collide with an unrelated company sharing the same canonical label.- let value = existingCompany.value;- if (trimmedLabel !== existingCompany.label) {- value = canonicalizeEntityValue(trimmedLabel, { stripLegalSuffix: true });-- const companyExists = await prisma.company.findFirst({- where: {- value,- createdBy: user.id,- },- });-- if (companyExists && companyExists.id !== id) {- throw new Error("Company already exists!");- }- }-- const res = await prisma.company.update({- where: {- id,- createdBy: user.id,- },- data: {- value,- label: company,- logoUrl,- },- });-- return { success: true, data: res };- } catch (error) {- const msg = "Failed to update company.";- return handleError(error, msg);- }-};--export const getCompanyById = async (- companyId: string,-): Promise<any | undefined> => {- try {- if (!companyId) {- throw new Error("Please provide company id");- }- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const company = await prisma.company.findUnique({- where: {- id: companyId,- createdBy: user.id,- },- });- return company;- } catch (error) {- const msg = "Failed to fetch company by Id. ";- console.error(msg);- if (error instanceof Error) {- return { success: false, message: error.message };- }- }-};--export const deleteCompanyById = async (- companyId: string,-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const experiences = await prisma.workExperience.count({- where: {- companyId,- },- });- if (experiences > 0) {- throw new Error(- `Company cannot be deleted due to its use in experience section of one of the resume! `,- );- }- const jobs = await prisma.job.count({- where: {- companyId,- userId: user.id,- },- });-- if (jobs > 0) {- throw new Error(- `Company cannot be deleted due to ${jobs} number of associated jobs! `,- );- }-- const res = await prisma.company.delete({- where: {- id: companyId,- createdBy: user.id,- },- });- return { res, success: true };- } catch (error) {- const msg = "Failed to delete company.";- return handleError(error, msg);- }-};+// Barrel for the company server actions, split into src/actions/company/.+// Each module below carries its own "use server"; this file only re-exports so+// the long-standing "@/actions/company.actions" import path keeps working.++export {+ getCompanyList,+ getAllCompanies,+ getCompanyById,+} from "./company/queries";++export {+ addCompany,+ updateCompany,+ deleteCompanyById,+} from "./company/mutations";diff --git a/src/actions/company/mutations.ts b/src/actions/company/mutations.tsnew file mode 100644index 0000000..d8b41fc--- /dev/null+++ b/src/actions/company/mutations.ts@@ -0,0 +1,179 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { canonicalizeEntityValue } from "@/lib/jobs/canonicalize";+import { AddCompanyFormSchema } from "@/models/addCompanyForm.schema";+import { revalidatePath } from "next/cache";+import { z } from "zod";+import { requireUser } from "../shared";++const isValidImageUrl = (url: string): boolean => {+ if (!url) return true;+ if (url.startsWith("/")) return true;+ try {+ const urlObj = new URL(url);+ if (!["http:", "https:"].includes(urlObj.protocol)) {+ return false;+ }+ return true;+ } catch {+ return false;+ }+};++export const addCompany = async (+ data: z.infer<typeof AddCompanyFormSchema>,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const { company, logoUrl } = data;++ // Validate image URL+ if (logoUrl && !isValidImageUrl(logoUrl)) {+ throw new Error(+ "Invalid logo URL. Only http and https protocols are allowed.",+ );+ }++ const value = canonicalizeEntityValue(company.trim(), { stripLegalSuffix: true });++ const companyExists = await prisma.company.findFirst({+ where: {+ value,+ createdBy: user.id,+ },+ });++ if (companyExists) {+ throw new Error("Company already exists!");+ }++ const res = await prisma.company.create({+ data: {+ createdBy: user.id,+ value,+ label: company,+ logoUrl,+ },+ });+ revalidatePath("/dashboard/myjobs", "page");+ return { success: true, data: res };+ } catch (error) {+ const msg = "Failed to create company.";+ return handleError(error, msg);+ }+};++export const updateCompany = async (+ data: z.infer<typeof AddCompanyFormSchema>,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const { id, company, logoUrl, createdBy } = data;++ if (!id) {+ throw new Error("Company id is required");+ }++ // Validate image URL+ if (logoUrl && !isValidImageUrl(logoUrl)) {+ throw new Error(+ "Invalid logo URL. Only http and https protocols are allowed.",+ );+ }++ const existingCompany = await prisma.company.findFirst({+ where: {+ id,+ createdBy: user.id,+ },+ });++ if (!existingCompany) {+ throw new Error("Company not found");+ }++ const trimmedLabel = company.trim();++ // Only recompute the match key when the label actually changed. Some+ // rows (e.g. mock-seeded companies) intentionally hold a `value` that+ // isn't derivable from their label — recomputing on every save would+ // collide with an unrelated company sharing the same canonical label.+ let value = existingCompany.value;+ if (trimmedLabel !== existingCompany.label) {+ value = canonicalizeEntityValue(trimmedLabel, { stripLegalSuffix: true });++ const companyExists = await prisma.company.findFirst({+ where: {+ value,+ createdBy: user.id,+ },+ });++ if (companyExists && companyExists.id !== id) {+ throw new Error("Company already exists!");+ }+ }++ const res = await prisma.company.update({+ where: {+ id,+ createdBy: user.id,+ },+ data: {+ value,+ label: company,+ logoUrl,+ },+ });++ return { success: true, data: res };+ } catch (error) {+ const msg = "Failed to update company.";+ return handleError(error, msg);+ }+};++export const deleteCompanyById = async (+ companyId: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const experiences = await prisma.workExperience.count({+ where: {+ companyId,+ },+ });+ if (experiences > 0) {+ throw new Error(+ `Company cannot be deleted due to its use in experience section of one of the resume! `,+ );+ }+ const jobs = await prisma.job.count({+ where: {+ companyId,+ userId: user.id,+ },+ });++ if (jobs > 0) {+ throw new Error(+ `Company cannot be deleted due to ${jobs} number of associated jobs! `,+ );+ }++ const res = await prisma.company.delete({+ where: {+ id: companyId,+ createdBy: user.id,+ },+ });+ return { res, success: true };+ } catch (error) {+ const msg = "Failed to delete company.";+ return handleError(error, msg);+ }+};diff --git a/src/actions/company/queries.ts b/src/actions/company/queries.tsnew file mode 100644index 0000000..c6c85ff--- /dev/null+++ b/src/actions/company/queries.ts@@ -0,0 +1,156 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { APP_CONSTANTS } from "@/lib/constants";+import { requireUser } from "../shared";++type JobCountGroup = { companyId: string; _count: { id: number } };++const COMPANY_WITH_APPLIED_COUNT_SELECT = {+ id: true,+ label: true,+ value: true,+ logoUrl: true,+ _count: {+ select: {+ jobsApplied: {+ where: {+ applied: true,+ },+ },+ },+ },+};++// Prisma can only count the `applied` relation inline, so the rejected and+// total tallies come from separate groupBy queries and are spliced on here.+const attachJobCounts = (+ data: any[],+ rejectedCounts: JobCountGroup[],+ totalCounts: JobCountGroup[],+) => {+ const rejectedMap = new Map(+ rejectedCounts.map((r) => [r.companyId, r._count.id]),+ );++ const totalMap = new Map(totalCounts.map((r) => [r.companyId, r._count.id]));++ return data.map((company) => ({+ ...company,+ _count: {+ ...(company._count ?? {}),+ jobsRejected: rejectedMap.get(company.id) ?? 0,+ jobsTotal: totalMap.get(company.id) ?? 0,+ },+ }));+};++export const getCompanyList = async (+ page: number = 1,+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,+ countBy?: string,+ search?: string,+): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ const skip = (page - 1) * limit;++ const whereClause: any = {+ createdBy: user.id,+ };++ if (search) {+ whereClause.label = { contains: search };+ }++ const [data, total, rejectedCounts, totalCounts] = await Promise.all([+ prisma.company.findMany({+ where: whereClause,+ skip,+ take: limit,+ ...(countBy ? { select: COMPANY_WITH_APPLIED_COUNT_SELECT } : {}),+ orderBy: {+ jobsApplied: {+ _count: "desc",+ },+ },+ }),+ prisma.company.count({+ where: whereClause,+ }),+ countBy+ ? prisma.job.groupBy({+ by: ["companyId"],+ where: {+ userId: user.id,+ Status: { value: "rejected" },+ },+ _count: { id: true },+ })+ : Promise.resolve([]),+ countBy+ ? prisma.job.groupBy({+ by: ["companyId"],+ where: {+ userId: user.id,+ },+ _count: { id: true },+ })+ : Promise.resolve([]),+ ]);++ const dataWithRejected = countBy+ ? attachJobCounts(+ data as any[],+ rejectedCounts as JobCountGroup[],+ totalCounts as JobCountGroup[],+ )+ : data;++ return { data: dataWithRejected, total };+ } catch (error) {+ const msg = "Failed to fetch company list. ";+ return handleError(error, msg);+ }+};++export const getAllCompanies = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const companies = await prisma.company.findMany({+ where: {+ createdBy: user.id,+ },+ });+ return companies;+ } catch (error) {+ const msg = "Failed to fetch all companies. ";+ return handleError(error, msg);+ }+};++export const getCompanyById = async (+ companyId: string,+): Promise<any | undefined> => {+ try {+ if (!companyId) {+ throw new Error("Please provide company id");+ }+ const user = await requireUser();++ const company = await prisma.company.findUnique({+ where: {+ id: companyId,+ createdBy: user.id,+ },+ });+ return company;+ } catch (error) {+ const msg = "Failed to fetch company by Id. ";+ console.error(msg);+ if (error instanceof Error) {+ return { success: false, message: error.message };+ }+ }+};diff --git a/src/actions/dashboard.actions.ts b/src/actions/dashboard.actions.tsindex 6af39e9..688d6f7 100644--- a/src/actions/dashboard.actions.ts+++ b/src/actions/dashboard.actions.ts@@ -1,376 +1,18 @@-import { APP_CONSTANTS } from "@/lib/constants";-import prisma from "@/lib/db";-import { calculatePercentageDifference, getLast7Days } from "@/lib/utils";-import { getCurrentUser } from "@/utils/user.utils";-import { Prisma } from "@prisma/client";-import { format, parseISO, subDays } from "date-fns";--// Local-time day range: start at 00:00 daysBack days ago, end today 23:59:59.999-const getLocalDayRange = (daysBack: number): { start: Date; end: Date } => {- const now = new Date();- const end = new Date(- now.getFullYear(),- now.getMonth(),- now.getDate(),- 23,- 59,- 59,- 999,- );- const start = new Date(- now.getFullYear(),- now.getMonth(),- now.getDate() - daysBack,- 0,- 0,- 0,- 0,- );- return { start, end };-};--export const getJobsAppliedForPeriod = async (- daysAgo: number,-): Promise<any | undefined> => {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- try {- const startDate1 = subDays(new Date(), daysAgo);- const startDate2 = subDays(new Date(), daysAgo * 2);- const endDate = new Date();- const query = (date: Date): Prisma.JobCountArgs => ({- where: {- userId: user.id,- applied: true,- appliedDate: {- gte: date,- lt: endDate,- },- },- });-- const [count, count2] = await prisma.$transaction([- prisma.job.count(query(startDate1)),- prisma.job.count(query(startDate2)),- ]);- const difference = Math.abs(count2 - count);- const trend = calculatePercentageDifference(difference, count);- return { count, trend };- } catch (error) {- const msg = "Failed to calculate job count";- console.error(msg, error);- throw new Error(msg);- }-};--export const getRecentJobs = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }- const list = await prisma.job.findMany({- where: {- userId: user.id,- applied: true,- },- include: {- JobSource: true,- JobTitle: true,- Company: true,- Status: true,- Location: true,- },- orderBy: {- appliedDate: "desc",- },- take: APP_CONSTANTS.RECENT_NUM_JOBS_ACTIVITIES,- });- return list;- } catch (error) {- const msg = "Failed to fetch jobs list. ";- console.error(msg, error);- throw new Error(msg);- }-};--export const getActivityDataForPeriod = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }- // Use local time for date range to match grouping and getLast7Days- const { start: sevenDaysAgo, end: today } = getLocalDayRange(6);- const activities = await prisma.activity.findMany({- where: {- userId: user.id,- startTime: {- gte: sevenDaysAgo,- lte: today,- },- },- select: {- startTime: true,- duration: true,- activityType: {- select: {- label: true,- },- },- },- orderBy: {- startTime: "asc",- },- });- const groupedData = activities.reduce((acc: any, activity: any) => {- // Use local date for grouping to match user's perception- const activityDate = new Date(activity.startTime);- const day = format(activityDate, "yyyy-MM-dd");- const activityTypeLabel = activity.activityType?.label || "Unknown";-- if (!acc[day]) {- acc[day] = {};- }-- const durationInHours = (activity.duration || 0) / 60;- acc[day][activityTypeLabel] =- (acc[day][activityTypeLabel] || 0) + durationInHours;-- return acc;- }, {});- const last7Days = getLast7Days("yyyy-MM-dd");- const result = last7Days.map((dateStr) => ({- day: format(parseISO(dateStr), "EEE, MMM d"),- ...groupedData[dateStr],- }));- return result;- } catch (error) {- const msg = "Failed to fetch activities data.";- console.error(msg, error);- throw new Error(msg);- }-};--export const getJobsActivityForPeriod = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }- // Use local time for date range to match grouping and getLast7Days- const { start: sevenDaysAgo, end: today } = getLocalDayRange(6);- const jobData = await prisma.job.groupBy({- by: "appliedDate",- _count: {- _all: true,- },- where: {- userId: user.id,- applied: true,- appliedDate: {- gte: sevenDaysAgo,- lte: today,- },- },- orderBy: {- appliedDate: "asc",- },- });- // Reduce to a format that groups by unique date (YYYY-MM-DD) using local time- const groupedPosts = jobData.reduce((acc: any, post: any) => {- if (!post.appliedDate) return acc;- const date = format(new Date(post.appliedDate), "yyyy-MM-dd");- acc[date] = (acc[date] || 0) + post._count._all;- return acc;- }, {});- // Get the last 7 days in local time- const last7Days = getLast7Days("yyyy-MM-dd");- // Map to ensure all dates are represented with a count of 0 if necessary- const result = last7Days.map((dateStr) => ({- day: format(parseISO(dateStr), "EEE, MMM d"),- value: groupedPosts[dateStr] || 0,- }));-- return result;- } catch (error) {- const msg = "Failed to fetch jobs list. ";- console.error(msg, error);- throw new Error(msg);- }-};--export interface TopActivityType {- label: string;- hours: number;-}--export const getTopActivityTypesByDuration = async (- daysAgo: number,-): Promise<TopActivityType[]> => {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- try {- const { start: startDate, end: today } = getLocalDayRange(daysAgo - 1);-- const activities = await prisma.activity.findMany({- where: {- userId: user.id,- startTime: {- gte: startDate,- lte: today,- },- },- select: {- duration: true,- activityType: {- select: {- label: true,- },- },- },- });-- const groupedByType = activities.reduce(- (acc: Record<string, number>, activity) => {- const label = activity.activityType?.label || "Unknown";- const durationInHours = (activity.duration || 0) / 60;- acc[label] = (acc[label] || 0) + durationInHours;- return acc;- },- {},- );-- const sorted = Object.entries(groupedByType)- .map(([label, hours]) => ({ label, hours: Math.round(hours * 10) / 10 }))- .sort((a, b) => b.hours - a.hours)- .slice(0, 3);-- return sorted;- } catch (error) {- const msg = "Failed to fetch top activity types";- console.error(msg, error);- throw new Error(msg);- }-};--export const getRecentActivities = async () => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }- const list = await prisma.activity.findMany({- where: {- userId: user.id,- endTime: { not: null },- },- include: {- activityType: true,- },- orderBy: {- endTime: "desc",- },- take: APP_CONSTANTS.RECENT_NUM_JOBS_ACTIVITIES,- });- return list;- } catch (error) {- const msg = "Failed to fetch recent activities.";- console.error(msg, error);- throw new Error(msg);- }-};--export const getActivityCalendarData = async (): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }- // Use local time for date range to match grouping- const { start: daysAgo, end: today } = getLocalDayRange(365);- const jobData = await prisma.job.groupBy({- by: "appliedDate",- _count: {- _all: true,- },- where: {- userId: user.id,- applied: true,- appliedDate: {- gte: daysAgo,- lte: today,- },- },- orderBy: {- appliedDate: "asc",- },- });-- const activityData = await prisma.activity.findMany({- where: {- userId: user.id,- startTime: { gte: daysAgo, lte: today },- duration: { not: null },- },- select: { startTime: true, duration: true },- });-- const groupedJobs: Record<string, number> = jobData.reduce(- (acc: Record<string, number>, job: any) => {- if (!job.appliedDate) return acc;- const date = format(new Date(job.appliedDate), "yyyy-MM-dd");- acc[date] = (acc[date] || 0) + job._count._all;- return acc;- },- {},- );-- const groupedHours: Record<string, number> = activityData.reduce(- (acc: Record<string, number>, activity) => {- const date = format(new Date(activity.startTime), "yyyy-MM-dd");- acc[date] = (acc[date] || 0) + (activity.duration || 0) / 60;- return acc;- },- {},- );-- const allDates = new Set([- ...Object.keys(groupedJobs),- ...Object.keys(groupedHours),- ]);-- const groupedByYear = [...allDates].reduce(- (acc: Record<string, any[]>, date) => {- const year = date.split("-")[0];- if (!acc[year]) acc[year] = [];- acc[year].push({- day: date,- value: groupedJobs[date] || 0,- hours: Math.round((groupedHours[date] || 0) * 10) / 10,- });- return acc;- },- {},- );-- return groupedByYear;- } catch (error) {- const msg = "Failed to fetch jobs list. ";- console.error(msg, error);- throw new Error(msg);- }-};+// Barrel for the dashboard data functions, split into src/actions/dashboard/.+// Unlike the other action barrels this file and its modules carry no+// "use server": these are plain server-side reads called from the dashboard+// page, and TopActivityType is a type export a client component imports.++export {+ getJobsAppliedForPeriod,+ getTopActivityTypesByDuration,+} from "./dashboard/stats";+export type { TopActivityType } from "./dashboard/stats";++export { getRecentJobs, getRecentActivities } from "./dashboard/recent";++export {+ getActivityDataForPeriod,+ getJobsActivityForPeriod,+ getActivityCalendarData,+} from "./dashboard/charts";diff --git a/src/actions/dashboard/charts.ts b/src/actions/dashboard/charts.tsnew file mode 100644index 0000000..e8f60c2--- /dev/null+++ b/src/actions/dashboard/charts.ts@@ -0,0 +1,183 @@+import prisma from "@/lib/db";+import { getLast7Days } from "@/lib/utils";+import { format, parseISO } from "date-fns";+import { requireUser } from "../shared";+import { getLocalDayRange } from "./shared";++export const getActivityDataForPeriod = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ // Use local time for date range to match grouping and getLast7Days+ const { start: sevenDaysAgo, end: today } = getLocalDayRange(6);+ const activities = await prisma.activity.findMany({+ where: {+ userId: user.id,+ startTime: {+ gte: sevenDaysAgo,+ lte: today,+ },+ },+ select: {+ startTime: true,+ duration: true,+ activityType: {+ select: {+ label: true,+ },+ },+ },+ orderBy: {+ startTime: "asc",+ },+ });+ const groupedData = activities.reduce((acc: any, activity: any) => {+ // Use local date for grouping to match user's perception+ const activityDate = new Date(activity.startTime);+ const day = format(activityDate, "yyyy-MM-dd");+ const activityTypeLabel = activity.activityType?.label || "Unknown";++ if (!acc[day]) {+ acc[day] = {};+ }++ const durationInHours = (activity.duration || 0) / 60;+ acc[day][activityTypeLabel] =+ (acc[day][activityTypeLabel] || 0) + durationInHours;++ return acc;+ }, {});+ const last7Days = getLast7Days("yyyy-MM-dd");+ const result = last7Days.map((dateStr) => ({+ day: format(parseISO(dateStr), "EEE, MMM d"),+ ...groupedData[dateStr],+ }));+ return result;+ } catch (error) {+ const msg = "Failed to fetch activities data.";+ console.error(msg, error);+ throw new Error(msg);+ }+};++export const getJobsActivityForPeriod = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ // Use local time for date range to match grouping and getLast7Days+ const { start: sevenDaysAgo, end: today } = getLocalDayRange(6);+ const jobData = await prisma.job.groupBy({+ by: "appliedDate",+ _count: {+ _all: true,+ },+ where: {+ userId: user.id,+ applied: true,+ appliedDate: {+ gte: sevenDaysAgo,+ lte: today,+ },+ },+ orderBy: {+ appliedDate: "asc",+ },+ });+ // Reduce to a format that groups by unique date (YYYY-MM-DD) using local time+ const groupedPosts = jobData.reduce((acc: any, post: any) => {+ if (!post.appliedDate) return acc;+ const date = format(new Date(post.appliedDate), "yyyy-MM-dd");+ acc[date] = (acc[date] || 0) + post._count._all;+ return acc;+ }, {});+ // Get the last 7 days in local time+ const last7Days = getLast7Days("yyyy-MM-dd");+ // Map to ensure all dates are represented with a count of 0 if necessary+ const result = last7Days.map((dateStr) => ({+ day: format(parseISO(dateStr), "EEE, MMM d"),+ value: groupedPosts[dateStr] || 0,+ }));++ return result;+ } catch (error) {+ const msg = "Failed to fetch jobs list. ";+ console.error(msg, error);+ throw new Error(msg);+ }+};++export const getActivityCalendarData = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ // Use local time for date range to match grouping+ const { start: daysAgo, end: today } = getLocalDayRange(365);+ const jobData = await prisma.job.groupBy({+ by: "appliedDate",+ _count: {+ _all: true,+ },+ where: {+ userId: user.id,+ applied: true,+ appliedDate: {+ gte: daysAgo,+ lte: today,+ },+ },+ orderBy: {+ appliedDate: "asc",+ },+ });++ const activityData = await prisma.activity.findMany({+ where: {+ userId: user.id,+ startTime: { gte: daysAgo, lte: today },+ duration: { not: null },+ },+ select: { startTime: true, duration: true },+ });++ const groupedJobs: Record<string, number> = jobData.reduce(+ (acc: Record<string, number>, job: any) => {+ if (!job.appliedDate) return acc;+ const date = format(new Date(job.appliedDate), "yyyy-MM-dd");+ acc[date] = (acc[date] || 0) + job._count._all;+ return acc;+ },+ {},+ );++ const groupedHours: Record<string, number> = activityData.reduce(+ (acc: Record<string, number>, activity) => {+ const date = format(new Date(activity.startTime), "yyyy-MM-dd");+ acc[date] = (acc[date] || 0) + (activity.duration || 0) / 60;+ return acc;+ },+ {},+ );++ const allDates = new Set([+ ...Object.keys(groupedJobs),+ ...Object.keys(groupedHours),+ ]);++ const groupedByYear = [...allDates].reduce(+ (acc: Record<string, any[]>, date) => {+ const year = date.split("-")[0];+ if (!acc[year]) acc[year] = [];+ acc[year].push({+ day: date,+ value: groupedJobs[date] || 0,+ hours: Math.round((groupedHours[date] || 0) * 10) / 10,+ });+ return acc;+ },+ {},+ );++ return groupedByYear;+ } catch (error) {+ const msg = "Failed to fetch jobs list. ";+ console.error(msg, error);+ throw new Error(msg);+ }+};diff --git a/src/actions/dashboard/recent.ts b/src/actions/dashboard/recent.tsnew file mode 100644index 0000000..1f4dcec--- /dev/null+++ b/src/actions/dashboard/recent.ts@@ -0,0 +1,55 @@+import { APP_CONSTANTS } from "@/lib/constants";+import prisma from "@/lib/db";+import { requireUser } from "../shared";++export const getRecentJobs = async (): Promise<any | undefined> => {+ try {+ const user = await requireUser();+ const list = await prisma.job.findMany({+ where: {+ userId: user.id,+ applied: true,+ },+ include: {+ JobSource: true,+ JobTitle: true,+ Company: true,+ Status: true,+ Location: true,+ },+ orderBy: {+ appliedDate: "desc",+ },+ take: APP_CONSTANTS.RECENT_NUM_JOBS_ACTIVITIES,+ });+ return list;+ } catch (error) {+ const msg = "Failed to fetch jobs list. ";+ console.error(msg, error);+ throw new Error(msg);+ }+};++export const getRecentActivities = async () => {+ try {+ const user = await requireUser();+ const list = await prisma.activity.findMany({+ where: {+ userId: user.id,+ endTime: { not: null },+ },+ include: {+ activityType: true,+ },+ orderBy: {+ endTime: "desc",+ },+ take: APP_CONSTANTS.RECENT_NUM_JOBS_ACTIVITIES,+ });+ return list;+ } catch (error) {+ const msg = "Failed to fetch recent activities.";+ console.error(msg, error);+ throw new Error(msg);+ }+};diff --git a/src/actions/dashboard/shared.ts b/src/actions/dashboard/shared.tsnew file mode 100644index 0000000..314a5cc--- /dev/null+++ b/src/actions/dashboard/shared.ts@@ -0,0 +1,25 @@+// Local-time day range: start at 00:00 daysBack days ago, end today 23:59:59.999+export const getLocalDayRange = (+ daysBack: number,+): { start: Date; end: Date } => {+ const now = new Date();+ const end = new Date(+ now.getFullYear(),+ now.getMonth(),+ now.getDate(),+ 23,+ 59,+ 59,+ 999,+ );+ const start = new Date(+ now.getFullYear(),+ now.getMonth(),+ now.getDate() - daysBack,+ 0,+ 0,+ 0,+ 0,+ );+ return { start, end };+};diff --git a/src/actions/dashboard/stats.ts b/src/actions/dashboard/stats.tsnew file mode 100644index 0000000..3050535--- /dev/null+++ b/src/actions/dashboard/stats.ts@@ -0,0 +1,97 @@+import prisma from "@/lib/db";+import { calculatePercentageDifference } from "@/lib/utils";+import { Prisma } from "@prisma/client";+import { subDays } from "date-fns";+import { requireUser } from "../shared";+import { getLocalDayRange } from "./shared";++export interface TopActivityType {+ label: string;+ hours: number;+}++// Auth guard sits outside the try so an unauthenticated call surfaces+// "Not authenticated" rather than this function's generic message.+export const getJobsAppliedForPeriod = async (+ daysAgo: number,+): Promise<any | undefined> => {+ const user = await requireUser();++ try {+ const startDate1 = subDays(new Date(), daysAgo);+ const startDate2 = subDays(new Date(), daysAgo * 2);+ const endDate = new Date();+ const query = (date: Date): Prisma.JobCountArgs => ({+ where: {+ userId: user.id,+ applied: true,+ appliedDate: {+ gte: date,+ lt: endDate,+ },+ },+ });++ const [count, count2] = await prisma.$transaction([+ prisma.job.count(query(startDate1)),+ prisma.job.count(query(startDate2)),+ ]);+ const difference = Math.abs(count2 - count);+ const trend = calculatePercentageDifference(difference, count);+ return { count, trend };+ } catch (error) {+ const msg = "Failed to calculate job count";+ console.error(msg, error);+ throw new Error(msg);+ }+};++// Auth guard sits outside the try, as above.+export const getTopActivityTypesByDuration = async (+ daysAgo: number,+): Promise<TopActivityType[]> => {+ const user = await requireUser();++ try {+ const { start: startDate, end: today } = getLocalDayRange(daysAgo - 1);++ const activities = await prisma.activity.findMany({+ where: {+ userId: user.id,+ startTime: {+ gte: startDate,+ lte: today,+ },+ },+ select: {+ duration: true,+ activityType: {+ select: {+ label: true,+ },+ },+ },+ });++ const groupedByType = activities.reduce(+ (acc: Record<string, number>, activity) => {+ const label = activity.activityType?.label || "Unknown";+ const durationInHours = (activity.duration || 0) / 60;+ acc[label] = (acc[label] || 0) + durationInHours;+ return acc;+ },+ {},+ );++ const sorted = Object.entries(groupedByType)+ .map(([label, hours]) => ({ label, hours: Math.round(hours * 10) / 10 }))+ .sort((a, b) => b.hours - a.hours)+ .slice(0, 3);++ return sorted;+ } catch (error) {+ const msg = "Failed to fetch top activity types";+ console.error(msg, error);+ throw new Error(msg);+ }+};diff --git a/src/actions/task.actions.ts b/src/actions/task.actions.tsindex eb30591..860ee51 100644--- a/src/actions/task.actions.ts+++ b/src/actions/task.actions.ts@@ -1,423 +1,18 @@-"use server";-import prisma from "@/lib/db";-import { handleError } from "@/lib/utils";-import { Task, TaskGroupBy, TaskStatus } from "@/models/task.model";-import { AddTaskFormSchema } from "@/models/addTaskForm.schema";-import { getCurrentUser } from "@/utils/user.utils";-import { APP_CONSTANTS } from "@/lib/constants";-import { z } from "zod";--function getTasksOrderBy(groupBy?: TaskGroupBy) {- switch (groupBy) {- case "dueDate":- return [- { dueDate: "asc" as const },- { priority: "desc" as const },- { createdAt: "desc" as const },- ];- case "createdDate":- return [{ createdAt: "desc" as const }, { priority: "desc" as const }];- case "updatedDate":- return [- { updatedAt: "desc" as const },- { priority: "desc" as const },- { createdAt: "desc" as const },- ];- case "activityType":- return [- { activityType: { label: "asc" as const } },- { priority: "desc" as const },- { createdAt: "desc" as const },- ];- default:- return [- { priority: "desc" as const },- { createdAt: "desc" as const },- { updatedAt: "desc" as const },- ];- }-}--export const getTasksList = async (- page: number = 1,- limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,- filter?: string,- statusFilter?: TaskStatus[],- search?: string,- groupBy?: TaskGroupBy-): 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,- };-- if (filter) {- whereClause.activityTypeId = filter;- }-- if (statusFilter && statusFilter.length > 0) {- whereClause.status = { in: statusFilter };- }-- if (search) {- whereClause.OR = [- { title: { contains: search } },- { description: { contains: search } },- { activityType: { label: { contains: search } } },- ];- }-- const [data, total] = await Promise.all([- prisma.task.findMany({- where: whereClause,- include: {- activityType: true,- activities: {- select: { id: true },- },- },- orderBy: getTasksOrderBy(groupBy),- skip: offset,- take: limit,- }),- prisma.task.count({- where: whereClause,- }),- ]);-- return {- success: true,- data,- total,- };- } catch (error) {- const msg = "Failed to fetch tasks list.";- return handleError(error, msg);- }-};--export const getTaskById = async (- taskId: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const task = await prisma.task.findFirst({- where: {- id: taskId,- userId: user.id,- },- include: {- activityType: true,- activities: {- select: { id: true },- },- },- });-- if (!task) {- return { success: false, message: "Task not found" };- }-- return {- success: true,- data: task,- };- } catch (error) {- const msg = "Failed to fetch task.";- return handleError(error, msg);- }-};--export const createTask = async (- data: z.infer<typeof AddTaskFormSchema>-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const validatedData = AddTaskFormSchema.parse(data);-- const task = await prisma.task.create({- data: {- title: validatedData.title,- description: validatedData.description,- status: validatedData.status,- priority: validatedData.priority,- percentComplete: validatedData.percentComplete,- dueDate: validatedData.dueDate,- activityTypeId: validatedData.activityTypeId,- userId: user.id,- },- include: {- activityType: true,- },- });-- return { success: true, data: task };- } catch (error) {- const msg = "Failed to create task.";- return handleError(error, msg);- }-};--export const updateTask = async (- data: z.infer<typeof AddTaskFormSchema>-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- if (!data.id) {- throw new Error("Task ID is required for update");- }-- const validatedData = AddTaskFormSchema.parse(data);-- const task = await prisma.task.update({- where: {- id: data.id,- userId: user.id,- },- data: {- title: validatedData.title,- description: validatedData.description,- status: validatedData.status,- priority: validatedData.priority,- percentComplete: validatedData.percentComplete,- dueDate: validatedData.dueDate,- activityTypeId: validatedData.activityTypeId,- },- include: {- activityType: true,- },- });-- return { success: true, data: task };- } catch (error) {- const msg = "Failed to update task.";- return handleError(error, msg);- }-};--export const updateTaskStatus = async (- taskId: string,- status: TaskStatus-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const task = await prisma.task.update({- where: {- id: taskId,- userId: user.id,- },- data: {- status,- },- include: {- activityType: true,- },- });-- return { success: true, data: task };- } catch (error) {- const msg = "Failed to update task status.";- return handleError(error, msg);- }-};--export const deleteTaskById = async (- taskId: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const task = await prisma.task.findFirst({- where: {- id: taskId,- userId: user.id,- },- include: {- activities: {- select: { id: true },- },- },- });-- if (!task) {- return { success: false, message: "Task not found" };- }-- if (task.activities.length > 0) {- return {- success: false,- message:- "Cannot delete task with linked activity. Remove the activity first.",- };- }-- await prisma.task.delete({- where: {- id: taskId,- userId: user.id,- },- });-- return { success: true };- } catch (error) {- const msg = "Failed to delete task.";- return handleError(error, msg);- }-};--export const startActivityFromTask = async (- taskId: string-): Promise<any | undefined> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const task = await prisma.task.findFirst({- where: {- id: taskId,- userId: user.id,- },- });-- if (!task) {- return { success: false, message: "Task not found" };- }-- if (task.status === "complete" || task.status === "cancelled") {- return {- success: false,- message: "Cannot start an activity from a completed or cancelled task.",- };- }-- if (!task.activityTypeId) {- return {- success: false,- message: "Task must have an activity type to start an activity.",- };- }-- const runningActivity = await prisma.activity.findFirst({- where: {- userId: user.id,- endTime: null,- },- });-- if (runningActivity) {- return {- success: false,- message:- "You already have a running activity. Please stop it before starting a new one.",- };- }-- // A task can have many activities over time; each start links a new one- // to the task so per-task time can be tracked.- const activity = await prisma.activity.create({- data: {- activityName: task.title,- activityTypeId: task.activityTypeId,- userId: user.id,- startTime: new Date(),- endTime: null,- taskId: task.id,- },- include: {- activityType: true,- },- });-- return { success: true, data: activity };- } catch (error) {- const msg = "Failed to start activity from task.";- return handleError(error, msg);- }-};--export const getActivityTypesWithTaskCounts = async (): Promise<- any | undefined-> => {- try {- const user = await getCurrentUser();-- if (!user) {- throw new Error("Not authenticated");- }-- const excludedStatuses = ["complete", "cancelled"];-- const activityTypes = await prisma.activityType.findMany({- where: {- createdBy: user.id,- },- include: {- _count: {- select: {- Tasks: {- where: {- status: { notIn: excludedStatuses },- },- },- },- },- },- });-- const data = activityTypes- .map((type) => ({- id: type.id,- label: type.label,- value: type.value,- taskCount: type._count.Tasks,- }))- .sort((a, b) => b.taskCount - a.taskCount);-- const totalTasks = await prisma.task.count({- where: {- userId: user.id,- status: { notIn: excludedStatuses },- },- });-- return { success: true, data, totalTasks };- } catch (error) {- const msg = "Failed to fetch activity types with task counts.";- return handleError(error, msg);- }-};+// Barrel for the task server actions, split into src/actions/task/.+// Each module below carries its own "use server"; this file only re-exports so+// the long-standing "@/actions/task.actions" import path keeps working.++export {+ getTasksList,+ getTaskById,+ getActivityTypesWithTaskCounts,+} from "./task/queries";++export {+ createTask,+ updateTask,+ updateTaskStatus,+ deleteTaskById,+} from "./task/mutations";++export { startActivityFromTask } from "./task/activity";diff --git a/src/actions/task/activity.ts b/src/actions/task/activity.tsnew file mode 100644index 0000000..4763de1--- /dev/null+++ b/src/actions/task/activity.ts@@ -0,0 +1,73 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { requireUser } from "../shared";++export const startActivityFromTask = async (+ taskId: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const task = await prisma.task.findFirst({+ where: {+ id: taskId,+ userId: user.id,+ },+ });++ if (!task) {+ return { success: false, message: "Task not found" };+ }++ if (task.status === "complete" || task.status === "cancelled") {+ return {+ success: false,+ message: "Cannot start an activity from a completed or cancelled task.",+ };+ }++ if (!task.activityTypeId) {+ return {+ success: false,+ message: "Task must have an activity type to start an activity.",+ };+ }++ const runningActivity = await prisma.activity.findFirst({+ where: {+ userId: user.id,+ endTime: null,+ },+ });++ if (runningActivity) {+ return {+ success: false,+ message:+ "You already have a running activity. Please stop it before starting a new one.",+ };+ }++ // A task can have many activities over time; each start links a new one+ // to the task so per-task time can be tracked.+ const activity = await prisma.activity.create({+ data: {+ activityName: task.title,+ activityTypeId: task.activityTypeId,+ userId: user.id,+ startTime: new Date(),+ endTime: null,+ taskId: task.id,+ },+ include: {+ activityType: true,+ },+ });++ return { success: true, data: activity };+ } catch (error) {+ const msg = "Failed to start activity from task.";+ return handleError(error, msg);+ }+};diff --git a/src/actions/task/mutations.ts b/src/actions/task/mutations.tsnew file mode 100644index 0000000..e8e2b08--- /dev/null+++ b/src/actions/task/mutations.ts@@ -0,0 +1,145 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { TaskStatus } from "@/models/task.model";+import { AddTaskFormSchema } from "@/models/addTaskForm.schema";+import { z } from "zod";+import { requireUser } from "../shared";++const WITH_ACTIVITY_TYPE = {+ activityType: true,+};++export const createTask = async (+ data: z.infer<typeof AddTaskFormSchema>+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const validatedData = AddTaskFormSchema.parse(data);++ const task = await prisma.task.create({+ data: {+ title: validatedData.title,+ description: validatedData.description,+ status: validatedData.status,+ priority: validatedData.priority,+ percentComplete: validatedData.percentComplete,+ dueDate: validatedData.dueDate,+ activityTypeId: validatedData.activityTypeId,+ userId: user.id,+ },+ include: WITH_ACTIVITY_TYPE,+ });++ return { success: true, data: task };+ } catch (error) {+ const msg = "Failed to create task.";+ return handleError(error, msg);+ }+};++export const updateTask = async (+ data: z.infer<typeof AddTaskFormSchema>+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ if (!data.id) {+ throw new Error("Task ID is required for update");+ }++ const validatedData = AddTaskFormSchema.parse(data);++ const task = await prisma.task.update({+ where: {+ id: data.id,+ userId: user.id,+ },+ data: {+ title: validatedData.title,+ description: validatedData.description,+ status: validatedData.status,+ priority: validatedData.priority,+ percentComplete: validatedData.percentComplete,+ dueDate: validatedData.dueDate,+ activityTypeId: validatedData.activityTypeId,+ },+ include: WITH_ACTIVITY_TYPE,+ });++ return { success: true, data: task };+ } catch (error) {+ const msg = "Failed to update task.";+ return handleError(error, msg);+ }+};++export const updateTaskStatus = async (+ taskId: string,+ status: TaskStatus+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const task = await prisma.task.update({+ where: {+ id: taskId,+ userId: user.id,+ },+ data: {+ status,+ },+ include: WITH_ACTIVITY_TYPE,+ });++ return { success: true, data: task };+ } catch (error) {+ const msg = "Failed to update task status.";+ return handleError(error, msg);+ }+};++export const deleteTaskById = async (+ taskId: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const task = await prisma.task.findFirst({+ where: {+ id: taskId,+ userId: user.id,+ },+ include: {+ activities: {+ select: { id: true },+ },+ },+ });++ if (!task) {+ return { success: false, message: "Task not found" };+ }++ if (task.activities.length > 0) {+ return {+ success: false,+ message:+ "Cannot delete task with linked activity. Remove the activity first.",+ };+ }++ await prisma.task.delete({+ where: {+ id: taskId,+ userId: user.id,+ },+ });++ return { success: true };+ } catch (error) {+ const msg = "Failed to delete task.";+ return handleError(error, msg);+ }+};diff --git a/src/actions/task/queries.ts b/src/actions/task/queries.tsnew file mode 100644index 0000000..778e32e--- /dev/null+++ b/src/actions/task/queries.ts@@ -0,0 +1,177 @@+"use server";+import prisma from "@/lib/db";+import { handleError } from "@/lib/utils";+import { TaskGroupBy, TaskStatus } from "@/models/task.model";+import { APP_CONSTANTS } from "@/lib/constants";+import { requireUser } from "../shared";++const TASK_WITH_ACTIVITIES_INCLUDE = {+ activityType: true,+ activities: {+ select: { id: true },+ },+};++function getTasksOrderBy(groupBy?: TaskGroupBy) {+ switch (groupBy) {+ case "dueDate":+ return [+ { dueDate: "asc" as const },+ { priority: "desc" as const },+ { createdAt: "desc" as const },+ ];+ case "createdDate":+ return [{ createdAt: "desc" as const }, { priority: "desc" as const }];+ case "updatedDate":+ return [+ { updatedAt: "desc" as const },+ { priority: "desc" as const },+ { createdAt: "desc" as const },+ ];+ case "activityType":+ return [+ { activityType: { label: "asc" as const } },+ { priority: "desc" as const },+ { createdAt: "desc" as const },+ ];+ default:+ return [+ { priority: "desc" as const },+ { createdAt: "desc" as const },+ { updatedAt: "desc" as const },+ ];+ }+}++export const getTasksList = async (+ page: number = 1,+ limit: number = APP_CONSTANTS.RECORDS_PER_PAGE,+ filter?: string,+ statusFilter?: TaskStatus[],+ search?: string,+ groupBy?: TaskGroupBy+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const offset = (page - 1) * limit;++ const whereClause: any = {+ userId: user.id,+ };++ if (filter) {+ whereClause.activityTypeId = filter;+ }++ if (statusFilter && statusFilter.length > 0) {+ whereClause.status = { in: statusFilter };+ }++ if (search) {+ whereClause.OR = [+ { title: { contains: search } },+ { description: { contains: search } },+ { activityType: { label: { contains: search } } },+ ];+ }++ const [data, total] = await Promise.all([+ prisma.task.findMany({+ where: whereClause,+ include: TASK_WITH_ACTIVITIES_INCLUDE,+ orderBy: getTasksOrderBy(groupBy),+ skip: offset,+ take: limit,+ }),+ prisma.task.count({+ where: whereClause,+ }),+ ]);++ return {+ success: true,+ data,+ total,+ };+ } catch (error) {+ const msg = "Failed to fetch tasks list.";+ return handleError(error, msg);+ }+};++export const getTaskById = async (+ taskId: string+): Promise<any | undefined> => {+ try {+ const user = await requireUser();++ const task = await prisma.task.findFirst({+ where: {+ id: taskId,+ userId: user.id,+ },+ include: TASK_WITH_ACTIVITIES_INCLUDE,+ });++ if (!task) {+ return { success: false, message: "Task not found" };+ }++ return {+ success: true,+ data: task,+ };+ } catch (error) {+ const msg = "Failed to fetch task.";+ return handleError(error, msg);+ }+};++export const getActivityTypesWithTaskCounts = async (): Promise<+ any | undefined+> => {+ try {+ const user = await requireUser();++ const excludedStatuses = ["complete", "cancelled"];++ const activityTypes = await prisma.activityType.findMany({+ where: {+ createdBy: user.id,+ },+ include: {+ _count: {+ select: {+ Tasks: {+ where: {+ status: { notIn: excludedStatuses },+ },+ },+ },+ },+ },+ });++ const data = activityTypes+ .map((type) => ({+ id: type.id,+ label: type.label,+ value: type.value,+ taskCount: type._count.Tasks,+ }))+ .sort((a, b) => b.taskCount - a.taskCount);++ const totalTasks = await prisma.task.count({+ where: {+ userId: user.id,+ status: { notIn: excludedStatuses },+ },+ });++ return { success: true, data, totalTasks };+ } catch (error) {+ const msg = "Failed to fetch activity types with task counts.";+ return handleError(error, msg);+ }+};