Email MBOX parser, Coupa web scraper, and Payee Central scrapers for extracting PO data and resolving Amazon site codes.
170 lines
5.4 KiB
JavaScript
170 lines
5.4 KiB
JavaScript
import { chromium } from "playwright";
|
|
import { readFileSync, writeFileSync, existsSync } from "fs";
|
|
|
|
const PO_LIST = "output/not-found-pos.json";
|
|
const OUTPUT_FILE = "output/notfound-payee-results.json";
|
|
const PROGRESS_FILE = "output/notfound-payee-progress.json";
|
|
const DELAY_MS = 800;
|
|
|
|
const allPOs = JSON.parse(readFileSync(PO_LIST, "utf-8"));
|
|
console.log(`Loaded ${allPOs.length} POs to scrape from Payee Central`);
|
|
|
|
let completed = {};
|
|
if (existsSync(PROGRESS_FILE)) {
|
|
completed = JSON.parse(readFileSync(PROGRESS_FILE, "utf-8"));
|
|
console.log(`Resuming: ${Object.keys(completed).length} already scraped`);
|
|
}
|
|
|
|
const remaining = allPOs.filter((po) => !completed[po]);
|
|
console.log(`Remaining: ${remaining.length} POs\n`);
|
|
|
|
if (remaining.length === 0) {
|
|
console.log("All POs already scraped!");
|
|
process.exit(0);
|
|
}
|
|
|
|
function poUrl(po) {
|
|
return `https://payeecentral.amazon.com/PurchaseOrder/Details?poNumber=${po}`;
|
|
}
|
|
|
|
const userDataDir = new URL("./chrome-profile", import.meta.url).pathname;
|
|
const context = await chromium.launchPersistentContext(userDataDir, {
|
|
headless: false,
|
|
channel: "chrome",
|
|
args: ["--disable-blink-features=AutomationControlled"],
|
|
ignoreDefaultArgs: ["--enable-automation"],
|
|
});
|
|
|
|
const page = context.pages()[0] || (await context.newPage());
|
|
|
|
console.log("Opening Payee Central...");
|
|
await page.goto(poUrl(remaining[0]), { waitUntil: "networkidle", timeout: 30000 });
|
|
|
|
if (page.url().includes("signin") || page.url().includes("/ap/")) {
|
|
console.log("\n🔐 Login required. Please sign in in the browser window...");
|
|
await page.waitForURL(
|
|
(u) => {
|
|
const s = u.toString();
|
|
return s.includes("payeecentral.amazon.com") && !s.includes("signin") && !s.includes("/ap/");
|
|
},
|
|
{ timeout: 180000 }
|
|
);
|
|
console.log("✅ Logged in!\n");
|
|
}
|
|
|
|
let results = [];
|
|
if (existsSync(OUTPUT_FILE)) {
|
|
results = JSON.parse(readFileSync(OUTPUT_FILE, "utf-8"));
|
|
}
|
|
|
|
let scraped = 0;
|
|
let errors = 0;
|
|
let consecutiveErrors = 0;
|
|
const startTime = Date.now();
|
|
|
|
for (const po of remaining) {
|
|
try {
|
|
await page.goto(poUrl(po), { waitUntil: "networkidle", timeout: 20000 });
|
|
|
|
if (page.url().includes("signin") || page.url().includes("/ap/")) {
|
|
console.log("\n🔐 Session expired. Please log in again...");
|
|
await page.waitForURL(
|
|
(u) => !u.toString().includes("signin") && !u.toString().includes("/ap/"),
|
|
{ timeout: 180000 }
|
|
);
|
|
await page.goto(poUrl(po), { waitUntil: "networkidle", timeout: 20000 });
|
|
}
|
|
|
|
await page.waitForTimeout(500);
|
|
const bodyText = await page.innerText("body");
|
|
|
|
const shipToMatch = bodyText.match(/Ship To\s+([\s\S]*?)(?=Payee Central Account)/);
|
|
const shipTo = shipToMatch ? shipToMatch[1].trim() : null;
|
|
|
|
let siteCode = null;
|
|
if (shipTo) {
|
|
const m = shipTo.match(/\(([A-Z0-9]{3,5})\)/);
|
|
if (m) siteCode = m[1];
|
|
if (!siteCode) {
|
|
const m2 = shipTo.match(/(?:LLC|Inc)\s*-\s*([A-Z0-9]{3,5})\b/);
|
|
if (m2) siteCode = m2[1];
|
|
}
|
|
if (!siteCode) {
|
|
const m3 = shipTo.match(/LLC\s+([A-Z0-9]{3,5})\b/);
|
|
if (m3) siteCode = m3[1];
|
|
}
|
|
if (!siteCode) {
|
|
const m4 = shipTo.match(/^([A-Z0-9]{3,5})\s*-\s*Amazon/m);
|
|
if (m4) siteCode = m4[1];
|
|
}
|
|
if (!siteCode) {
|
|
const m5 = shipTo.match(/Amazon\s+Fresh\s+([A-Z0-9]{3,5})\b/);
|
|
if (m5) siteCode = m5[1];
|
|
}
|
|
}
|
|
|
|
const lineItems = await page.$$eval(
|
|
"table tbody tr",
|
|
(rows) =>
|
|
rows.map((row) => {
|
|
const cells = row.querySelectorAll("td");
|
|
if (cells.length < 7) return null;
|
|
return {
|
|
description: cells[1]?.textContent?.trim() || null,
|
|
need_by: cells[2]?.textContent?.trim() || null,
|
|
quantity: cells[3]?.textContent?.trim() || null,
|
|
unit: cells[4]?.textContent?.trim() || null,
|
|
price: cells[5]?.textContent?.trim() || null,
|
|
amount: cells[6]?.textContent?.trim() || null,
|
|
};
|
|
}).filter(Boolean)
|
|
).catch(() => []);
|
|
|
|
const result = {
|
|
po_number: po,
|
|
site_code: siteCode,
|
|
ship_to_raw: shipTo,
|
|
line_items: lineItems,
|
|
};
|
|
|
|
results.push(result);
|
|
completed[po] = true;
|
|
scraped++;
|
|
consecutiveErrors = 0;
|
|
|
|
const elapsed = (Date.now() - startTime) / 1000;
|
|
const rate = scraped / elapsed;
|
|
const eta = Math.round((remaining.length - scraped) / rate);
|
|
const etaMin = Math.floor(eta / 60);
|
|
const etaSec = eta % 60;
|
|
|
|
const desc0 = lineItems[0]?.description?.substring(0, 40) || "no items";
|
|
process.stdout.write(
|
|
`\r[${scraped}/${remaining.length}] ${po} | ${siteCode || "?"} | ${desc0} | ETA: ${etaMin}m${etaSec}s `
|
|
);
|
|
|
|
if (scraped % 10 === 0) {
|
|
writeFileSync(OUTPUT_FILE, JSON.stringify(results, null, 2));
|
|
writeFileSync(PROGRESS_FILE, JSON.stringify(completed));
|
|
}
|
|
} catch (err) {
|
|
console.error(`\n [${po}] Error: ${err.message}`);
|
|
errors++;
|
|
consecutiveErrors++;
|
|
if (consecutiveErrors > 10) {
|
|
console.error("Too many consecutive errors, stopping.");
|
|
break;
|
|
}
|
|
}
|
|
|
|
await page.waitForTimeout(DELAY_MS);
|
|
}
|
|
|
|
writeFileSync(OUTPUT_FILE, JSON.stringify(results, null, 2));
|
|
writeFileSync(PROGRESS_FILE, JSON.stringify(completed));
|
|
|
|
console.log(`\n\nDone! Scraped: ${scraped}, Errors: ${errors}`);
|
|
console.log(`Total in output: ${results.length} POs`);
|
|
console.log(`Results saved to ${OUTPUT_FILE}`);
|
|
|
|
await context.close();
|