소스 검색

max files

Bernt Christian Egeland 9 달 전
부모
커밋
1c431a1ac5

+ 18 - 12
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/documents/page.tsx

@@ -2,6 +2,7 @@ import { db } from "@/lib/db";
 import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
 import { redirect } from "next/navigation";
 import { ServiceDocumentsManager } from "@/features/vehicles/Components/service-documents-manager";
+import { getFeatures } from "@/lib/features";
 
 export default async function EditServiceDocumentsPage({
   params,
@@ -15,19 +16,22 @@ export default async function EditServiceDocumentsPage({
   const membership = await getCachedMembership(session.user.id);
   if (!membership) redirect("/sign-in");
 
-  const record = await db.serviceRecord.findFirst({
-    where: {
-      id: serviceId,
-      vehicle: { id, organizationId: membership.organizationId },
-    },
-    select: {
-      id: true,
-      attachments: {
-        where: { category: { in: ["document", "diagnostic"] } },
-        orderBy: { createdAt: "asc" },
+  const [record, features] = await Promise.all([
+    db.serviceRecord.findFirst({
+      where: {
+        id: serviceId,
+        vehicle: { id, organizationId: membership.organizationId },
       },
-    },
-  });
+      select: {
+        id: true,
+        attachments: {
+          where: { category: { in: ["document", "diagnostic"] } },
+          orderBy: { createdAt: "asc" },
+        },
+      },
+    }),
+    getFeatures(membership.organizationId),
+  ]);
 
   if (!record) {
     return (
@@ -41,6 +45,8 @@ export default async function EditServiceDocumentsPage({
     <ServiceDocumentsManager
       serviceRecordId={record.id}
       initialDocuments={record.attachments}
+      maxDiagnostics={features.maxDiagnosticsPerService}
+      maxDocuments={features.maxDocumentsPerService}
     />
   );
 }

+ 17 - 12
src/app/(authenticated)/vehicles/[id]/service/[serviceId]/edit/images/page.tsx

@@ -2,6 +2,7 @@ import { db } from "@/lib/db";
 import { getCachedSession, getCachedMembership } from "@/lib/cached-session";
 import { redirect } from "next/navigation";
 import { ServiceImagesManager } from "@/features/vehicles/Components/service-images-manager";
+import { getFeatures } from "@/lib/features";
 
 export default async function EditServiceImagesPage({
   params,
@@ -15,19 +16,22 @@ export default async function EditServiceImagesPage({
   const membership = await getCachedMembership(session.user.id);
   if (!membership) redirect("/sign-in");
 
-  const record = await db.serviceRecord.findFirst({
-    where: {
-      id: serviceId,
-      vehicle: { id, organizationId: membership.organizationId },
-    },
-    select: {
-      id: true,
-      attachments: {
-        where: { category: "image" },
-        orderBy: { createdAt: "asc" },
+  const [record, features] = await Promise.all([
+    db.serviceRecord.findFirst({
+      where: {
+        id: serviceId,
+        vehicle: { id, organizationId: membership.organizationId },
       },
-    },
-  });
+      select: {
+        id: true,
+        attachments: {
+          where: { category: "image" },
+          orderBy: { createdAt: "asc" },
+        },
+      },
+    }),
+    getFeatures(membership.organizationId),
+  ]);
 
   if (!record) {
     return (
@@ -41,6 +45,7 @@ export default async function EditServiceImagesPage({
     <ServiceImagesManager
       serviceRecordId={record.id}
       initialImages={record.attachments}
+      maxImages={features.maxImagesPerService}
     />
   );
 }

+ 2 - 2
src/app/api/upload/service-files/route.ts

@@ -16,7 +16,7 @@ const ALLOWED_TYPES = [
   "video/quicktime",
 ];
 
-const MAX_SIZE = 20 * 1024 * 1024; // 20MB
+const MAX_SIZE = 10 * 1024 * 1024; // 10MB
 
 export async function POST(request: NextRequest) {
   const ctx = await getAuthContext();
@@ -41,7 +41,7 @@ export async function POST(request: NextRequest) {
 
   if (file.size > MAX_SIZE) {
     return NextResponse.json(
-      { error: "File size must be under 20MB" },
+      { error: "File size must be under 10MB" },
       { status: 400 }
     );
   }

+ 27 - 0
src/features/vehicles/Actions/addServiceAttachment.ts

@@ -5,6 +5,7 @@ import { withAuth } from "@/lib/with-auth";
 import { serviceAttachmentSchema } from "../Schema/serviceSchema";
 import { revalidatePath } from "next/cache";
 import { PermissionAction, PermissionSubject } from "@/lib/permissions";
+import { getFeatures, type PlanFeatures } from "@/lib/features";
 import { z } from "zod";
 
 const addAttachmentSchema = z.object({
@@ -12,6 +13,12 @@ const addAttachmentSchema = z.object({
   attachment: serviceAttachmentSchema,
 });
 
+const CATEGORY_LIMIT_MAP: Record<string, keyof PlanFeatures | undefined> = {
+  image: "maxImagesPerService",
+  diagnostic: "maxDiagnosticsPerService",
+  document: "maxDocumentsPerService",
+};
+
 export async function addServiceAttachment(input: unknown) {
   return withAuth(
     async ({ organizationId }) => {
@@ -26,6 +33,26 @@ export async function addServiceAttachment(input: unknown) {
       });
       if (!record) throw new Error("Service record not found");
 
+      const limitKey = CATEGORY_LIMIT_MAP[data.attachment.category];
+      if (limitKey) {
+        const features = await getFeatures(organizationId);
+        const maxAllowed = features[limitKey] as number;
+        const currentCount = await db.serviceAttachment.count({
+          where: {
+            serviceRecordId: record.id,
+            category: data.attachment.category,
+          },
+        });
+        if (currentCount >= maxAllowed) {
+          const label = data.attachment.category === "diagnostic"
+            ? "Diagnostic report"
+            : data.attachment.category.charAt(0).toUpperCase() + data.attachment.category.slice(1);
+          throw new Error(
+            `${label} limit reached (${currentCount}/${maxAllowed}). Upgrade your plan for more.`
+          );
+        }
+      }
+
       const attachment = await db.serviceAttachment.create({
         data: {
           ...data.attachment,

+ 118 - 66
src/features/vehicles/Components/service-documents-manager.tsx

@@ -31,6 +31,8 @@ interface Attachment {
 interface ServiceDocumentsManagerProps {
   serviceRecordId: string;
   initialDocuments: Attachment[];
+  maxDiagnostics?: number;
+  maxDocuments?: number;
 }
 
 function formatFileSize(bytes: number) {
@@ -50,6 +52,8 @@ function getFileIcon(type: string) {
 export function ServiceDocumentsManager({
   serviceRecordId,
   initialDocuments,
+  maxDiagnostics,
+  maxDocuments,
 }: ServiceDocumentsManagerProps) {
   const [files, setFiles] = useState<Attachment[]>(initialDocuments);
   const [uploadingReports, setUploadingReports] = useState(false);
@@ -59,16 +63,32 @@ export function ServiceDocumentsManager({
 
   const diagnosticReports = files.filter((f) => f.category === "diagnostic");
   const documents = files.filter((f) => f.category === "document");
+  const diagnosticsAtLimit = maxDiagnostics !== undefined && diagnosticReports.length >= maxDiagnostics;
+  const documentsAtLimit = maxDocuments !== undefined && documents.length >= maxDocuments;
 
   const handleUpload = useCallback(
     async (
       fileList: FileList | File[],
       category: "diagnostic" | "document"
     ) => {
+      const maxLimit = category === "diagnostic" ? maxDiagnostics : maxDocuments;
+      const currentItems = category === "diagnostic" ? diagnosticReports : documents;
+      let fileArr = Array.from(fileList);
+      if (maxLimit !== undefined) {
+        const remaining = maxLimit - currentItems.length;
+        if (remaining <= 0) {
+          const label = category === "diagnostic" ? "Diagnostic report" : "Document";
+          toast.error(`${label} limit reached (${currentItems.length}/${maxLimit}). Upgrade your plan for more.`);
+          return;
+        }
+        if (fileArr.length > remaining) {
+          fileArr = fileArr.slice(0, remaining);
+          toast.warning(`Only uploading ${remaining} file${remaining > 1 ? "s" : ""} to stay within limit.`);
+        }
+      }
       const setUploading =
         category === "diagnostic" ? setUploadingReports : setUploadingDocuments;
       setUploading(true);
-      const fileArr = Array.from(fileList);
       const toastId = toast.loading(
         `Uploading ${fileArr.length} file${fileArr.length > 1 ? "s" : ""}...`
       );
@@ -123,7 +143,7 @@ export function ServiceDocumentsManager({
       }
       setUploading(false);
     },
-    [serviceRecordId]
+    [serviceRecordId, maxDiagnostics, maxDocuments, diagnosticReports, documents]
   );
 
   const handleDelete = useCallback(async (attachmentId: string) => {
@@ -208,42 +228,58 @@ export function ServiceDocumentsManager({
           <CardTitle className="flex items-center gap-2 text-base">
             <FileText className="h-4 w-4" />
             Diagnostic Reports
+            {maxDiagnostics !== undefined && (
+              <span className="ml-auto text-xs font-normal text-muted-foreground">
+                {diagnosticReports.length} / {maxDiagnostics}
+              </span>
+            )}
           </CardTitle>
         </CardHeader>
         <CardContent className="space-y-4">
-          <div
-            onDrop={(e) => {
-              e.preventDefault();
-              if (e.dataTransfer.files.length > 0)
-                handleUpload(e.dataTransfer.files, "diagnostic");
-            }}
-            onDragOver={(e) => e.preventDefault()}
-            onClick={() => reportInputRef.current?.click()}
-            className="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6 transition-colors hover:border-muted-foreground/50"
-          >
-            <Upload className="mb-2 h-8 w-8 text-muted-foreground/50" />
-            <p className="text-sm font-medium">
-              {uploadingReports
-                ? "Uploading..."
-                : "Drop files here or click to browse"}
-            </p>
-            <p className="mt-1 text-xs text-muted-foreground">
-              PDF, CSV, TXT — max 10MB each
-            </p>
-            <input
-              ref={reportInputRef}
-              type="file"
-              multiple
-              accept=".pdf,.csv,.txt"
-              className="hidden"
-              onChange={(e) => {
-                if (e.target.files && e.target.files.length > 0) {
-                  handleUpload(e.target.files, "diagnostic");
-                  e.target.value = "";
-                }
+          {diagnosticsAtLimit ? (
+            <div className="flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6">
+              <p className="text-sm font-medium text-muted-foreground">
+                Diagnostic report limit reached ({diagnosticReports.length}/{maxDiagnostics})
+              </p>
+              <p className="mt-1 text-xs text-muted-foreground">
+                Upgrade your plan to upload more.
+              </p>
+            </div>
+          ) : (
+            <div
+              onDrop={(e) => {
+                e.preventDefault();
+                if (e.dataTransfer.files.length > 0)
+                  handleUpload(e.dataTransfer.files, "diagnostic");
               }}
-            />
-          </div>
+              onDragOver={(e) => e.preventDefault()}
+              onClick={() => reportInputRef.current?.click()}
+              className="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6 transition-colors hover:border-muted-foreground/50"
+            >
+              <Upload className="mb-2 h-8 w-8 text-muted-foreground/50" />
+              <p className="text-sm font-medium">
+                {uploadingReports
+                  ? "Uploading..."
+                  : "Drop files here or click to browse"}
+              </p>
+              <p className="mt-1 text-xs text-muted-foreground">
+                PDF, CSV, TXT — max 10MB each
+              </p>
+              <input
+                ref={reportInputRef}
+                type="file"
+                multiple
+                accept=".pdf,.csv,.txt"
+                className="hidden"
+                onChange={(e) => {
+                  if (e.target.files && e.target.files.length > 0) {
+                    handleUpload(e.target.files, "diagnostic");
+                    e.target.value = "";
+                  }
+                }}
+              />
+            </div>
+          )}
 
           {uploadingReports && (
             <div className="flex items-center gap-2 text-sm text-muted-foreground">
@@ -262,42 +298,58 @@ export function ServiceDocumentsManager({
           <CardTitle className="flex items-center gap-2 text-base">
             <Paperclip className="h-4 w-4" />
             Documents
+            {maxDocuments !== undefined && (
+              <span className="ml-auto text-xs font-normal text-muted-foreground">
+                {documents.length} / {maxDocuments}
+              </span>
+            )}
           </CardTitle>
         </CardHeader>
         <CardContent className="space-y-4">
-          <div
-            onDrop={(e) => {
-              e.preventDefault();
-              if (e.dataTransfer.files.length > 0)
-                handleUpload(e.dataTransfer.files, "document");
-            }}
-            onDragOver={(e) => e.preventDefault()}
-            onClick={() => documentInputRef.current?.click()}
-            className="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6 transition-colors hover:border-muted-foreground/50"
-          >
-            <Upload className="mb-2 h-8 w-8 text-muted-foreground/50" />
-            <p className="text-sm font-medium">
-              {uploadingDocuments
-                ? "Uploading..."
-                : "Drop files here or click to browse"}
-            </p>
-            <p className="mt-1 text-xs text-muted-foreground">
-              PDF, DOCX, XLSX, CSV, TXT — max 10MB each
-            </p>
-            <input
-              ref={documentInputRef}
-              type="file"
-              multiple
-              accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.txt"
-              className="hidden"
-              onChange={(e) => {
-                if (e.target.files && e.target.files.length > 0) {
-                  handleUpload(e.target.files, "document");
-                  e.target.value = "";
-                }
+          {documentsAtLimit ? (
+            <div className="flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6">
+              <p className="text-sm font-medium text-muted-foreground">
+                Document limit reached ({documents.length}/{maxDocuments})
+              </p>
+              <p className="mt-1 text-xs text-muted-foreground">
+                Upgrade your plan to upload more.
+              </p>
+            </div>
+          ) : (
+            <div
+              onDrop={(e) => {
+                e.preventDefault();
+                if (e.dataTransfer.files.length > 0)
+                  handleUpload(e.dataTransfer.files, "document");
               }}
-            />
-          </div>
+              onDragOver={(e) => e.preventDefault()}
+              onClick={() => documentInputRef.current?.click()}
+              className="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6 transition-colors hover:border-muted-foreground/50"
+            >
+              <Upload className="mb-2 h-8 w-8 text-muted-foreground/50" />
+              <p className="text-sm font-medium">
+                {uploadingDocuments
+                  ? "Uploading..."
+                  : "Drop files here or click to browse"}
+              </p>
+              <p className="mt-1 text-xs text-muted-foreground">
+                PDF, DOCX, XLSX, CSV, TXT — max 10MB each
+              </p>
+              <input
+                ref={documentInputRef}
+                type="file"
+                multiple
+                accept=".pdf,.doc,.docx,.xls,.xlsx,.csv,.txt"
+                className="hidden"
+                onChange={(e) => {
+                  if (e.target.files && e.target.files.length > 0) {
+                    handleUpload(e.target.files, "document");
+                    e.target.value = "";
+                  }
+                }}
+              />
+            </div>
+          )}
 
           {uploadingDocuments && (
             <div className="flex items-center gap-2 text-sm text-muted-foreground">

+ 59 - 29
src/features/vehicles/Components/service-images-manager.tsx

@@ -26,20 +26,34 @@ interface Attachment {
 interface ServiceImagesManagerProps {
   serviceRecordId: string;
   initialImages: Attachment[];
+  maxImages?: number;
 }
 
 export function ServiceImagesManager({
   serviceRecordId,
   initialImages,
+  maxImages,
 }: ServiceImagesManagerProps) {
   const [images, setImages] = useState<Attachment[]>(initialImages);
+  const atLimit = maxImages !== undefined && images.length >= maxImages;
   const [uploading, setUploading] = useState(false);
   const inputRef = useRef<HTMLInputElement>(null);
 
   const handleUpload = useCallback(
     async (files: FileList | File[]) => {
+      let fileArr = Array.from(files);
+      if (maxImages !== undefined) {
+        const remaining = maxImages - images.length;
+        if (remaining <= 0) {
+          toast.error(`Image limit reached (${images.length}/${maxImages}). Upgrade your plan for more.`);
+          return;
+        }
+        if (fileArr.length > remaining) {
+          fileArr = fileArr.slice(0, remaining);
+          toast.warning(`Only uploading ${remaining} image${remaining > 1 ? "s" : ""} to stay within limit.`);
+        }
+      }
       setUploading(true);
-      const fileArr = Array.from(files);
       const toastId = toast.loading(
         `Uploading ${fileArr.length} image${fileArr.length > 1 ? "s" : ""}...`
       );
@@ -97,7 +111,7 @@ export function ServiceImagesManager({
       }
       setUploading(false);
     },
-    [serviceRecordId]
+    [serviceRecordId, maxImages, images.length]
   );
 
   const handleDrop = useCallback(
@@ -169,36 +183,52 @@ export function ServiceImagesManager({
         <CardTitle className="flex items-center gap-2 text-base">
           <Camera className="h-4 w-4" />
           Service Images
+          {maxImages !== undefined && (
+            <span className="ml-auto text-xs font-normal text-muted-foreground">
+              {images.length} / {maxImages}
+            </span>
+          )}
         </CardTitle>
       </CardHeader>
       <CardContent className="space-y-4">
-        <div
-          onDrop={handleDrop}
-          onDragOver={(e) => e.preventDefault()}
-          onClick={() => inputRef.current?.click()}
-          className="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6 transition-colors hover:border-muted-foreground/50"
-        >
-          <ImageIcon className="mb-2 h-8 w-8 text-muted-foreground/50" />
-          <p className="text-sm font-medium">
-            {uploading ? "Uploading..." : "Drop images here or click to browse"}
-          </p>
-          <p className="mt-1 text-xs text-muted-foreground">
-            JPG, PNG, WebP — max 10MB each
-          </p>
-          <input
-            ref={inputRef}
-            type="file"
-            multiple
-            accept=".jpg,.jpeg,.png,.webp"
-            className="hidden"
-            onChange={(e) => {
-              if (e.target.files && e.target.files.length > 0) {
-                handleUpload(e.target.files);
-                e.target.value = "";
-              }
-            }}
-          />
-        </div>
+        {atLimit ? (
+          <div className="flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6">
+            <p className="text-sm font-medium text-muted-foreground">
+              Image limit reached ({images.length}/{maxImages})
+            </p>
+            <p className="mt-1 text-xs text-muted-foreground">
+              Upgrade your plan to upload more images.
+            </p>
+          </div>
+        ) : (
+          <div
+            onDrop={handleDrop}
+            onDragOver={(e) => e.preventDefault()}
+            onClick={() => inputRef.current?.click()}
+            className="flex cursor-pointer flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted-foreground/25 p-6 transition-colors hover:border-muted-foreground/50"
+          >
+            <ImageIcon className="mb-2 h-8 w-8 text-muted-foreground/50" />
+            <p className="text-sm font-medium">
+              {uploading ? "Uploading..." : "Drop images here or click to browse"}
+            </p>
+            <p className="mt-1 text-xs text-muted-foreground">
+              JPG, PNG, WebP — max 10MB each
+            </p>
+            <input
+              ref={inputRef}
+              type="file"
+              multiple
+              accept=".jpg,.jpeg,.png,.webp"
+              className="hidden"
+              onChange={(e) => {
+                if (e.target.files && e.target.files.length > 0) {
+                  handleUpload(e.target.files);
+                  e.target.value = "";
+                }
+              }}
+            />
+          </div>
+        )}
 
         {uploading && (
           <div className="flex items-center gap-2 text-sm text-muted-foreground">

+ 1 - 1
src/features/vehicles/Components/service-video-manager.tsx

@@ -163,7 +163,7 @@ export function ServiceVideoManager({
                 : "Drop videos here or click to browse"}
             </p>
             <p className="mt-1 text-xs text-muted-foreground">
-              MP4, WebM, MOV — max 20MB each
+              MP4, WebM, MOV — max 10MB each
             </p>
             <input
               ref={inputRef}

+ 15 - 0
src/lib/features.ts

@@ -15,6 +15,9 @@ export type PlanFeatures = {
   customFields: boolean
   brandingRemoved: boolean
   customPlatformName: boolean
+  maxImagesPerService: number
+  maxDiagnosticsPerService: number
+  maxDocumentsPerService: number
 }
 
 export const PLAN_FEATURES: Record<Plan, PlanFeatures> = {
@@ -30,6 +33,9 @@ export const PLAN_FEATURES: Record<Plan, PlanFeatures> = {
     customFields: false,
     brandingRemoved: false,
     customPlatformName: false,
+    maxImagesPerService: 5,
+    maxDiagnosticsPerService: 5,
+    maxDocumentsPerService: 5,
   },
   pro: {
     maxCustomers: 999999,
@@ -43,6 +49,9 @@ export const PLAN_FEATURES: Record<Plan, PlanFeatures> = {
     customFields: true,
     brandingRemoved: true,
     customPlatformName: true,
+    maxImagesPerService: 30,
+    maxDiagnosticsPerService: 30,
+    maxDocumentsPerService: 30,
   },
   enterprise: {
     maxCustomers: 999999,
@@ -56,6 +65,9 @@ export const PLAN_FEATURES: Record<Plan, PlanFeatures> = {
     customFields: true,
     brandingRemoved: true,
     customPlatformName: true,
+    maxImagesPerService: 100,
+    maxDiagnosticsPerService: 100,
+    maxDocumentsPerService: 100,
   },
   'white-label': {
     maxCustomers: 999999,
@@ -69,6 +81,9 @@ export const PLAN_FEATURES: Record<Plan, PlanFeatures> = {
     customFields: true,
     brandingRemoved: true,
     customPlatformName: true,
+    maxImagesPerService: 999999,
+    maxDiagnosticsPerService: 999999,
+    maxDocumentsPerService: 999999,
   },
 }