| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510 |
- 'use server';
- import { prisma } from '@/lib/prisma';
- import { revalidatePath } from 'next/cache';
- import { z } from 'zod';
- // Validation schemas
- const createImportSchema = z.object({
- name: z.string().min(1, 'Import name is required'),
- layoutId: z.number().int().positive('Layout configuration is required'),
- fileId: z.string().optional(),
- });
- const updateImportSchema = z.object({
- id: z.number().int().positive(),
- name: z.string().min(1, 'Import name is required'),
- fileId: z.string().optional(),
- });
- // Create a new import
- export async function createImport(data: {
- name: string;
- layoutId: number;
- fileId?: string;
- }) {
- try {
- const validatedData = createImportSchema.parse(data);
- const importRecord = await prisma.import.create({
- data: {
- name: validatedData.name,
- layoutId: validatedData.layoutId,
- importDate: new Date(),
- ...(validatedData.fileId && { fileId: validatedData.fileId }),
- },
- include: {
- layout: true,
- },
- });
- revalidatePath('/imports');
- return { success: true, data: importRecord };
- } catch (error) {
- console.error('Error creating import:', error);
- return { success: false, error: 'Failed to create import' };
- }
- }
- // Get all imports for the current user
- export async function getImports(userId?: string) {
- try {
- const imports = await prisma.import.findMany({
- where: userId ? {
- fileId: {
- not: null,
- },
- } : {},
- include: {
- layout: true,
- },
- orderBy: {
- importDate: 'desc',
- },
- });
- // Filter by userId manually since Prisma doesn't have direct relation
- let filteredImports = imports;
- if (userId) {
- const fileIds = await prisma.file.findMany({
- where: {
- userId: userId,
- },
- select: {
- id: true,
- },
- });
- const userFileIds = new Set(fileIds.map(f => f.id));
- filteredImports = imports.filter(imp =>
- imp.fileId && userFileIds.has(imp.fileId)
- );
- }
- return { success: true, data: filteredImports };
- } catch (error) {
- console.error('Error fetching imports:', error);
- return { success: false, error: 'Failed to fetch imports' };
- }
- }
- // Get a single import by ID
- export async function getImportById(id: number) {
- try {
- const importRecord = await prisma.import.findUnique({
- where: { id },
- include: {
- layout: {
- include: {
- sections: {
- include: {
- fields: true,
- },
- },
- },
- },
- cintasSummaries: {
- orderBy: {
- weekId: 'desc',
- },
- },
- },
- });
- if (!importRecord) {
- return { success: false, error: 'Import not found' };
- }
- return { success: true, data: importRecord };
- } catch (error) {
- console.error('Error fetching import:', error);
- return { success: false, error: 'Failed to fetch import' };
- }
- }
- // Update an import
- export async function updateImport(data: {
- id: number;
- name: string;
- fileId?: string;
- }) {
- try {
- const validatedData = updateImportSchema.parse(data);
- const importRecord = await prisma.import.update({
- where: { id: validatedData.id },
- data: {
- name: validatedData.name,
- ...(validatedData.fileId !== undefined && { fileId: validatedData.fileId }),
- },
- include: {
- layout: true,
- },
- });
- revalidatePath('/imports');
- return { success: true, data: importRecord };
- } catch (error) {
- console.error('Error updating import:', error);
- return { success: false, error: 'Failed to update import' };
- }
- }
- // Delete an import
- export async function deleteImport(id: number) {
- try {
- await prisma.import.delete({
- where: { id },
- });
- revalidatePath('/imports');
- return { success: true };
- } catch (error) {
- console.error('Error deleting import:', error);
- return { success: false, error: 'Failed to delete import' };
- }
- }
- // Calculate Cintas summaries for an import
- export async function calculateCintasSummaries(importId: number) {
- try {
- // This would typically call a stored procedure or perform calculations
- // For now, we'll simulate the calculation
- // In a real implementation, you might call:
- // await prisma.$executeRaw`CALL cintas_calculate_summary(${importId})`;
- // For demo purposes, we'll create some sample data
- const summaries = [
- {
- importId,
- week: '2024-W01',
- trrTotal: 100,
- fourWkAverages: 95,
- trrPlus4Wk: 195,
- powerAdds: 25,
- weekId: 1,
- },
- {
- importId,
- week: '2024-W02',
- trrTotal: 110,
- fourWkAverages: 100,
- trrPlus4Wk: 210,
- powerAdds: 30,
- weekId: 2,
- },
- ];
- // Clear existing summaries for this import
- await prisma.cintasSummary.deleteMany({
- where: { importId },
- });
- // Create new summaries
- const createdSummaries = await Promise.all(
- summaries.map(summary =>
- prisma.cintasSummary.create({
- data: summary,
- })
- )
- );
- return { success: true, data: createdSummaries };
- } catch (error) {
- console.error('Error calculating Cintas summaries:', error);
- return { success: false, error: 'Failed to calculate summaries' };
- }
- }
- // Get available layout configurations
- export async function getLayoutConfigurations() {
- try {
- const layouts = await prisma.layoutConfiguration.findMany({
- include: {
- sections: {
- include: {
- fields: true,
- },
- },
- },
- orderBy: {
- name: 'asc',
- },
- });
- return { success: true, data: layouts };
- } catch (error) {
- console.error('Error fetching layout configurations:', error);
- return { success: false, error: 'Failed to fetch layout configurations' };
- }
- }
- // Get import summary (GET /api/imports/[id]/summary)
- export async function getImportSummary(importId: number) {
- try {
- if (!importId || isNaN(importId)) {
- return { success: false, error: 'Invalid import ID' };
- }
- // Check if import exists
- const importRecord = await prisma.import.findUnique({
- where: { id: importId }
- });
- if (!importRecord) {
- return { success: false, error: 'Import not found' };
- }
- // Get basic summary data
- const totalRecords = await prisma.cintasInstallCalendar.count({
- where: { importId }
- });
- const cintasSummaries = await prisma.cintasSummary.findMany({
- where: { importId },
- orderBy: { weekId: 'desc' }
- });
- // Get file info
- const file = importRecord.fileId ? await prisma.file.findUnique({
- where: { id: importRecord.fileId }
- }) : null;
- const summary = {
- totalRecords,
- totalWeeks: cintasSummaries.length,
- cintasSummaries: cintasSummaries.map((summary: any) => ({
- id: summary.id,
- week: summary.week,
- trrTotal: summary.trrTotal,
- fourWkAverages: summary.fourWkAverages,
- trrPlus4Wk: summary.trrPlus4Wk,
- powerAdds: summary.powerAdds,
- weekId: summary.weekId
- }))
- };
- return {
- success: true,
- data: {
- importId,
- fileName: file?.filename || 'Unknown',
- uploadDate: importRecord.createdAt,
- summary,
- summaryExists: cintasSummaries.length > 0
- }
- };
- } catch (error) {
- console.error('Error fetching import summary:', error);
- return { success: false, error: 'Failed to fetch import summary' };
- }
- }
- // Generate import summary (POST /api/imports/[id]/summary)
- export async function generateImportSummary(importId: number) {
- try {
- if (!importId || isNaN(importId)) {
- return { success: false, error: 'Invalid import ID' };
- }
- // Check if import exists
- const importRecord = await prisma.import.findUnique({
- where: { id: importId }
- });
- if (!importRecord) {
- return { success: false, error: 'Import not found' };
- }
- // Check if summary already exists
- const existingSummaries = await prisma.cintasSummary.count({
- where: { importId }
- });
- if (existingSummaries > 0) {
- // Return existing summary
- const cintasSummaries = await prisma.cintasSummary.findMany({
- where: { importId },
- orderBy: { weekId: 'desc' }
- });
- return {
- success: true,
- data: {
- importId,
- summaryGenerated: false,
- message: 'Summary already exists',
- summary: cintasSummaries.map((summary: any) => ({
- id: summary.id,
- week: summary.week,
- trrTotal: summary.trrTotal,
- fourWkAverages: summary.fourWkAverages,
- trrPlus4Wk: summary.trrPlus4Wk,
- powerAdds: summary.powerAdds,
- weekId: summary.weekId
- }))
- }
- };
- }
- // Generate new summary using stored procedure
- await prisma.$executeRawUnsafe(
- `CALL cintas_calculate_summary(${importId})`
- );
- // Fetch the newly generated summary
- const cintasSummaries = await prisma.cintasSummary.findMany({
- where: { importId },
- orderBy: { weekId: 'desc' }
- });
- return {
- success: true,
- data: {
- importId,
- summaryGenerated: true,
- message: 'Summary generated successfully',
- summary: cintasSummaries.map((summary: any) => ({
- id: summary.id,
- week: summary.week,
- trrTotal: summary.trrTotal,
- fourWkAverages: summary.fourWkAverages,
- trrPlus4Wk: summary.trrPlus4Wk,
- powerAdds: summary.powerAdds,
- weekId: summary.weekId
- }))
- }
- };
- } catch (error) {
- console.error('Error generating summary:', error);
- return { success: false, error: 'Failed to generate summary' };
- }
- }
- // Get import progress (GET /api/imports/[id]/progress)
- export async function getImportProgress(importId: number) {
- try {
- if (!importId || isNaN(importId)) {
- return { success: false, error: 'Invalid import ID' };
- }
- // Check if import exists
- const importRecord = await prisma.import.findUnique({
- where: { id: importId }
- });
- if (!importRecord) {
- return { success: false, error: 'Import not found' };
- }
- // For now, we'll simulate progress based on the existence of records
- const totalRecords = await prisma.cintasInstallCalendar.count({
- where: { importId }
- });
- // Since we don't have status fields, we'll use record count as proxy
- const hasRecords = totalRecords > 0;
- return {
- success: true,
- data: {
- importId,
- status: hasRecords ? 'completed' : 'pending',
- progress: hasRecords ? 100 : 0,
- processedRecords: totalRecords,
- totalRecords: totalRecords,
- errorMessage: null,
- lastUpdated: importRecord.updatedAt,
- timestamp: new Date().toISOString()
- }
- };
- } catch (error) {
- console.error('Error fetching import progress:', error);
- return { success: false, error: 'Failed to fetch import progress' };
- }
- }
- // Trigger import process (POST /api/imports/[id]/trigger)
- export async function triggerImportProcess(importId: number) {
- try {
- if (!importId || isNaN(importId)) {
- return { success: false, error: 'Invalid import ID' };
- }
- // Validate import exists
- const importRecord = await prisma.import.findUnique({
- where: { id: importId }
- });
- if (!importRecord) {
- return { success: false, error: 'Import not found' };
- }
- if (!importRecord.fileId) {
- return { success: false, error: 'No file attached to import' };
- }
- // Check if layout exists
- const layout = await prisma.layoutConfiguration.findUnique({
- where: { id: importRecord.layoutId }
- });
- if (!layout) {
- return { success: false, error: 'No layout configuration found' };
- }
- // Check if data already exists for this import
- const existingRecords = await prisma.cintasInstallCalendar.count({
- where: { importId }
- });
- if (existingRecords > 0) {
- return {
- success: true,
- message: 'Import already processed',
- importId,
- existingRecords
- };
- }
- // For now, we'll simulate the processing
- // In production, this would integrate with ImportProcessor
- // The ImportProcessor would handle the actual file processing
- return {
- success: true,
- message: 'Import process started successfully',
- importId
- };
- } catch (error) {
- console.error('Error triggering import:', error);
- return { success: false, error: 'Failed to trigger import' };
- }
- }
- // Update import progress (for internal use by ImportProcessor)
- export async function updateImportProgress(
- importId: number,
- progress: {
- processedRecords: number;
- totalRecords: number;
- status: string;
- errorMessage?: string;
- }
- ) {
- try {
- // Since the Import model doesn't have these fields, we'll just return success
- // In a real implementation, you would need to add these fields to the schema
- console.log(`Import ${importId} progress: ${progress.processedRecords}/${progress.totalRecords} (${progress.status})`);
- return { success: true };
- } catch (error) {
- console.error('Error updating import progress:', error);
- return { success: false, error: 'Failed to update progress' };
- }
- }
|