File size: 9,318 Bytes
c09f67c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import type { Attachments } from "./types";
import { lookupDomainByCompanyName } from "./utils/domain-lookup";

export const allowedMimeTypes = [
  "image/heic",
  "image/png",
  "image/jpeg",
  "image/jpg",
  "application/pdf",
  "application/octet-stream",
];

export function getAllowedAttachments(attachments?: Attachments) {
  return attachments?.filter((attachment) =>
    allowedMimeTypes.includes(attachment.ContentType),
  );
}

/**
 * Extract domain from email address
 * Handles various email formats and extracts root domain
 */
export function getDomainFromEmail(email?: string | null): string | null {
  if (!email) return null;

  // Clean email - remove any whitespace and angle brackets
  const cleanedEmail = email.trim().replace(/[<>]/g, "");

  const emailPattern = /^[^\s@]+@([^\s@]+)$/;
  const match = cleanedEmail.match(emailPattern);
  const domain = match?.at(1);

  if (!domain) return null;

  // Handle common email service domains (keep as-is)
  const commonEmailServices = [
    "gmail.com",
    "yahoo.com",
    "outlook.com",
    "hotmail.com",
    "icloud.com",
    "protonmail.com",
  ];
  if (commonEmailServices.includes(domain.toLowerCase())) {
    return domain.toLowerCase();
  }

  // Extract root domain (remove subdomains)
  const domainParts = domain.toLowerCase().split(".");

  // Handle special cases like .co.uk, .com.au, etc.
  const twoPartTLDs = [
    "co.uk",
    "com.au",
    "co.nz",
    "co.za",
    "com.br",
    "com.mx",
    "co.jp",
    "com.cn",
  ];

  // Check if it's a two-part TLD
  if (domainParts.length >= 3) {
    const lastTwo = domainParts.slice(-2).join(".");
    if (twoPartTLDs.includes(lastTwo)) {
      // Return domain with two-part TLD (e.g., example.co.uk)
      return domainParts.slice(-3).join(".");
    }
  }

  // Standard case: return last two parts (e.g., example.com)
  if (domainParts.length > 2) {
    return domainParts.slice(-2).join(".");
  }

  return domain.toLowerCase();
}

/**
 * Remove protocol and clean domain/URL
 * Handles various URL formats and extracts clean domain
 */
export function removeProtocolFromDomain(domain: string | null): string | null {
  if (!domain) return null;

  // Remove protocol (http://, https://, www.)
  let cleaned = domain
    .trim()
    .replace(/^(https?:\/\/)?(www\.)?/i, "")
    .toLowerCase();

  // Remove trailing slash
  cleaned = cleaned.replace(/\/$/, "");

  // Remove path, query params, and fragments
  cleaned = cleaned.split("/")[0]?.split("?")[0]?.split("#")[0] || cleaned;

  // Extract root domain (remove subdomains)
  const domainParts = cleaned.split(".");

  // Handle special cases like .co.uk, .com.au, etc.
  const twoPartTLDs = [
    "co.uk",
    "com.au",
    "co.nz",
    "co.za",
    "com.br",
    "com.mx",
    "co.jp",
    "com.cn",
  ];

  if (domainParts.length >= 3) {
    const lastTwo = domainParts.slice(-2).join(".");
    if (twoPartTLDs.includes(lastTwo)) {
      return domainParts.slice(-3).join(".");
    }
  }

  // Standard case: return last two parts
  if (domainParts.length > 2) {
    return domainParts.slice(-2).join(".");
  }

  return cleaned;
}

/**
 * Intelligently extract website from invoice/receipt data
 * Tries multiple sources: explicit website, email domain, vendor name lookup
 */
export async function extractWebsite(
  website: string | null | undefined,
  email: string | null | undefined,
  vendorName: string | null | undefined,
  logger?: ReturnType<typeof import("@midday/logger").createLoggerWithContext>,
): Promise<string | null> {
  // First priority: explicit website field
  if (website) {
    const cleaned = removeProtocolFromDomain(website);
    if (cleaned) return cleaned;
  }

  // Second priority: extract from email
  if (email) {
    const domain = getDomainFromEmail(email);
    if (domain) {
      // Skip common email service domains
      const commonEmailServices = [
        "gmail.com",
        "yahoo.com",
        "outlook.com",
        "hotmail.com",
        "icloud.com",
        "protonmail.com",
      ];
      if (!commonEmailServices.includes(domain)) {
        return domain;
      }
    }
  }

  // Third priority: lookup domain by company name using Gemini Grounding
  if (vendorName) {
    try {
      const lookedUpDomain = await lookupDomainByCompanyName(
        vendorName,
        logger,
      );
      if (lookedUpDomain) {
        return lookedUpDomain;
      }
    } catch (error) {
      // Log error but don't throw - graceful degradation
      logger?.warn("Domain lookup failed during website extraction", {
        vendorName,
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  }

  return null;
}

export function getDocumentTypeFromMimeType(mimetype: string): string {
  switch (mimetype) {
    case "application/pdf":
    case "application/octet-stream":
      return "invoice";
    default:
      return "receipt";
  }
}

export function getContentSample(text: string, maxTokens = 1200): string {
  const words = text.split(/\s+/);
  const approxWordsPerToken = 0.75; // Rough estimate
  const maxWords = Math.floor(maxTokens / approxWordsPerToken);
  return words.slice(0, maxWords).join(" ");
}

const supportedMimeTypesForProcessing = new Set([
  "application/pdf",
  "application/x-pdf",
  "text/csv",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "application/docx",
  "text/plain",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "application/pptx",
  "application/rtf",
  "text/markdown",
  "application/vnd.oasis.opendocument.text",
  "image/heic", // Handled via conversion
  // "application/vnd.apple.pages",
  // "application/x-iwork-pages-sffpages",
  // "applicatiosn/epub+zip",
]);

/**
 * Checks if a given MIME type is supported for document or image processing.
 * This includes types loadable by `loadDocument` and image types handled by `classifyImage`.
 * @param mimetype The MIME type string to check.
 * @returns True if the MIME type is supported, false otherwise.
 */
export function isMimeTypeSupportedForProcessing(mimetype: string): boolean {
  // Check exact matches first
  if (supportedMimeTypesForProcessing.has(mimetype)) {
    return true;
  }

  // Check if it's any other image type (handled by classifyImage)
  if (mimetype.startsWith("image/")) {
    return true;
  }

  return false;
}

export function extractTextFromRtf(buffer: Buffer): string {
  let rtfContent = buffer.toString("utf-8");

  // Remove font tables, color tables, and other metadata groups
  rtfContent = rtfContent.replace(
    /{\\(?:fonttbl|colortbl|stylesheet)[^}]*}/gi,
    "",
  );

  // Remove RTF header
  rtfContent = rtfContent.replace(/^{\\rtf1[^}]*}/i, "");

  // Remove embedded pictures, objects
  rtfContent = rtfContent.replace(/{\\\*\\shppict[^}]*}/gi, "");
  rtfContent = rtfContent.replace(/{\\object[^}]*}/gi, "");
  rtfContent = rtfContent.replace(/{\\pict[^}]*}/gi, "");

  // Remove Unicode characters like \u1234? (keep the fallback '?')
  rtfContent = rtfContent.replace(/\\u-?\d+\??/g, "");

  // Remove all other RTF control words
  rtfContent = rtfContent.replace(/\\[a-z]+\d* ?/gi, "");

  // Remove escaped hex like \'ab
  rtfContent = rtfContent.replace(/\\'[0-9a-f]{2}/gi, "");

  // Remove any leftover braces
  rtfContent = rtfContent.replace(/[{}]/g, "");

  // Replace known RTF newline/tab symbols
  rtfContent = rtfContent
    .replace(/\\par[d]?/gi, "\n")
    .replace(/\\tab/gi, "\t")
    .replace(/\\line/gi, "\n");

  // Collapse multiple spaces and newlines
  rtfContent = rtfContent.replace(/\r?\n\s*\r?\n/g, "\n"); // multiple newlines -> single
  rtfContent = rtfContent.replace(/[ \t]{2,}/g, " "); // multiple spaces/tabs -> single

  // Final clean trim§
  return rtfContent.trim();
}

export function cleanText(text: string): string {
  // Remove control characters (C0 and C1 controls)
  // Using Unicode escapes to avoid eslint `no-control-regex` error
  // \u0000-\u001F corresponds to \x00-\x1F
  // \u007F-\u009F corresponds to \x7F-\x9F
  // Remove control characters (C0 and C1 controls) using Unicode escapes to avoid eslint `no-control-regex` error
  let cleanedText = text.replace(
    new RegExp(
      [
        "[",
        "\\u0000-\\u001F", // C0 controls
        "\\u007F-\\u009F", // C1 controls
        "]",
      ].join(""),
      "g",
    ),
    "",
  );

  // Normalize spaces: replace multiple spaces, tabs, or line breaks with a single space
  cleanedText = cleanedText.replace(/\s+/g, " ").trim();

  // The previous version removed too many characters with /[^\x20-\x7E]/g
  // It also had potentially overly aggressive punctuation cleaning.
  // This simpler version focuses on removing control chars and normalizing space.

  // Optional: Further specific cleaning can be added here if needed,
  // for example, removing zero-width spaces:
  // cleanedText = cleanedText.replace(/[\u200B-\u200D\uFEFF]/g, '');

  return cleanedText;
}

export function limitWords(text: string, maxWords: number): string {
  if (!text) return "";

  const words = text.split(/\s+/); // Split by any whitespace

  if (words.length <= maxWords) {
    return text;
  }

  return words.slice(0, maxWords).join(" ");
}

export { mapLanguageCodeToPostgresConfig } from "./utils/language-mapping";