Spaces:
Runtime error

File size: 6,364 Bytes
ad79323
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import { Readable } from "node:stream";

import type { CaseFile } from "@prisma/client";

import {
  MINIO_BUCKET_NAME,
  MINIO_PUBLIC_BASE_URL,
} from "@/lib/constants";
import { assertCaseFileWithinSizeLimit, getSafeMimeType, isAllowedCaseFileType } from "@/lib/file-utils";
import { trimOrUndefined } from "@/lib/utils";
import { requireCaseByIdForOwner } from "@/server/cases/service";
import { requireCustomerByIdForOwner } from "@/server/customers/service";
import { db } from "@/server/db";
import { AppError } from "@/server/errors";
import { buildCaseFileStorageKey, ensureMinioBucket, minioClient } from "@/server/storage/minio";
import type {
  CaseFileListQueryInput,
  CaseFileMetadataInput,
} from "@/server/validation/case";
import type { CaseFileRagStatusValue } from "@/lib/constants";

export function normalizeCaseFileListFilters(input: CaseFileListQueryInput) {
  return {
    search: trimOrUndefined(input.fileSearch),
    selectedFileId: trimOrUndefined(input.fileId),
    sessionPreset: input.sessionPreset,
  };
}

export async function listCaseFilesForOwner(
  ownerId: string,
  customerId: string,
  caseId: string,
  search?: string,
) {
  await requireCaseByIdForOwner(ownerId, customerId, caseId);

  return db.caseFile.findMany({
    where: {
      ownerId,
      customerId,
      caseId,
      ...(search
        ? {
            displayName: {
              contains: search,
              mode: "insensitive",
            },
          }
        : {}),
    },
    orderBy: {
      createdAt: "desc",
    },
  });
}

export async function listCustomerArchiveFilesForOwner(
  ownerId: string,
  customerId: string,
  search?: string,
) {
  await requireCustomerByIdForOwner(customerId, ownerId);

  return db.caseFile.findMany({
    where: {
      ownerId,
      customerId,
      ...(search
        ? {
            displayName: {
              contains: search,
              mode: "insensitive",
            },
          }
        : {}),
    },
    include: {
      case: true,
    },
    orderBy: {
      createdAt: "desc",
    },
  });
}

export async function getCaseFileByIdForOwner(
  ownerId: string,
  customerId: string,
  caseId: string,
  fileId: string,
) {
  return db.caseFile.findFirst({
    where: {
      id: fileId,
      ownerId,
      customerId,
      caseId,
    },
    include: {
      case: {
        include: {
          customer: true,
        },
      },
    },
  });
}

export async function requireCaseFileByIdForOwner(
  ownerId: string,
  customerId: string,
  caseId: string,
  fileId: string,
) {
  const file = await getCaseFileByIdForOwner(ownerId, customerId, caseId, fileId);

  if (!file) {
    throw new AppError("الملف ده مش موجود.", 404);
  }

  return file;
}

export async function uploadCaseFileForOwner(
  ownerId: string,
  customerId: string,
  caseId: string,
  metadata: CaseFileMetadataInput,
  uploadedFile: File,
) {
  await requireCaseByIdForOwner(ownerId, customerId, caseId);

  if (!uploadedFile || uploadedFile.size <= 0) {
    throw new AppError("اختار ملف قبل الرفع.", 400);
  }

  if (!assertCaseFileWithinSizeLimit(uploadedFile.size)) {
    throw new AppError("حجم الملف أكبر من الحد المسموح 25 ميجابايت.", 400);
  }

  const mimeType = getSafeMimeType(uploadedFile.name, uploadedFile.type);

  if (!isAllowedCaseFileType(uploadedFile.name, mimeType)) {
    throw new AppError("نوع الملف ده غير مدعوم في النسخة الحالية.", 400);
  }

  const arrayBuffer = await uploadedFile.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
  const storageKey = buildCaseFileStorageKey(caseId, uploadedFile.name);
  const ragStatus: CaseFileRagStatusValue =
    mimeType === "application/pdf" ? "PROCESSING" : "SKIPPED";

  await ensureMinioBucket();
  await minioClient.putObject(MINIO_BUCKET_NAME, storageKey, buffer, buffer.length, {
    "Content-Type": mimeType,
  });

  return db.caseFile.create({
    data: {
      ownerId,
      customerId,
      caseId,
      displayName: metadata.displayName.trim(),
      description: trimOrUndefined(metadata.description),
      originalFileName: uploadedFile.name,
      mimeType,
      sizeBytes: uploadedFile.size,
      storageBucket: MINIO_BUCKET_NAME,
      storageKey,
      ragStatus,
    },
  });
}

export async function updateCaseFileRagStatus(
  fileId: string,
  status: CaseFileRagStatusValue,
  options?: {
    error?: string | null;
    syncedAt?: Date | null;
  },
) {
  return db.caseFile.update({
    where: {
      id: fileId,
    },
    data: {
      ragStatus: status,
      ragError: options?.error ?? null,
      ragSyncedAt: options?.syncedAt ?? null,
    },
  });
}

export async function listReadyPdfFilesForCase(
  ownerId: string,
  customerId: string,
  caseId: string,
) {
  await requireCaseByIdForOwner(ownerId, customerId, caseId);

  return db.caseFile.findMany({
    where: {
      ownerId,
      customerId,
      caseId,
      mimeType: "application/pdf",
      ragStatus: "READY",
    },
    orderBy: {
      createdAt: "desc",
    },
  });
}

export async function getCaseFileContentStream(file: CaseFile) {
  const stream = await minioClient.getObject(file.storageBucket, file.storageKey);
  return Readable.toWeb(stream) as ReadableStream<Uint8Array>;
}

export function buildCaseFileContentUrl(params: {
  customerId: string;
  caseId: string;
  fileId: string;
  download?: boolean;
}) {
  const basePath = `/api/customers/${params.customerId}/cases/${params.caseId}/files/${params.fileId}/content`;
  return params.download ? `${basePath}?download=1` : basePath;
}

export function buildCaseFilePreviewUrl(params: {
  customerId: string;
  caseId: string;
  fileId: string;
}) {
  const path = buildCaseFileContentUrl(params);

  if (!MINIO_PUBLIC_BASE_URL) {
    return path;
  }

  const normalizedBase = MINIO_PUBLIC_BASE_URL.replace(/\/$/, "");
  return `${normalizedBase}${path}`;
}

export function buildInlineFileName(file: Pick<CaseFile, "displayName" | "originalFileName">) {
  const extension = file.originalFileName.includes(".")
    ? file.originalFileName.slice(file.originalFileName.lastIndexOf("."))
    : "";

  if (extension && file.displayName.toLowerCase().endsWith(extension.toLowerCase())) {
    return file.displayName;
  }

  return `${file.displayName}${extension}`;
}