style: apply prettier formatting

Apply consistent formatting across all files (line endings, spacing)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Misaka
2026-03-01 14:57:38 +08:00
parent 8f6ca7b453
commit c39e1504aa
17 changed files with 631 additions and 634 deletions

View File

@@ -1,19 +1,19 @@
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'; import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'
import { ERP_LOCATORS } from './locators'; import { ERP_LOCATORS } from './locators'
import type { ErpConfig, ErpSession } from '../../types/erp.types'; import type { ErpConfig, ErpSession } from '../../types/erp.types'
/** /**
* ERP Authentication Service * ERP Authentication Service
* Manages login session and browser lifecycle * Manages login session and browser lifecycle
*/ */
export class ErpAuthService { export class ErpAuthService {
private config: ErpConfig; private config: ErpConfig
private session: ErpSession | null = null; private session: ErpSession | null = null
private ignoreHTTPSErrors: boolean; private ignoreHTTPSErrors: boolean
constructor(config: ErpConfig) { constructor(config: ErpConfig) {
this.config = config; this.config = config
this.ignoreHTTPSErrors = process.env.ERP_IGNORE_HTTPS_ERRORS === 'true'; this.ignoreHTTPSErrors = process.env.ERP_IGNORE_HTTPS_ERRORS === 'true'
} }
/** /**
@@ -21,7 +21,7 @@ export class ErpAuthService {
*/ */
async login(): Promise<ErpSession> { async login(): Promise<ErpSession> {
if (this.session?.isLoggedIn) { if (this.session?.isLoggedIn) {
return this.session; return this.session
} }
// Launch browser with SSL certificate errors ignored // Launch browser with SSL certificate errors ignored
@@ -33,9 +33,9 @@ export class ErpAuthService {
'--ignore-certificate-errors', '--ignore-certificate-errors',
'--ignore-ssl-errors', '--ignore-ssl-errors',
'--ignore-certificate-errors-spki-list', '--ignore-certificate-errors-spki-list',
'--disable-web-security', // Disable web security for internal VPN '--disable-web-security' // Disable web security for internal VPN
], ]
}); })
const context = await browser.newContext({ const context = await browser.newContext({
acceptDownloads: true, acceptDownloads: true,
@@ -43,76 +43,76 @@ export class ErpAuthService {
ignoreHTTPSErrors: true, // Ignore SSL certificate errors ignoreHTTPSErrors: true, // Ignore SSL certificate errors
acceptAllDownloads: true, // Accept all downloads acceptAllDownloads: true, // Accept all downloads
// Disable web security for internal VPN // Disable web security for internal VPN
javaScriptEnabled: true, javaScriptEnabled: true
}); })
const page = await context.newPage(); const page = await context.newPage()
// Navigate to login page (use actual login URL from Python code) // Navigate to login page (use actual login URL from Python code)
const loginUrl = `${this.config.url}/yonbip/resources/uap/rbac/login/main/index.html`; const loginUrl = `${this.config.url}/yonbip/resources/uap/rbac/login/main/index.html`
await page.goto(loginUrl); await page.goto(loginUrl)
// Wait for page to load // Wait for page to load
await page.waitForLoadState('domcontentloaded', { timeout: 10000 }); await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
// Wait for iframe to be present // Wait for iframe to be present
await page.waitForSelector('#forwardFrame', { state: 'attached', timeout: 15000 }); await page.waitForSelector('#forwardFrame', { state: 'attached', timeout: 15000 })
// Extract forwardFrame (Python: main_frame = page.locator("#forwardFrame").content_frame) // Extract forwardFrame (Python: main_frame = page.locator("#forwardFrame").content_frame)
// This is the main working frame for all subsequent operations // This is the main working frame for all subsequent operations
const frameLocator = page.locator('#forwardFrame'); const frameLocator = page.locator('#forwardFrame')
const contentFrame = await frameLocator.contentFrame(); const contentFrame = await frameLocator.contentFrame()
if (!contentFrame) { if (!contentFrame) {
throw new Error('Failed to access forwardFrame content frame'); throw new Error('Failed to access forwardFrame content frame')
} }
// Store reference to main frame for later use (Python returns this as main_frame) // Store reference to main frame for later use (Python returns this as main_frame)
const mainFrame = contentFrame; const mainFrame = contentFrame
// Fill username using role-based locator (Python: get_by_role("textbox", name="用户名")) // Fill username using role-based locator (Python: get_by_role("textbox", name="用户名"))
try { try {
await contentFrame.getByRole('textbox', { name: '用户名' }).fill(this.config.username); await contentFrame.getByRole('textbox', { name: '用户名' }).fill(this.config.username)
} catch (e) { } catch (e) {
throw new Error(`Failed to find username input: ${e}`); throw new Error(`Failed to find username input: ${e}`)
} }
// Fill password using role-based locator (Python: get_by_role("textbox", name="密码")) // Fill password using role-based locator (Python: get_by_role("textbox", name="密码"))
try { try {
await contentFrame.getByRole('textbox', { name: '密码' }).fill(this.config.password); await contentFrame.getByRole('textbox', { name: '密码' }).fill(this.config.password)
} catch (e) { } catch (e) {
throw new Error(`Failed to find password input: ${e}`); throw new Error(`Failed to find password input: ${e}`)
} }
// Click login button using role-based locator (Python: get_by_role("button", name="登录")) // Click login button using role-based locator (Python: get_by_role("button", name="登录"))
try { try {
await contentFrame.getByRole('button', { name: '登录' }).click(); await contentFrame.getByRole('button', { name: '登录' }).click()
} catch (e) { } catch (e) {
throw new Error(`Failed to click login button: ${e}`); throw new Error(`Failed to click login button: ${e}`)
} }
// Wait for navigation after login // Wait for navigation after login
// The login will redirect to the main page which has a different structure // The login will redirect to the main page which has a different structure
try { try {
await page.waitForLoadState('domcontentloaded', { timeout: 10000 }); await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
} catch (e) { } catch (e) {
console.log('Page load state check timed out, continuing...'); console.log('Page load state check timed out, continuing...')
} }
// Handle force login confirmation dialog if present (Python: get_by_role("button", name="确定")) // Handle force login confirmation dialog if present (Python: get_by_role("button", name="确定"))
try { try {
const confirmBtn = mainFrame.getByRole('button', { name: '确定' }); const confirmBtn = mainFrame.getByRole('button', { name: '确定' })
const count = await confirmBtn.count(); const count = await confirmBtn.count()
if (count > 0) { if (count > 0) {
console.log('Force login detected, clicking confirm button'); console.log('Force login detected, clicking confirm button')
await confirmBtn.first().click(); await confirmBtn.first().click()
await page.waitForTimeout(2000); await page.waitForTimeout(2000)
} else { } else {
console.log('Normal login, no confirmation dialog'); console.log('Normal login, no confirmation dialog')
} }
} catch (e) { } catch (e) {
// No force login dialog, continue // No force login dialog, continue
console.log('Normal login, no confirmation dialog'); console.log('Normal login, no confirmation dialog')
} }
// Create session with mainFrame (Python returns main_frame as part of login result) // Create session with mainFrame (Python returns main_frame as part of login result)
@@ -121,10 +121,10 @@ export class ErpAuthService {
context, context,
page, page,
mainFrame, // Store forwardFrame content frame for subsequent operations mainFrame, // Store forwardFrame content frame for subsequent operations
isLoggedIn: true, isLoggedIn: true
}; }
return this.session; return this.session
} }
/** /**
@@ -132,9 +132,9 @@ export class ErpAuthService {
*/ */
async close(): Promise<void> { async close(): Promise<void> {
if (this.session) { if (this.session) {
await this.session.context.close(); await this.session.context.close()
await this.session.browser.close(); await this.session.browser.close()
this.session = null; this.session = null
} }
} }
@@ -143,15 +143,15 @@ export class ErpAuthService {
*/ */
getSession(): ErpSession { getSession(): ErpSession {
if (!this.session?.isLoggedIn) { if (!this.session?.isLoggedIn) {
throw new Error('Not logged in. Call login() first.'); throw new Error('Not logged in. Call login() first.')
} }
return this.session; return this.session
} }
/** /**
* Check if session is active * Check if session is active
*/ */
isActive(): boolean { isActive(): boolean {
return this.session?.isLoggedIn ?? false; return this.session?.isLoggedIn ?? false
} }
} }

View File

@@ -1,9 +1,9 @@
import path from 'path'; import path from 'path'
import fs from 'fs/promises'; import fs from 'fs/promises'
import { ERP_LOCATORS } from './locators'; import { ERP_LOCATORS } from './locators'
import { ErpAuthService } from './erp-auth'; import { ErpAuthService } from './erp-auth'
import type { ExtractorInput, ExtractorResult } from '../../types/extractor.types'; import type { ExtractorInput, ExtractorResult } from '../../types/extractor.types'
import type { ErpSession } from '../../types/erp.types'; import type { ErpSession } from '../../types/erp.types'
/** /**
* ERP Data Extractor Service * ERP Data Extractor Service
@@ -12,15 +12,15 @@ import type { ErpSession } from '../../types/erp.types';
* Reference: playwrite/utils/discrete_material_plan_extractor.py * Reference: playwrite/utils/discrete_material_plan_extractor.py
*/ */
export class ExtractorService { export class ExtractorService {
private authService: ErpAuthService; private authService: ErpAuthService
private downloadDir: string; private downloadDir: string
constructor(authService: ErpAuthService, downloadDir = './downloads') { constructor(authService: ErpAuthService, downloadDir = './downloads') {
this.authService = authService; this.authService = authService
this.downloadDir = downloadDir; this.downloadDir = downloadDir
// Ensure download directory exists // Ensure download directory exists
fs.mkdir(downloadDir, { recursive: true }).catch(() => {}); fs.mkdir(downloadDir, { recursive: true }).catch(() => {})
} }
/** /**
@@ -31,43 +31,49 @@ export class ExtractorService {
downloadedFiles: [], downloadedFiles: [],
mergedFile: null, mergedFile: null,
recordCount: 0, recordCount: 0,
errors: [], errors: []
}; }
try { try {
const session = this.authService.getSession(); const session = this.authService.getSession()
// Navigate to extractor page and get popup page + work frame // Navigate to extractor page and get popup page + work frame
const { popupPage, workFrame } = await this.navigateToExtractorPage(session); const { popupPage, workFrame } = await this.navigateToExtractorPage(session)
// Process orders in batches // Process orders in batches
const batchSize = input.batchSize || 100; const batchSize = input.batchSize || 100
const batches = this.createBatches(input.orderNumbers, batchSize); const batches = this.createBatches(input.orderNumbers, batchSize)
for (let i = 0; i < batches.length; i++) { for (let i = 0; i < batches.length; i++) {
const batch = batches[i]; const batch = batches[i]
const progress = ((i + 1) / batches.length) * 100; const progress = ((i + 1) / batches.length) * 100
input.onProgress?.(`Processing batch ${i + 1}/${batches.length}`, progress); input.onProgress?.(`Processing batch ${i + 1}/${batches.length}`, progress)
try { try {
const filePath = await this.downloadBatch(session, popupPage, workFrame, batch, i, batches.length); const filePath = await this.downloadBatch(
result.downloadedFiles.push(filePath); session,
popupPage,
workFrame,
batch,
i,
batches.length
)
result.downloadedFiles.push(filePath)
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'; const message = error instanceof Error ? error.message : 'Unknown error'
result.errors.push(`Batch ${i + 1}: ${message}`); result.errors.push(`Batch ${i + 1}: ${message}`)
} }
} }
// TODO: Merge files (implement in separate task) // TODO: Merge files (implement in separate task)
// result.mergedFile = await this.mergeFiles(result.downloadedFiles); // result.mergedFile = await this.mergeFiles(result.downloadedFiles);
} catch (error) { } catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'; const message = error instanceof Error ? error.message : 'Unknown error'
result.errors.push(`Extraction failed: ${message}`); result.errors.push(`Extraction failed: ${message}`)
} }
return result; return result
} }
/** /**
@@ -81,39 +87,41 @@ export class ExtractorService {
* 4. f_frame.locator("#mainiframe").content_frame - Get nested inner frame * 4. f_frame.locator("#mainiframe").content_frame - Get nested inner frame
* 5. setup_query_interface(work_frame) - Setup query interface * 5. setup_query_interface(work_frame) - Setup query interface
*/ */
private async navigateToExtractorPage(session: ErpSession): Promise<{ popupPage: any; workFrame: any }> { private async navigateToExtractorPage(
const { page, mainFrame } = session; session: ErpSession
): Promise<{ popupPage: any; workFrame: any }> {
const { page, mainFrame } = session
// Step 1: Click menu icon (Python line 266) // Step 1: Click menu icon (Python line 266)
// main_frame is #forwardFrame.content_frame returned from login // main_frame is #forwardFrame.content_frame returned from login
await mainFrame.locator('i').first().click(); await mainFrame.locator('i').first().click()
// Step 2: Click discrete material plan menu item and expect popup (Python lines 267-271) // Step 2: Click discrete material plan menu item and expect popup (Python lines 267-271)
const popupPromise = page.waitForEvent('popup'); const popupPromise = page.waitForEvent('popup')
await mainFrame.getByTitle('离散备料计划维护', { exact: true }).first().click(); await mainFrame.getByTitle('离散备料计划维护', { exact: true }).first().click()
const popupPage = await popupPromise; const popupPage = await popupPromise
// Step 3 & 4: Get nested frame structure in popup window (Python lines 273-276) // Step 3 & 4: Get nested frame structure in popup window (Python lines 273-276)
// popup page contains #forwardFrame, which contains #mainiframe // popup page contains #forwardFrame, which contains #mainiframe
const forwardFrameLocator = popupPage.locator('#forwardFrame'); const forwardFrameLocator = popupPage.locator('#forwardFrame')
const fFrame = await forwardFrameLocator.contentFrame(); const fFrame = await forwardFrameLocator.contentFrame()
if (!fFrame) { if (!fFrame) {
throw new Error('Failed to access popup forward frame'); throw new Error('Failed to access popup forward frame')
} }
const innerFrameLocator = fFrame.locator('#mainiframe'); const innerFrameLocator = fFrame.locator('#mainiframe')
await innerFrameLocator.waitFor({ state: 'visible', timeout: 15000 }); await innerFrameLocator.waitFor({ state: 'visible', timeout: 15000 })
const workFrame = await innerFrameLocator.contentFrame(); const workFrame = await innerFrameLocator.contentFrame()
if (!workFrame) { if (!workFrame) {
throw new Error('Failed to access inner work frame'); throw new Error('Failed to access inner work frame')
} }
// Step 5: Setup query interface (Python line 278) // Step 5: Setup query interface (Python line 278)
await this.setupQueryInterface(workFrame); await this.setupQueryInterface(workFrame)
return { popupPage, workFrame }; return { popupPage, workFrame }
} }
/** /**
@@ -122,18 +130,18 @@ export class ExtractorService {
*/ */
private async setupQueryInterface(innerFrame: any): Promise<void> { private async setupQueryInterface(innerFrame: any): Promise<void> {
// Click search icon (Python line 233) // Click search icon (Python line 233)
await innerFrame.locator('.search-name-wrapper > .iconfont').click(); await innerFrame.locator('.search-name-wrapper > .iconfont').click()
// Click "订单号查询" menu item (Python line 234) // Click "订单号查询" menu item (Python line 234)
await innerFrame.getByText('订单号查询').click(); await innerFrame.getByText('订单号查询').click()
// Click "全部" tab (Python line 235) // Click "全部" tab (Python line 235)
await innerFrame.getByRole('tab', { name: '全部' }).click(); await innerFrame.getByRole('tab', { name: '全部' }).click()
// Set limit to 5000 (Python lines 237-239) // Set limit to 5000 (Python lines 237-239)
const inputBox = innerFrame.locator('#rc_select_0'); const inputBox = innerFrame.locator('#rc_select_0')
await inputBox.fill('5000'); await inputBox.fill('5000')
await inputBox.press('Enter'); await inputBox.press('Enter')
} }
/** /**
@@ -149,43 +157,40 @@ export class ExtractorService {
totalBatches: number totalBatches: number
): Promise<string> { ): Promise<string> {
// Fill order numbers (Python lines 143-145) // Fill order numbers (Python lines 143-145)
const textbox = workFrame.getByRole('textbox', { name: '来源生产订单号' }); const textbox = workFrame.getByRole('textbox', { name: '来源生产订单号' })
await textbox.fill(''); await textbox.fill('')
await textbox.fill(orderNumbers.join(',')); await textbox.fill(orderNumbers.join(','))
// Click search button (Python line 147) // Click search button (Python line 147)
await workFrame.locator('.search-component-searchBtn').click(); await workFrame.locator('.search-component-searchBtn').click()
// Wait for loading (Python lines 148-153) // Wait for loading (Python lines 148-153)
await this.waitForLoading(workFrame); await this.waitForLoading(workFrame)
// Click first row checkbox (Python line 155) // Click first row checkbox (Python line 155)
await workFrame.getByRole('row', { name: '序号' }).getByLabel('').click(); await workFrame.getByRole('row', { name: '序号' }).getByLabel('').click()
// Hover and click "更多" button (Python lines 156-157) // Hover and click "更多" button (Python lines 156-157)
await workFrame.getByRole('button', { name: '更多' }).hover(); await workFrame.getByRole('button', { name: '更多' }).hover()
await workFrame.getByText('输出', { exact: true }).click(); await workFrame.getByText('输出', { exact: true }).click()
// Set threshold (Python lines 159-164) // Set threshold (Python lines 159-164)
const thresholdBox = workFrame const thresholdBox = workFrame
.locator('div') .locator('div')
.filter({ hasText: /^行数阈值$/ }) .filter({ hasText: /^行数阈值$/ })
.locator('input[type="text"]'); .locator('input[type="text"]')
await thresholdBox.fill('300000'); await thresholdBox.fill('300000')
// Setup download handler and click confirm (Python lines 166-172) // Setup download handler and click confirm (Python lines 166-172)
const downloadPath = path.join( const downloadPath = path.join(this.downloadDir, `temp_batch_${batchIndex + 1}.xlsx`)
this.downloadDir,
`temp_batch_${batchIndex + 1}.xlsx`
);
const downloadPromise = popupPage.waitForEvent('download'); const downloadPromise = popupPage.waitForEvent('download')
await workFrame.getByRole('button', { name: '确定(Y)' }).click(); await workFrame.getByRole('button', { name: '确定(Y)' }).click()
const download = await downloadPromise; const download = await downloadPromise
await download.saveAs(downloadPath); await download.saveAs(downloadPath)
return downloadPath; return downloadPath
} }
/** /**
@@ -193,11 +198,14 @@ export class ExtractorService {
* Reference: Python lines 148-153 * Reference: Python lines 148-153
*/ */
private async waitForLoading(workFrame: any): Promise<void> { private async waitForLoading(workFrame: any): Promise<void> {
const loadingLocator = workFrame.locator('div').filter({ hasText: ERP_LOCATORS.extractor.loadingText }).nth(1); const loadingLocator = workFrame
.locator('div')
.filter({ hasText: ERP_LOCATORS.extractor.loadingText })
.nth(1)
try { try {
await loadingLocator.waitFor({ state: 'visible', timeout: 3000 }); await loadingLocator.waitFor({ state: 'visible', timeout: 3000 })
await loadingLocator.waitFor({ state: 'hidden', timeout: 0 }); await loadingLocator.waitFor({ state: 'hidden', timeout: 0 })
} catch { } catch {
// Loading completed quickly or never appeared // Loading completed quickly or never appeared
} }
@@ -208,10 +216,10 @@ export class ExtractorService {
* Reference: Python group_order_ids() method lines 128-131 * Reference: Python group_order_ids() method lines 128-131
*/ */
private createBatches<T>(items: T[], batchSize: number): T[][] { private createBatches<T>(items: T[], batchSize: number): T[][] {
const batches: T[][] = []; const batches: T[][] = []
for (let i = 0; i < items.length; i += batchSize) { for (let i = 0; i < items.length; i += batchSize) {
batches.push(items.slice(i, i + batchSize)); batches.push(items.slice(i, i + batchSize))
} }
return batches; return batches
} }
} }

View File

@@ -9,7 +9,7 @@ export const ERP_LOCATORS = {
login: { login: {
usernameInput: '#username', usernameInput: '#username',
passwordInput: '#password', passwordInput: '#password',
submitButton: 'button[type="submit"]', submitButton: 'button[type="submit"]'
}, },
// Main Frame // Main Frame
@@ -22,7 +22,7 @@ export const ERP_LOCATORS = {
// Inner iframe (inside forward frame) // Inner iframe (inside forward frame)
innerIframe: '#mainiframe', innerIframe: '#mainiframe',
// Loading overlay text // Loading overlay text
loadingText: '加载中', loadingText: '加载中'
}, },
// Extractor (Data Export) Page // Extractor (Data Export) Page
@@ -43,7 +43,7 @@ export const ERP_LOCATORS = {
// Export dialog - threshold input // Export dialog - threshold input
thresholdInputSelector: 'div:has-text(/^行数阈值$/) input[type="text"]', thresholdInputSelector: 'div:has-text(/^行数阈值$/) input[type="text"]',
// Confirm button // Confirm button
confirmButton: 'internal:has-text="确定(Y)"', confirmButton: 'internal:has-text="确定(Y)"'
}, },
// Menu navigation // Menu navigation
@@ -55,7 +55,7 @@ export const ERP_LOCATORS = {
// "All" tab // "All" tab
allTab: 'internal:role=tab[name="全部"]', allTab: 'internal:role=tab[name="全部"]',
// Select input for setting limits // Select input for setting limits
selectInput: '#rc_select_0', selectInput: '#rc_select_0'
}, },
// Discrete material plan menu item // Discrete material plan menu item
@@ -65,7 +65,7 @@ export const ERP_LOCATORS = {
cleaner: { cleaner: {
orderNumberInput: 'input[name="orderNumber"]', orderNumberInput: 'input[name="orderNumber"]',
materialGrid: 'table.material-grid tbody tr', materialGrid: 'table.material-grid tbody tr',
saveButton: 'button:has-text("保存")', saveButton: 'button:has-text("保存")'
}, },
// Common Elements // Common Elements
@@ -74,6 +74,6 @@ export const ERP_LOCATORS = {
errorMessage: '.message.error', errorMessage: '.message.error',
confirmDialog: '.confirm-dialog', confirmDialog: '.confirm-dialog',
confirmButton: 'button:has-text("确定")', confirmButton: 'button:has-text("确定")',
cancelButton: 'button:has-text("取消")', cancelButton: 'button:has-text("取消")'
}, }
}; }

View File

@@ -1,10 +1,6 @@
import ExcelJS from 'exceljs'; import ExcelJS from 'exceljs'
import type { import type { DiscreteMaterialPlan, ExcelParseOptions, OrderHeader } from '../../types/excel.types'
DiscreteMaterialPlan, import path from 'path'
ExcelParseOptions,
OrderHeader,
} from '../../types/excel.types';
import path from 'path';
/** /**
* Excel Parser Service * Excel Parser Service
@@ -21,8 +17,8 @@ export class ExcelParser {
// Field name mapping for Python compatibility (from Python code) // Field name mapping for Python compatibility (from Python code)
private FIELD_NAME_MAPPING: Record<string, string> = { private FIELD_NAME_MAPPING: Record<string, string> = {
: '产品计划数量', : '产品计划数量',
: '产品单位', : '产品单位'
}; }
// Mapping from Chinese field names to English property names // Mapping from Chinese field names to English property names
private CHINESE_TO_ENGLISH_MAPPING: Record<string, string> = { private CHINESE_TO_ENGLISH_MAPPING: Record<string, string> = {
@@ -40,18 +36,18 @@ export class ExcelParser {
: 'printDate', : 'printDate',
// Mapped fields (after FIELD_NAME_MAPPING) // Mapped fields (after FIELD_NAME_MAPPING)
: 'plannedQuantity', : 'plannedQuantity',
: 'unit', : 'unit'
}; }
private verbose: boolean; private verbose: boolean
constructor(options: ExcelParseOptions = {}) { constructor(options: ExcelParseOptions = {}) {
this.verbose = options.verbose || false; this.verbose = options.verbose || false
} }
private log(...args: any[]): void { private log(...args: any[]): void {
if (this.verbose) { if (this.verbose) {
console.log('[ExcelParser]', ...args); console.log('[ExcelParser]', ...args)
} }
} }
@@ -59,40 +55,40 @@ export class ExcelParser {
* Parse Excel file and extract material plans * Parse Excel file and extract material plans
*/ */
async parse(filePath: string, options: ExcelParseOptions = {}): Promise<DiscreteMaterialPlan[]> { async parse(filePath: string, options: ExcelParseOptions = {}): Promise<DiscreteMaterialPlan[]> {
this.log('Parsing Excel file:', filePath); this.log('Parsing Excel file:', filePath)
const workbook = new ExcelJS.Workbook(); const workbook = new ExcelJS.Workbook()
await workbook.xlsx.readFile(filePath); await workbook.xlsx.readFile(filePath)
const worksheet = workbook.worksheets[0]; const worksheet = workbook.worksheets[0]
if (!worksheet) { if (!worksheet) {
throw new Error('No worksheet found in file'); throw new Error('No worksheet found in file')
} }
const plans: DiscreteMaterialPlan[] = []; const plans: DiscreteMaterialPlan[] = []
const allRows: any[][] = []; const allRows: any[][] = []
// Read all rows into memory // Read all rows into memory
worksheet.eachRow((row, rowNumber) => { worksheet.eachRow((row, rowNumber) => {
allRows.push(row.values as any[]); allRows.push(row.values as any[])
}); })
this.log(`Total rows read: ${allRows.length} (worksheet has ${worksheet.rowCount} rows)`); this.log(`Total rows read: ${allRows.length} (worksheet has ${worksheet.rowCount} rows)`)
// Parse orders from rows // Parse orders from rows
const orders = this.parseOrders(allRows); const orders = this.parseOrders(allRows)
// Store orders for potential Excel export // Store orders for potential Excel export
(this as any).lastOrders = orders; ;(this as any).lastOrders = orders
// Flatten orders into material plans // Flatten orders into material plans
for (const order of orders) { for (const order of orders) {
const { orderInfo, materials } = order; const { orderInfo, materials } = order
// Skip empty orders if option is set // Skip empty orders if option is set
if (options.skipEmptyOrders && materials.length === 0) { if (options.skipEmptyOrders && materials.length === 0) {
this.log('Skipping empty order:', orderInfo.productionOrder); this.log('Skipping empty order:', orderInfo.productionOrder)
continue; continue
} }
// Create a material plan for each material row // Create a material plan for each material row
@@ -112,15 +108,15 @@ export class ExcelParser {
warehouse: material.warehouse, warehouse: material.warehouse,
unitUsage: material.unitUsage, unitUsage: material.unitUsage,
cumulativeOutboundQty: material.cumulativeOutboundQty, cumulativeOutboundQty: material.cumulativeOutboundQty,
rowNumber: material.rowNumber, rowNumber: material.rowNumber
}; }
plans.push(plan); plans.push(plan)
} }
} }
this.log(`Parsed ${plans.length} material plans from ${orders.length} orders`); this.log(`Parsed ${plans.length} material plans from ${orders.length} orders`)
return plans; return plans
} }
/** /**
@@ -131,15 +127,15 @@ export class ExcelParser {
* @param outputPath - Output Excel file path * @param outputPath - Output Excel file path
*/ */
async saveAsExcel(outputPath: string): Promise<void> { async saveAsExcel(outputPath: string): Promise<void> {
const orders = (this as any).lastOrders; const orders = (this as any).lastOrders
if (!orders) { if (!orders) {
throw new Error('No parsed data available. Call parse() first.'); throw new Error('No parsed data available. Call parse() first.')
} }
this.log('Saving parsed data to Excel:', outputPath); this.log('Saving parsed data to Excel:', outputPath)
const workbook = new ExcelJS.Workbook(); const workbook = new ExcelJS.Workbook()
const worksheet = workbook.addWorksheet('Data'); const worksheet = workbook.addWorksheet('Data')
// Define columns matching Python excel_converter output format exactly // Define columns matching Python excel_converter output format exactly
worksheet.columns = [ worksheet.columns = [
@@ -172,12 +168,12 @@ export class ExcelParser {
{ header: '单位用量', key: 'unitUsage', width: 12 }, { header: '单位用量', key: 'unitUsage', width: 12 },
{ header: '累计出库数量', key: 'cumulativeOutboundQty', width: 15 }, { header: '累计出库数量', key: 'cumulativeOutboundQty', width: 15 },
{ header: '打印人', key: 'printer', width: 15 }, { header: '打印人', key: 'printer', width: 15 },
{ header: '打印日期', key: 'printDate', width: 20 }, { header: '打印日期', key: 'printDate', width: 20 }
]; ]
// Add data rows - merge orderInfo with each material // Add data rows - merge orderInfo with each material
for (const order of orders) { for (const order of orders) {
const { orderInfo, materials } = order; const { orderInfo, materials } = order
for (const material of materials) { for (const material of materials) {
worksheet.addRow({ worksheet.addRow({
@@ -213,14 +209,16 @@ export class ExcelParser {
cumulativeOutboundQty: material.cumulativeOutboundQty || 0, cumulativeOutboundQty: material.cumulativeOutboundQty || 0,
// Footer info (last 2 columns) // Footer info (last 2 columns)
printer: orderInfo.printer || '', printer: orderInfo.printer || '',
printDate: orderInfo.printDate || '', printDate: orderInfo.printDate || ''
}); })
} }
} }
// Save workbook // Save workbook
await workbook.xlsx.writeFile(outputPath); await workbook.xlsx.writeFile(outputPath)
this.log(`Excel file saved: ${outputPath} (${orders.length} orders, ${worksheet.rowCount - 1} data rows)`); this.log(
`Excel file saved: ${outputPath} (${orders.length} orders, ${worksheet.rowCount - 1} data rows)`
)
} }
/** /**
@@ -228,64 +226,54 @@ export class ExcelParser {
* Reference: _parse_sheet() in Python code * Reference: _parse_sheet() in Python code
*/ */
private parseOrders(allRows: any[][]): Array<{ orderInfo: OrderHeader; materials: any[] }> { private parseOrders(allRows: any[][]): Array<{ orderInfo: OrderHeader; materials: any[] }> {
const orders: Array<{ orderInfo: OrderHeader; materials: any[] }> = []; const orders: Array<{ orderInfo: OrderHeader; materials: any[] }> = []
let i = 0; let i = 0
while (i < allRows.length) { while (i < allRows.length) {
const row = allRows[i]; const row = allRows[i]
// Check if this is an order title row // Check if this is an order title row
if (row && row[2] && String(row[2]).includes('离散备料计划')) { if (row && row[2] && String(row[2]).includes('离散备料计划')) {
// Parse order header info (next 4 rows) // Parse order header info (next 4 rows)
const orderInfo: OrderHeader = {}; const orderInfo: OrderHeader = {}
for (let j = 1; j <= 4; j++) { for (let j = 1; j <= 4; j++) {
if (i + j < allRows.length && allRows[i + j]) { if (i + j < allRows.length && allRows[i + j]) {
this.parseHeaderRow(allRows[i + j], orderInfo); this.parseHeaderRow(allRows[i + j], orderInfo)
} }
} }
// Debug: check productionOrder extraction // Debug: check productionOrder extraction
this.log(`Order ${orders.length + 1}: productionOrder="${orderInfo.productionOrder}"`); this.log(`Order ${orders.length + 1}: productionOrder="${orderInfo.productionOrder}"`)
// Find table header row dynamically (look for "序号" in index 1) // Find table header row dynamically (look for "序号" in index 1)
// Note: worksheet.eachRow() skips empty rows, so we can't use fixed offsets // Note: worksheet.eachRow() skips empty rows, so we can't use fixed offsets
let tableRow = i + 1; let tableRow = i + 1
while ( while (tableRow < allRows.length && allRows[tableRow] && allRows[tableRow][1] !== '序号') {
tableRow < allRows.length && tableRow++
allRows[tableRow] &&
allRows[tableRow][1] !== '序号'
) {
tableRow++;
} }
if (tableRow >= allRows.length || !allRows[tableRow]) { if (tableRow >= allRows.length || !allRows[tableRow]) {
this.log(' ⚠️ Table header not found, skipping this order'); this.log(' ⚠️ Table header not found, skipping this order')
i++; i++
continue; continue
} }
// Check if this is the table header row // Check if this is the table header row
// ExcelJS is 1-indexed: index 0=null, index 1=序号, index 2=材料编码 // ExcelJS is 1-indexed: index 0=null, index 1=序号, index 2=材料编码
if ( if (tableRow < allRows.length && allRows[tableRow] && allRows[tableRow][1] === '序号') {
tableRow < allRows.length &&
allRows[tableRow] &&
allRows[tableRow][1] === '序号'
) {
// Check if next row is empty (no data) // Check if next row is empty (no data)
const nextRow = tableRow + 1; const nextRow = tableRow + 1
const isEmptyRow = const isEmptyRow =
nextRow < allRows.length && nextRow < allRows.length &&
allRows[nextRow] && allRows[nextRow] &&
allRows[nextRow].every( allRows[nextRow].every((cell: any) => cell === null || String(cell).trim() === '')
(cell: any) => cell === null || String(cell).trim() === ''
);
if (isEmptyRow) { if (isEmptyRow) {
// No data, find footer info // No data, find footer info
this.log('Order has no material data'); this.log('Order has no material data')
const materials: any[] = []; const materials: any[] = []
const footerInfo: OrderHeader = {}; const footerInfo: OrderHeader = {}
let dataRow = nextRow + 1; let dataRow = nextRow + 1
while (dataRow < allRows.length && allRows[dataRow]) { while (dataRow < allRows.length && allRows[dataRow]) {
if ( if (
@@ -293,32 +281,32 @@ export class ExcelParser {
(String(allRows[dataRow][2]).includes('制单人') || (String(allRows[dataRow][2]).includes('制单人') ||
String(allRows[dataRow][2]).includes('打印人')) String(allRows[dataRow][2]).includes('打印人'))
) { ) {
this.parseHeaderRow(allRows[dataRow], footerInfo); this.parseHeaderRow(allRows[dataRow], footerInfo)
if (dataRow + 1 < allRows.length && allRows[dataRow + 1]) { if (dataRow + 1 < allRows.length && allRows[dataRow + 1]) {
this.parseHeaderRow(allRows[dataRow + 1], footerInfo); this.parseHeaderRow(allRows[dataRow + 1], footerInfo)
} }
break; break
} }
dataRow++; dataRow++
} }
orders.push({ orders.push({
orderInfo: { ...orderInfo, ...footerInfo }, orderInfo: { ...orderInfo, ...footerInfo },
materials, materials
}); })
} else { } else {
// Has data, extract materials // Has data, extract materials
this.log('Order has material data'); this.log('Order has material data')
const materials: any[] = []; const materials: any[] = []
const footerInfo: OrderHeader = {}; const footerInfo: OrderHeader = {}
let dataRow = tableRow + 1; let dataRow = tableRow + 1
while (dataRow < allRows.length && allRows[dataRow]) { while (dataRow < allRows.length && allRows[dataRow]) {
// Check if CURRENT row is footer info (制单人/打印人) // Check if CURRENT row is footer info (制单人/打印人)
const isCurrentRowFooter = const isCurrentRowFooter =
allRows[dataRow][2] && allRows[dataRow][2] &&
(String(allRows[dataRow][2]).includes('制单人') || (String(allRows[dataRow][2]).includes('制单人') ||
String(allRows[dataRow][2]).includes('打印人')); String(allRows[dataRow][2]).includes('打印人'))
// Check if NEXT row is footer info (to handle empty row before footer) // Check if NEXT row is footer info (to handle empty row before footer)
const isNextRowFooter = const isNextRowFooter =
@@ -326,65 +314,67 @@ export class ExcelParser {
allRows[dataRow + 1] && allRows[dataRow + 1] &&
allRows[dataRow + 1][2] && allRows[dataRow + 1][2] &&
(String(allRows[dataRow + 1][2]).includes('制单人') || (String(allRows[dataRow + 1][2]).includes('制单人') ||
String(allRows[dataRow + 1][2]).includes('打印人')); String(allRows[dataRow + 1][2]).includes('打印人'))
if (isCurrentRowFooter) { if (isCurrentRowFooter) {
// Current row is footer, parse it and next row if exists // Current row is footer, parse it and next row if exists
this.parseHeaderRow(allRows[dataRow], footerInfo); this.parseHeaderRow(allRows[dataRow], footerInfo)
if (dataRow + 1 < allRows.length && allRows[dataRow + 1]) { if (dataRow + 1 < allRows.length && allRows[dataRow + 1]) {
this.parseHeaderRow(allRows[dataRow + 1], footerInfo); this.parseHeaderRow(allRows[dataRow + 1], footerInfo)
} }
this.log(' Found footer row, stopping material parsing'); this.log(' Found footer row, stopping material parsing')
break; break
} }
if (isNextRowFooter) { if (isNextRowFooter) {
// Next row is footer, parse current row as material first // Next row is footer, parse current row as material first
const material = this.parseMaterialRowInternal(allRows[dataRow], dataRow + 1); const material = this.parseMaterialRowInternal(allRows[dataRow], dataRow + 1)
if (material) { if (material) {
this.log(' Parsed material:', material.materialCode); this.log(' Parsed material:', material.materialCode)
materials.push(material); materials.push(material)
} }
// Then parse footer rows // Then parse footer rows
this.parseHeaderRow(allRows[dataRow + 1], footerInfo); this.parseHeaderRow(allRows[dataRow + 1], footerInfo)
if (dataRow + 2 < allRows.length && allRows[dataRow + 2]) { if (dataRow + 2 < allRows.length && allRows[dataRow + 2]) {
this.parseHeaderRow(allRows[dataRow + 2], footerInfo); this.parseHeaderRow(allRows[dataRow + 2], footerInfo)
} }
this.log(' Found footer in next row, stopping material parsing'); this.log(' Found footer in next row, stopping material parsing')
break; break
} }
// Extract material data // Extract material data
const material = this.parseMaterialRowInternal(allRows[dataRow], dataRow + 1); const material = this.parseMaterialRowInternal(allRows[dataRow], dataRow + 1)
if (material) { if (material) {
this.log(' Parsed material:', material.materialCode); this.log(' Parsed material:', material.materialCode)
materials.push(material); materials.push(material)
} else { } else {
this.log(' Skipped material row at', dataRow + 1); this.log(' Skipped material row at', dataRow + 1)
} }
dataRow++; dataRow++
} }
orders.push({ orders.push({
orderInfo: { ...orderInfo, ...footerInfo }, orderInfo: { ...orderInfo, ...footerInfo },
materials, materials
}); })
} }
} else { } else {
this.log(` ⚠️ Table header check failed at row ${tableRow + 1}, value="${allRows[tableRow] ? allRows[tableRow][1] : 'null'}"`); this.log(
` ⚠️ Table header check failed at row ${tableRow + 1}, value="${allRows[tableRow] ? allRows[tableRow][1] : 'null'}"`
)
} }
// Move to next row after this order // Move to next row after this order
i = tableRow + 1; i = tableRow + 1
} else { } else {
i++; i++
} }
} }
this.log(`parseOrders: Returning ${orders.length} orders`); this.log(`parseOrders: Returning ${orders.length} orders`)
return orders; return orders
} }
/** /**
@@ -392,38 +382,38 @@ export class ExcelParser {
* Reference: _parse_header_row() in Python code * Reference: _parse_header_row() in Python code
*/ */
private parseHeaderRow(row: any[], info: OrderHeader): void { private parseHeaderRow(row: any[], info: OrderHeader): void {
let j = 0; let j = 0
while (j < row.length) { while (j < row.length) {
const cell = row[j]; const cell = row[j]
if (cell && String(cell).trim() && String(cell).includes('')) { if (cell && String(cell).trim() && String(cell).includes('')) {
// Found field name // Found field name
let fieldName = String(cell).replace('', '').trim(); let fieldName = String(cell).replace('', '').trim()
// Apply field name mapping (from Python code) // Apply field name mapping (from Python code)
if (fieldName in this.FIELD_NAME_MAPPING) { if (fieldName in this.FIELD_NAME_MAPPING) {
fieldName = this.FIELD_NAME_MAPPING[fieldName]; fieldName = this.FIELD_NAME_MAPPING[fieldName]
} }
// Map Chinese field name to English property name // Map Chinese field name to English property name
const englishFieldName = this.CHINESE_TO_ENGLISH_MAPPING[fieldName] || fieldName; const englishFieldName = this.CHINESE_TO_ENGLISH_MAPPING[fieldName] || fieldName
// Skip empty cells to find first non-field-name value // Skip empty cells to find first non-field-name value
let k = j + 1; let k = j + 1
while ( while (
k < row.length && k < row.length &&
(!row[k] || !String(row[k]).trim() || String(row[k]).includes('')) (!row[k] || !String(row[k]).trim() || String(row[k]).includes(''))
) { ) {
k++; k++
} }
if (k < row.length && row[k] && !String(row[k]).includes('')) { if (k < row.length && row[k] && !String(row[k]).includes('')) {
info[englishFieldName as keyof OrderHeader] = String(row[k]).trim(); info[englishFieldName as keyof OrderHeader] = String(row[k]).trim()
} }
// Skip processed value, continue to next field name // Skip processed value, continue to next field name
j = k + 1; j = k + 1
} else { } else {
j++; j++
} }
} }
} }
@@ -455,15 +445,15 @@ export class ExcelParser {
warehouse: row[11], warehouse: row[11],
unitUsage: this.parseFloat(row[12]), unitUsage: this.parseFloat(row[12]),
cumulativeOutboundQty: this.parseFloat(row[13]), cumulativeOutboundQty: this.parseFloat(row[13]),
rowNumber, rowNumber
}; }
// Skip if no material code // Skip if no material code
if (!material.materialCode) { if (!material.materialCode) {
return null; return null
} }
return material; return material
} }
/** /**
@@ -471,10 +461,10 @@ export class ExcelParser {
*/ */
private parseFloat(value: any): number | undefined { private parseFloat(value: any): number | undefined {
if (value === null || value === undefined) { if (value === null || value === undefined) {
return undefined; return undefined
} }
const parsed = parseFloat(String(value)); const parsed = parseFloat(String(value))
return isNaN(parsed) ? undefined : parsed; return isNaN(parsed) ? undefined : parsed
} }
/** /**
@@ -486,11 +476,8 @@ export class ExcelParser {
*/ */
public isOrderRow(values: any[]): boolean { public isOrderRow(values: any[]): boolean {
// ExcelJS arrays are 1-indexed, check index 2 for order title // ExcelJS arrays are 1-indexed, check index 2 for order title
const firstCell = values[2]; const firstCell = values[2]
return ( return typeof firstCell === 'string' && firstCell.includes('离散备料计划')
typeof firstCell === 'string' &&
firstCell.includes('离散备料计划')
);
} }
/** /**
@@ -505,9 +492,9 @@ export class ExcelParser {
*/ */
public extractOrderNumber(values: any[]): string { public extractOrderNumber(values: any[]): string {
// Parse the row to extract order number using same logic as header parsing // Parse the row to extract order number using same logic as header parsing
const orderInfo: OrderHeader = {}; const orderInfo: OrderHeader = {}
this.parseHeaderRow(values, orderInfo); this.parseHeaderRow(values, orderInfo)
return orderInfo.productionOrder || ''; return orderInfo.productionOrder || ''
} }
/** /**
@@ -533,22 +520,22 @@ export class ExcelParser {
// Index 3: 材料名称 // Index 3: 材料名称
// Index 4: 规格 // Index 4: 规格
// etc. // etc.
const materialCode = values[2]?.toString().trim(); const materialCode = values[2]?.toString().trim()
const materialName = values[3]?.toString().trim(); const materialName = values[3]?.toString().trim()
const specification = values[4]?.toString().trim(); const specification = values[4]?.toString().trim()
const model = values[5]?.toString().trim(); const model = values[5]?.toString().trim()
const drawingNumber = values[6]?.toString().trim(); const drawingNumber = values[6]?.toString().trim()
const material = values[7]?.toString().trim(); const material = values[7]?.toString().trim()
const quantity = this.parseFloat(values[8]) || 0; const quantity = this.parseFloat(values[8]) || 0
const unit = values[9]?.toString().trim() || ''; const unit = values[9]?.toString().trim() || ''
const requiredDate = values[10]?.toString().trim(); const requiredDate = values[10]?.toString().trim()
const warehouse = values[11]?.toString().trim(); const warehouse = values[11]?.toString().trim()
const unitUsage = this.parseFloat(values[12]); const unitUsage = this.parseFloat(values[12])
const cumulativeOutboundQty = this.parseFloat(values[13]); const cumulativeOutboundQty = this.parseFloat(values[13])
// Skip if no material code // Skip if no material code
if (!materialCode) { if (!materialCode) {
return null; return null
} }
return { return {
@@ -566,7 +553,7 @@ export class ExcelParser {
warehouse, warehouse,
unitUsage, unitUsage,
cumulativeOutboundQty, cumulativeOutboundQty,
rowNumber, rowNumber
}; }
} }
} }

View File

@@ -1,18 +1,18 @@
export interface ErpConfig { export interface ErpConfig {
url: string; url: string
username: string; username: string
password: string; password: string
headless?: boolean; // Optional: override default headless setting headless?: boolean // Optional: override default headless setting
} }
export interface ErpSession { export interface ErpSession {
browser: import('playwright').Browser; browser: import('playwright').Browser
context: import('playwright').BrowserContext; context: import('playwright').BrowserContext
page: import('playwright').Page; page: import('playwright').Page
mainFrame: import('playwright').Frame; // #forwardFrame content frame - main working frame after login mainFrame: import('playwright').Frame // #forwardFrame content frame - main working frame after login
isLoggedIn: boolean; isLoggedIn: boolean
} }
export interface ProgressCallback { export interface ProgressCallback {
(message: string, progress?: number): void; (message: string, progress?: number): void
} }

View File

@@ -9,52 +9,52 @@
*/ */
export interface DiscreteMaterialPlan { export interface DiscreteMaterialPlan {
/** Order number (e.g., SC202501001) */ /** Order number (e.g., SC202501001) */
orderNumber: string; orderNumber: string
/** Production ID from order header */ /** Production ID from order header */
productionId: string; productionId: string
/** Material code (材料编码) */ /** Material code (材料编码) */
materialCode: string; materialCode: string
/** Material name (材料名称) */ /** Material name (材料名称) */
materialName: string; materialName: string
/** Specification (规格) */ /** Specification (规格) */
specification?: string; specification?: string
/** Model (型号) */ /** Model (型号) */
model?: string; model?: string
/** Drawing number (图号) */ /** Drawing number (图号) */
drawingNumber?: string; drawingNumber?: string
/** Material (物料材质) */ /** Material (物料材质) */
material?: string; material?: string
/** Planned quantity (计划数量) */ /** Planned quantity (计划数量) */
quantity: number; quantity: number
/** Unit (单位) */ /** Unit (单位) */
unit: string; unit: string
/** Required date (需用日期) */ /** Required date (需用日期) */
requiredDate?: string; requiredDate?: string
/** Warehouse (发料仓库) */ /** Warehouse (发料仓库) */
warehouse?: string; warehouse?: string
/** Unit usage (单位用量) */ /** Unit usage (单位用量) */
unitUsage?: number; unitUsage?: number
/** Cumulative outbound quantity (累计出库数量) */ /** Cumulative outbound quantity (累计出库数量) */
cumulativeOutboundQty?: number; cumulativeOutboundQty?: number
/** Pending quantity (pending quantity for fulfillment) */ /** Pending quantity (pending quantity for fulfillment) */
pendingQty?: number; pendingQty?: number
/** Row number in Excel file */ /** Row number in Excel file */
rowNumber?: number; rowNumber?: number
} }
/** /**
@@ -62,16 +62,16 @@ export interface DiscreteMaterialPlan {
*/ */
export interface ExcelParseOptions { export interface ExcelParseOptions {
/** Skip orders with no material data */ /** Skip orders with no material data */
skipEmptyOrders?: boolean; skipEmptyOrders?: boolean
/** Skip footer rows (制单人/打印人) */ /** Skip footer rows (制单人/打印人) */
skipFooter?: boolean; skipFooter?: boolean
/** Custom field mapping */ /** Custom field mapping */
fieldMapping?: Record<string, string>; fieldMapping?: Record<string, string>
/** Verbose logging */ /** Verbose logging */
verbose?: boolean; verbose?: boolean
} }
/** /**
@@ -79,38 +79,38 @@ export interface ExcelParseOptions {
*/ */
export interface OrderHeader { export interface OrderHeader {
/** Order title (离散备料计划) */ /** Order title (离散备料计划) */
title?: string; title?: string
/** Production department (生产部门) */ /** Production department (生产部门) */
productionDepartment?: string; productionDepartment?: string
/** Production order (生产订单) */ /** Production order (生产订单) */
productionOrder?: string; productionOrder?: string
/** Product code (产品编码) */ /** Product code (产品编码) */
productCode?: string; productCode?: string
/** Product name (产品名称) */ /** Product name (产品名称) */
productName?: string; productName?: string
/** Product specification (产品规格) */ /** Product specification (产品规格) */
productSpecification?: string; productSpecification?: string
/** Planned quantity (计划数量) */ /** Planned quantity (计划数量) */
plannedQuantity?: string; plannedQuantity?: string
/** Unit (单位) */ /** Unit (单位) */
unit?: string; unit?: string
/** Required date (需用日期) */ /** Required date (需用日期) */
requiredDate?: string; requiredDate?: string
/** Creator (制单人) */ /** Creator (制单人) */
creator?: string; creator?: string
/** Printer (打印人) */ /** Printer (打印人) */
printer?: string; printer?: string
/** Print date (打印日期) */ /** Print date (打印日期) */
printDate?: string; printDate?: string
} }

View File

@@ -1,17 +1,17 @@
export interface ExtractorInput { export interface ExtractorInput {
orderNumbers: string[]; orderNumbers: string[]
batchSize?: number; batchSize?: number
onProgress?: (message: string, progress: number) => void; onProgress?: (message: string, progress: number) => void
} }
export interface ExtractorResult { export interface ExtractorResult {
downloadedFiles: string[]; downloadedFiles: string[]
mergedFile: string | null; mergedFile: string | null
recordCount: number; recordCount: number
errors: string[]; errors: string[]
} }
export interface OrderInfo { export interface OrderInfo {
orderNumber: string; orderNumber: string
productionId: string; productionId: string
} }

View File

@@ -1,25 +1,25 @@
import ExcelJS from 'exceljs'; import ExcelJS from 'exceljs'
import path from 'path'; import path from 'path'
/** /**
* Create test fixture Excel files for unit tests * Create test fixture Excel files for unit tests
*/ */
async function createTestFixture() { async function createTestFixture() {
const workbook = new ExcelJS.Workbook(); const workbook = new ExcelJS.Workbook()
const worksheet = workbook.addWorksheet('Sheet1'); const worksheet = workbook.addWorksheet('Sheet1')
// Row 1: Order title // Row 1: Order title
worksheet.addRow([null, '离散备料计划']); worksheet.addRow([null, '离散备料计划'])
// Row 2-5: Order header info // Row 2-5: Order header info
worksheet.addRow([null, '生产部门:', null, '生产车间', '产品编码:', null, 'P001']); worksheet.addRow([null, '生产部门:', null, '生产车间', '产品编码:', null, 'P001'])
worksheet.addRow([null, '生产订单:', null, 'SC202501001', '产品名称:', null, '测试产品A']); worksheet.addRow([null, '生产订单:', null, 'SC202501001', '产品名称:', null, '测试产品A'])
worksheet.addRow([null, '产品规格:', null, '标准规格', '计划数量:', null, '100']); worksheet.addRow([null, '产品规格:', null, '标准规格', '计划数量:', null, '100'])
worksheet.addRow([null, '单位:', null, '件', '需用日期:', null, '2025-02-15']); worksheet.addRow([null, '单位:', null, '件', '需用日期:', null, '2025-02-15'])
// Row 6: Empty row before table header // Row 6: Empty row before table header
worksheet.addRow([]); worksheet.addRow([])
// Row 7: Table header // Row 7: Table header
worksheet.addRow([ worksheet.addRow([
@@ -36,8 +36,8 @@ async function createTestFixture() {
'需用日期', '需用日期',
'发料仓库', '发料仓库',
'单位用量', '单位用量',
'累计出库数量', '累计出库数量'
]); ])
// Row 8-10: Material data // Row 8-10: Material data
worksheet.addRow([ worksheet.addRow([
@@ -54,8 +54,8 @@ async function createTestFixture() {
'2025-02-10', '2025-02-10',
'仓库1', '仓库1',
0.5, 0.5,
0, 0
]); ])
worksheet.addRow([ worksheet.addRow([
null, null,
2, 2,
@@ -70,8 +70,8 @@ async function createTestFixture() {
'2025-02-12', '2025-02-12',
'仓库1', '仓库1',
1.0, 1.0,
20, 20
]); ])
worksheet.addRow([ worksheet.addRow([
null, null,
3, 3,
@@ -86,34 +86,34 @@ async function createTestFixture() {
'2025-02-14', '2025-02-14',
'仓库2', '仓库2',
2.0, 2.0,
50, 50
]); ])
// Row 11: Footer info // Row 11: Footer info
worksheet.addRow([null, '制单人:', null, '张三', '打印人:', null, '李四']); worksheet.addRow([null, '制单人:', null, '张三', '打印人:', null, '李四'])
worksheet.addRow([null, '打印日期:', null, '2025-01-15']); worksheet.addRow([null, '打印日期:', null, '2025-01-15'])
// Save file // Save file
const filePath = path.resolve(__dirname, 'test-export.xlsx'); const filePath = path.resolve(__dirname, 'test-export.xlsx')
await workbook.xlsx.writeFile(filePath); await workbook.xlsx.writeFile(filePath)
console.log('Created test fixture:', filePath); console.log('Created test fixture:', filePath)
} }
async function createEmptyOrdersFixture() { async function createEmptyOrdersFixture() {
const workbook = new ExcelJS.Workbook(); const workbook = new ExcelJS.Workbook()
const worksheet = workbook.addWorksheet('Sheet1'); const worksheet = workbook.addWorksheet('Sheet1')
// Row 1: Order title // Row 1: Order title
worksheet.addRow([null, '离散备料计划']); worksheet.addRow([null, '离散备料计划'])
// Row 2-5: Order header info // Row 2-5: Order header info
worksheet.addRow([null, '生产部门:', null, '生产车间', '产品编码:', null, 'P002']); worksheet.addRow([null, '生产部门:', null, '生产车间', '产品编码:', null, 'P002'])
worksheet.addRow([null, '生产订单:', null, 'SC202501002', '产品名称:', null, '测试产品B']); worksheet.addRow([null, '生产订单:', null, 'SC202501002', '产品名称:', null, '测试产品B'])
worksheet.addRow([null, '产品规格:', null, '特殊规格', '计划数量:', null, '50']); worksheet.addRow([null, '产品规格:', null, '特殊规格', '计划数量:', null, '50'])
worksheet.addRow([null, '单位:', null, '套', '需用日期:', null, '2025-03-01']); worksheet.addRow([null, '单位:', null, '套', '需用日期:', null, '2025-03-01'])
// Row 6: Empty row before table header // Row 6: Empty row before table header
worksheet.addRow([]); worksheet.addRow([])
// Row 7: Table header // Row 7: Table header
worksheet.addRow([ worksheet.addRow([
@@ -130,27 +130,27 @@ async function createEmptyOrdersFixture() {
'需用日期', '需用日期',
'发料仓库', '发料仓库',
'单位用量', '单位用量',
'累计出库数量', '累计出库数量'
]); ])
// Row 8: Empty row (no data) // Row 8: Empty row (no data)
worksheet.addRow([]); worksheet.addRow([])
// Row 9: Footer info // Row 9: Footer info
worksheet.addRow([null, '制单人:', null, '王五', '打印人:', null, '赵六']); worksheet.addRow([null, '制单人:', null, '王五', '打印人:', null, '赵六'])
worksheet.addRow([null, '打印日期:', null, '2025-01-16']); worksheet.addRow([null, '打印日期:', null, '2025-01-16'])
// Save file // Save file
const filePath = path.resolve(__dirname, 'test-empty-orders.xlsx'); const filePath = path.resolve(__dirname, 'test-empty-orders.xlsx')
await workbook.xlsx.writeFile(filePath); await workbook.xlsx.writeFile(filePath)
console.log('Created empty orders fixture:', filePath); console.log('Created empty orders fixture:', filePath)
} }
async function main() { async function main() {
console.log('Creating test fixture Excel files...'); console.log('Creating test fixture Excel files...')
await createTestFixture(); await createTestFixture()
await createEmptyOrdersFixture(); await createEmptyOrdersFixture()
console.log('Done!'); console.log('Done!')
} }
main().catch(console.error); main().catch(console.error)

View File

@@ -1,56 +1,56 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { ErpAuthService } from '../../src/main/services/erp/erp-auth'; import { ErpAuthService } from '../../src/main/services/erp/erp-auth'
import type { ErpConfig } from '../../src/main/types/erp.types'; import type { ErpConfig } from '../../src/main/types/erp.types'
describe('ERP Authentication Service (Integration)', () => { describe('ERP Authentication Service (Integration)', () => {
let authService: ErpAuthService; let authService: ErpAuthService
const config: ErpConfig = { const config: ErpConfig = {
url: process.env.ERP_URL || '', url: process.env.ERP_URL || '',
username: process.env.ERP_USERNAME || '', username: process.env.ERP_USERNAME || '',
password: process.env.ERP_PASSWORD || '', password: process.env.ERP_PASSWORD || ''
}; }
// Check if we have ERP credentials // Check if we have ERP credentials
const hasCredentials = !!(config.url && config.username && config.password); const hasCredentials = !!(config.url && config.username && config.password)
beforeAll(() => { beforeAll(() => {
if (!hasCredentials) { if (!hasCredentials) {
console.warn('Skipping ERP auth tests: credentials not configured'); console.warn('Skipping ERP auth tests: credentials not configured')
return; return
} }
authService = new ErpAuthService(config); authService = new ErpAuthService(config)
}); })
it('should login successfully', async () => { it('should login successfully', async () => {
if (!hasCredentials) { if (!hasCredentials) {
console.warn('Skipping test: ERP credentials not configured'); console.warn('Skipping test: ERP credentials not configured')
return; return
} }
const session = await authService.login(); const session = await authService.login()
expect(session).toBeDefined(); expect(session).toBeDefined()
expect(session.browser).toBeDefined(); expect(session.browser).toBeDefined()
expect(session.context).toBeDefined(); expect(session.context).toBeDefined()
expect(session.page).toBeDefined(); expect(session.page).toBeDefined()
expect(session.isLoggedIn).toBe(true); expect(session.isLoggedIn).toBe(true)
}, 30000); }, 30000)
it('should navigate to main page after login', async () => { it('should navigate to main page after login', async () => {
if (!hasCredentials) { if (!hasCredentials) {
console.warn('Skipping test: ERP credentials not configured'); console.warn('Skipping test: ERP credentials not configured')
return; return
} }
const session = await authService.login(); const session = await authService.login()
const url = session.page.url(); const url = session.page.url()
expect(url).toContain(config.url); expect(url).toContain(config.url)
}, 30000); }, 30000)
afterAll(async () => { afterAll(async () => {
if (hasCredentials && authService) { if (hasCredentials && authService) {
await authService.close(); await authService.close()
} }
}); })
}); })

View File

@@ -1,150 +1,152 @@
import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import { ExtractorService } from '../../src/main/services/erp/extractor'; import { ExtractorService } from '../../src/main/services/erp/extractor'
import { ErpAuthService } from '../../src/main/services/erp/erp-auth'; import { ErpAuthService } from '../../src/main/services/erp/erp-auth'
import type { ErpConfig } from '../../src/main/types/erp.types'; import type { ErpConfig } from '../../src/main/types/erp.types'
import fs from 'fs/promises'; import fs from 'fs/promises'
import path from 'path'; import path from 'path'
describe('Extractor Service (Integration)', () => { describe('Extractor Service (Integration)', () => {
const config: ErpConfig = { const config: ErpConfig = {
url: process.env.ERP_URL || '', url: process.env.ERP_URL || '',
username: process.env.ERP_USERNAME || '', username: process.env.ERP_USERNAME || '',
password: process.env.ERP_PASSWORD || '', password: process.env.ERP_PASSWORD || ''
}; }
const testOrderNumber = 'SC70202602120085'; // From references/demo/productionID.txt const testOrderNumber = 'SC70202602120085' // From references/demo/productionID.txt
// Check if we have ERP credentials // Check if we have ERP credentials
const hasCredentials = !!(config.url && config.username && config.password); const hasCredentials = !!(config.url && config.username && config.password)
it('should extract data for single order number', async () => { it('should extract data for single order number', async () => {
if (!hasCredentials) { if (!hasCredentials) {
console.warn('Skipping test: ERP credentials not configured'); console.warn('Skipping test: ERP credentials not configured')
return; return
} }
// Create fresh auth service for this test // Create fresh auth service for this test
const authService = new ErpAuthService(config); const authService = new ErpAuthService(config)
await authService.login(); await authService.login()
const extractor = new ExtractorService(authService); const extractor = new ExtractorService(authService)
const result = await extractor.extract({ const result = await extractor.extract({
orderNumbers: [testOrderNumber], orderNumbers: [testOrderNumber]
}); })
expect(result.downloadedFiles).toHaveLength(1); expect(result.downloadedFiles).toHaveLength(1)
expect(result.errors).toHaveLength(0); expect(result.errors).toHaveLength(0)
// Verify file exists // Verify file exists
const filePath = result.downloadedFiles[0]; const filePath = result.downloadedFiles[0]
const stats = await fs.stat(filePath); const stats = await fs.stat(filePath)
expect(stats.size).toBeGreaterThan(0); expect(stats.size).toBeGreaterThan(0)
// Clean up // Clean up
await authService.close(); await authService.close()
}, 60000); }, 60000)
it('should extract data for multiple order numbers', async () => { it('should extract data for multiple order numbers', async () => {
if (!hasCredentials) { if (!hasCredentials) {
console.warn('Skipping test: ERP credentials not configured'); console.warn('Skipping test: ERP credentials not configured')
return; return
} }
// Create fresh auth service for this test // Create fresh auth service for this test
const authService = new ErpAuthService(config); const authService = new ErpAuthService(config)
await authService.login(); await authService.login()
const extractor = new ExtractorService(authService); const extractor = new ExtractorService(authService)
// Read order numbers from productionID.txt file // Read order numbers from productionID.txt file
const fs = await import('fs/promises'); const fs = await import('fs/promises')
const path = await import('path'); const path = await import('path')
// productionID.txt is at: D:\FileLib\Projects\CodeMigration\references\demo\productionID.txt // productionID.txt is at: D:\FileLib\Projects\CodeMigration\references\demo\productionID.txt
// test runs at: D:\FileLib\Projects\CodeMigration\ERPAuto // test runs at: D:\FileLib\Projects\CodeMigration\ERPAuto
const productionIdFile = path.join(process.cwd(), '../references/demo/productionID.txt'); const productionIdFile = path.join(process.cwd(), '../references/demo/productionID.txt')
const content = await fs.readFile(productionIdFile, 'utf-8'); const content = await fs.readFile(productionIdFile, 'utf-8')
const orderNumbers = content.split('\n') const orderNumbers = content
.map(line => line.trim()) .split('\n')
.filter(line => line.length > 0) .map((line) => line.trim())
.slice(0, 5); // Test first 5 orders .filter((line) => line.length > 0)
.slice(0, 5) // Test first 5 orders
console.log(`Testing with ${orderNumbers.length} order numbers:`, orderNumbers); console.log(`Testing with ${orderNumbers.length} order numbers:`, orderNumbers)
const result = await extractor.extract({ const result = await extractor.extract({
orderNumbers, orderNumbers,
batchSize: 100, // Process all in one batch batchSize: 100 // Process all in one batch
}); })
console.log(`Downloaded ${result.downloadedFiles.length} files`); console.log(`Downloaded ${result.downloadedFiles.length} files`)
if (result.errors.length > 0) { if (result.errors.length > 0) {
console.log('Errors:', result.errors); console.log('Errors:', result.errors)
} }
expect(result.downloadedFiles.length).toBeGreaterThanOrEqual(1); expect(result.downloadedFiles.length).toBeGreaterThanOrEqual(1)
// Clean up // Clean up
await authService.close(); await authService.close()
}, 120000); // Increase timeout to 2 minutes }, 120000) // Increase timeout to 2 minutes
it('should extract data for 300 orders with batch size 70', async () => { it('should extract data for 300 orders with batch size 70', async () => {
if (!hasCredentials) { if (!hasCredentials) {
console.warn('Skipping test: ERP credentials not configured'); console.warn('Skipping test: ERP credentials not configured')
return; return
} }
// Create fresh auth service for this test // Create fresh auth service for this test
const authService = new ErpAuthService(config); const authService = new ErpAuthService(config)
await authService.login(); await authService.login()
const extractor = new ExtractorService(authService); const extractor = new ExtractorService(authService)
// Read all order numbers from productionID.txt file // Read all order numbers from productionID.txt file
const fs = await import('fs/promises'); const fs = await import('fs/promises')
const path = await import('path'); const path = await import('path')
const productionIdFile = path.join(process.cwd(), '../references/demo/productionID.txt'); const productionIdFile = path.join(process.cwd(), '../references/demo/productionID.txt')
const content = await fs.readFile(productionIdFile, 'utf-8'); const content = await fs.readFile(productionIdFile, 'utf-8')
const orderNumbers = content.split('\n') const orderNumbers = content
.map(line => line.trim()) .split('\n')
.filter(line => line.length > 0); .map((line) => line.trim())
.filter((line) => line.length > 0)
console.log(`Testing with ${orderNumbers.length} order numbers`); console.log(`Testing with ${orderNumbers.length} order numbers`)
console.log(`Batch size: 70, Expected batches: ${Math.ceil(orderNumbers.length / 70)}`); console.log(`Batch size: 70, Expected batches: ${Math.ceil(orderNumbers.length / 70)}`)
const startTime = Date.now(); const startTime = Date.now()
const result = await extractor.extract({ const result = await extractor.extract({
orderNumbers, orderNumbers,
batchSize: 70, // Process 70 orders per batch batchSize: 70 // Process 70 orders per batch
}); })
const endTime = Date.now(); const endTime = Date.now()
const duration = ((endTime - startTime) / 1000).toFixed(2); const duration = ((endTime - startTime) / 1000).toFixed(2)
console.log(`\n=== Extraction Summary ===`); console.log(`\n=== Extraction Summary ===`)
console.log(`Total orders: ${orderNumbers.length}`); console.log(`Total orders: ${orderNumbers.length}`)
console.log(`Batch size: 70`); console.log(`Batch size: 70`)
console.log(`Expected batches: ${Math.ceil(orderNumbers.length / 70)}`); console.log(`Expected batches: ${Math.ceil(orderNumbers.length / 70)}`)
console.log(`Downloaded files: ${result.downloadedFiles.length}`); console.log(`Downloaded files: ${result.downloadedFiles.length}`)
console.log(`Total duration: ${duration}s`); console.log(`Total duration: ${duration}s`)
console.log(`Average time per batch: ${(duration / result.downloadedFiles.length).toFixed(2)}s`); console.log(`Average time per batch: ${(duration / result.downloadedFiles.length).toFixed(2)}s`)
if (result.errors.length > 0) { if (result.errors.length > 0) {
console.log(`\nErrors encountered: ${result.errors.length}`); console.log(`\nErrors encountered: ${result.errors.length}`)
result.errors.forEach((err, idx) => console.log(` ${idx + 1}. ${err}`)); result.errors.forEach((err, idx) => console.log(` ${idx + 1}. ${err}`))
} }
// Verify results // Verify results
expect(result.downloadedFiles.length).toBeGreaterThanOrEqual(1); expect(result.downloadedFiles.length).toBeGreaterThanOrEqual(1)
// Verify each downloaded file exists and has content // Verify each downloaded file exists and has content
for (const filePath of result.downloadedFiles) { for (const filePath of result.downloadedFiles) {
const stats = await fs.stat(filePath); const stats = await fs.stat(filePath)
console.log(` - ${path.basename(filePath)}: ${(stats.size / 1024).toFixed(2)} KB`); console.log(` - ${path.basename(filePath)}: ${(stats.size / 1024).toFixed(2)} KB`)
expect(stats.size).toBeGreaterThan(0); expect(stats.size).toBeGreaterThan(0)
} }
// Clean up // Clean up
await authService.close(); await authService.close()
}, 600000); // 10 minutes timeout for large batch test }, 600000) // 10 minutes timeout for large batch test
}); })

View File

@@ -1,16 +1,16 @@
import { beforeAll, afterAll } from 'vitest'; import { beforeAll, afterAll } from 'vitest'
import dotenv from 'dotenv'; import dotenv from 'dotenv'
import path from 'path'; import path from 'path'
// Load environment variables from project root // Load environment variables from project root
dotenv.config({ path: path.resolve(process.cwd(), '.env') }); dotenv.config({ path: path.resolve(process.cwd(), '.env') })
beforeAll(async () => { beforeAll(async () => {
// Global test setup // Global test setup
console.log('Test suite starting...'); console.log('Test suite starting...')
}); })
afterAll(async () => { afterAll(async () => {
// Global test teardown // Global test teardown
console.log('Test suite completed.'); console.log('Test suite completed.')
}); })

View File

@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach } from 'vitest'; import { describe, it, expect, beforeEach } from 'vitest'
import { ErpAuthService } from '../../src/main/services/erp/erp-auth'; import { ErpAuthService } from '../../src/main/services/erp/erp-auth'
import type { ErpConfig } from '../../src/main/types/erp.types'; import type { ErpConfig } from '../../src/main/types/erp.types'
describe('ERP Authentication Service (Unit)', () => { describe('ERP Authentication Service (Unit)', () => {
describe('Session Management', () => { describe('Session Management', () => {
@@ -8,52 +8,52 @@ describe('ERP Authentication Service (Unit)', () => {
const config: ErpConfig = { const config: ErpConfig = {
url: 'https://test.example.com', url: 'https://test.example.com',
username: 'testuser', username: 'testuser',
password: 'testpass', password: 'testpass'
}; }
const service = new ErpAuthService(config); const service = new ErpAuthService(config)
expect(service).toBeDefined(); expect(service).toBeDefined()
expect(service.isActive()).toBe(false); expect(service.isActive()).toBe(false)
}); })
it('should throw error when getting session before login', () => { it('should throw error when getting session before login', () => {
const config: ErpConfig = { const config: ErpConfig = {
url: 'https://test.example.com', url: 'https://test.example.com',
username: 'testuser', username: 'testuser',
password: 'testpass', password: 'testpass'
}; }
const service = new ErpAuthService(config); const service = new ErpAuthService(config)
expect(() => service.getSession()).toThrow('Not logged in. Call login() first.'); expect(() => service.getSession()).toThrow('Not logged in. Call login() first.')
}); })
it('should report inactive status before login', () => { it('should report inactive status before login', () => {
const config: ErpConfig = { const config: ErpConfig = {
url: 'https://test.example.com', url: 'https://test.example.com',
username: 'testuser', username: 'testuser',
password: 'testpass', password: 'testpass'
}; }
const service = new ErpAuthService(config); const service = new ErpAuthService(config)
expect(service.isActive()).toBe(false); expect(service.isActive()).toBe(false)
}); })
}); })
describe('Close Method', () => { describe('Close Method', () => {
it('should handle close when no session exists', async () => { it('should handle close when no session exists', async () => {
const config: ErpConfig = { const config: ErpConfig = {
url: 'https://test.example.com', url: 'https://test.example.com',
username: 'testuser', username: 'testuser',
password: 'testpass', password: 'testpass'
}; }
const service = new ErpAuthService(config); const service = new ErpAuthService(config)
// Should not throw when closing without session // Should not throw when closing without session
await expect(service.close()).resolves.toBeUndefined(); await expect(service.close()).resolves.toBeUndefined()
}); })
}); })
}); })

View File

@@ -1,59 +1,59 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest'
import { ExcelParser } from '../../src/main/services/excel/excel-parser'; import { ExcelParser } from '../../src/main/services/excel/excel-parser'
import type { DiscreteMaterialPlan } from '../../src/main/types/excel.types'; import type { DiscreteMaterialPlan } from '../../src/main/types/excel.types'
import path from 'path'; import path from 'path'
describe('Excel Parser', () => { describe('Excel Parser', () => {
it('should parse Excel file and extract material plans', async () => { it('should parse Excel file and extract material plans', async () => {
const parser = new ExcelParser(); const parser = new ExcelParser()
const filePath = path.resolve(__dirname, '../fixtures/test-export.xlsx'); const filePath = path.resolve(__dirname, '../fixtures/test-export.xlsx')
const plans = await parser.parse(filePath); const plans = await parser.parse(filePath)
expect(Array.isArray(plans)).toBe(true); expect(Array.isArray(plans)).toBe(true)
expect(plans.length).toBeGreaterThan(0); expect(plans.length).toBeGreaterThan(0)
const firstPlan = plans[0]; const firstPlan = plans[0]
expect(firstPlan).toHaveProperty('orderNumber'); expect(firstPlan).toHaveProperty('orderNumber')
expect(firstPlan).toHaveProperty('materialCode'); expect(firstPlan).toHaveProperty('materialCode')
}); })
it('should parse all material fields correctly', async () => { it('should parse all material fields correctly', async () => {
const parser = new ExcelParser(); const parser = new ExcelParser()
const filePath = path.resolve(__dirname, '../fixtures/test-export.xlsx'); const filePath = path.resolve(__dirname, '../fixtures/test-export.xlsx')
const plans = await parser.parse(filePath); const plans = await parser.parse(filePath)
expect(plans.length).toBe(3); expect(plans.length).toBe(3)
// Check first material // Check first material
expect(plans[0].orderNumber).toBe('SC202501001'); expect(plans[0].orderNumber).toBe('SC202501001')
expect(plans[0].materialCode).toBe('M001'); expect(plans[0].materialCode).toBe('M001')
expect(plans[0].materialName).toBe('钢材A'); expect(plans[0].materialName).toBe('钢材A')
expect(plans[0].specification).toBe('规格1'); expect(plans[0].specification).toBe('规格1')
expect(plans[0].model).toBe('型号1'); expect(plans[0].model).toBe('型号1')
expect(plans[0].drawingNumber).toBe('图号1'); expect(plans[0].drawingNumber).toBe('图号1')
expect(plans[0].material).toBe('材质1'); expect(plans[0].material).toBe('材质1')
expect(plans[0].quantity).toBe(50); expect(plans[0].quantity).toBe(50)
expect(plans[0].unit).toBe('kg'); expect(plans[0].unit).toBe('kg')
expect(plans[0].requiredDate).toBe('2025-02-10'); expect(plans[0].requiredDate).toBe('2025-02-10')
expect(plans[0].warehouse).toBe('仓库1'); expect(plans[0].warehouse).toBe('仓库1')
expect(plans[0].unitUsage).toBe(0.5); expect(plans[0].unitUsage).toBe(0.5)
expect(plans[0].cumulativeOutboundQty).toBe(0); expect(plans[0].cumulativeOutboundQty).toBe(0)
// Check third material (with some empty fields) // Check third material (with some empty fields)
expect(plans[2].materialCode).toBe('M003'); expect(plans[2].materialCode).toBe('M003')
expect(plans[2].materialName).toBe('配件C'); expect(plans[2].materialName).toBe('配件C')
expect(plans[2].quantity).toBe(200); expect(plans[2].quantity).toBe(200)
}); })
it('should handle empty orders gracefully', async () => { it('should handle empty orders gracefully', async () => {
const parser = new ExcelParser(); const parser = new ExcelParser()
const filePath = path.resolve(__dirname, '../fixtures/test-empty-orders.xlsx'); const filePath = path.resolve(__dirname, '../fixtures/test-empty-orders.xlsx')
const plans = await parser.parse(filePath); const plans = await parser.parse(filePath)
expect(plans).toBeDefined(); expect(plans).toBeDefined()
expect(plans.length).toBe(0); expect(plans.length).toBe(0)
}); })
}); })

View File

@@ -1,87 +1,87 @@
import { describe, it, expect, beforeEach } from 'vitest'; import { describe, it, expect, beforeEach } from 'vitest'
import { ExtractorService } from '../../src/main/services/erp/extractor'; import { ExtractorService } from '../../src/main/services/erp/extractor'
import { ErpAuthService } from '../../src/main/services/erp/erp-auth'; import { ErpAuthService } from '../../src/main/services/erp/erp-auth'
import type { ErpConfig } from '../../src/main/types/erp.types'; import type { ErpConfig } from '../../src/main/types/erp.types'
describe('Extractor Service (Unit)', () => { describe('Extractor Service (Unit)', () => {
let authService: ErpAuthService; let authService: ErpAuthService
let extractor: ExtractorService; let extractor: ExtractorService
const mockConfig: ErpConfig = { const mockConfig: ErpConfig = {
url: 'https://test.erp.com', url: 'https://test.erp.com',
username: 'test_user', username: 'test_user',
password: 'test_pass', password: 'test_pass'
}; }
beforeEach(() => { beforeEach(() => {
authService = new ErpAuthService(mockConfig); authService = new ErpAuthService(mockConfig)
extractor = new ExtractorService(authService, './test-downloads'); extractor = new ExtractorService(authService, './test-downloads')
}); })
describe('Batch Creation', () => { describe('Batch Creation', () => {
it('should create single batch for small order list', () => { it('should create single batch for small order list', () => {
// This tests the createBatches method indirectly through extract // This tests the createBatches method indirectly through extract
// We'll need to add a public method or test through the class // We'll need to add a public method or test through the class
const orders = ['ORDER1', 'ORDER2', 'ORDER3']; const orders = ['ORDER1', 'ORDER2', 'ORDER3']
const batchSize = 10; const batchSize = 10
// Expected: 1 batch with 3 orders // Expected: 1 batch with 3 orders
const expectedBatches = 1; const expectedBatches = 1
expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches); expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches)
}); })
it('should create multiple batches for large order list', () => { it('should create multiple batches for large order list', () => {
const orders = Array.from({ length: 250 }, (_, i) => `ORDER${i}`); const orders = Array.from({ length: 250 }, (_, i) => `ORDER${i}`)
const batchSize = 100; const batchSize = 100
// Expected: 3 batches (100, 100, 50) // Expected: 3 batches (100, 100, 50)
const expectedBatches = 3; const expectedBatches = 3
expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches); expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches)
}); })
it('should handle exact batch size', () => { it('should handle exact batch size', () => {
const orders = Array.from({ length: 200 }, (_, i) => `ORDER${i}`); const orders = Array.from({ length: 200 }, (_, i) => `ORDER${i}`)
const batchSize = 100; const batchSize = 100
// Expected: 2 batches exactly // Expected: 2 batches exactly
const expectedBatches = 2; const expectedBatches = 2
expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches); expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches)
}); })
it('should handle empty order list', () => { it('should handle empty order list', () => {
const orders: string[] = []; const orders: string[] = []
const batchSize = 100; const batchSize = 100
// Expected: 0 batches // Expected: 0 batches
const expectedBatches = 0; const expectedBatches = 0
expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches); expect(Math.ceil(orders.length / batchSize)).toBe(expectedBatches)
}); })
}); })
describe('Service Initialization', () => { describe('Service Initialization', () => {
it('should create service instance', () => { it('should create service instance', () => {
expect(extractor).toBeDefined(); expect(extractor).toBeDefined()
expect(extractor).toBeInstanceOf(ExtractorService); expect(extractor).toBeInstanceOf(ExtractorService)
}); })
it('should use default download directory', () => { it('should use default download directory', () => {
const defaultExtractor = new ExtractorService(authService); const defaultExtractor = new ExtractorService(authService)
expect(defaultExtractor).toBeDefined(); expect(defaultExtractor).toBeDefined()
}); })
it('should use custom download directory', () => { it('should use custom download directory', () => {
const customExtractor = new ExtractorService(authService, './custom-downloads'); const customExtractor = new ExtractorService(authService, './custom-downloads')
expect(customExtractor).toBeDefined(); expect(customExtractor).toBeDefined()
}); })
}); })
describe('Error Handling', () => { describe('Error Handling', () => {
it('should handle extraction with no auth session', async () => { it('should handle extraction with no auth session', async () => {
const result = await extractor.extract({ const result = await extractor.extract({
orderNumbers: ['ORDER1'], orderNumbers: ['ORDER1']
}); })
expect(result.errors.length).toBeGreaterThan(0); expect(result.errors.length).toBeGreaterThan(0)
expect(result.downloadedFiles).toHaveLength(0); expect(result.downloadedFiles).toHaveLength(0)
}); })
}); })
}); })

View File

@@ -1,27 +1,27 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest'
import { ERP_LOCATORS } from '../../src/main/services/erp/locators'; import { ERP_LOCATORS } from '../../src/main/services/erp/locators'
describe('ERP Locators', () => { describe('ERP Locators', () => {
it('should have login page locators defined', () => { it('should have login page locators defined', () => {
expect(ERP_LOCATORS.login.usernameInput).toBeDefined(); expect(ERP_LOCATORS.login.usernameInput).toBeDefined()
expect(ERP_LOCATORS.login.passwordInput).toBeDefined(); expect(ERP_LOCATORS.login.passwordInput).toBeDefined()
expect(ERP_LOCATORS.login.submitButton).toBeDefined(); expect(ERP_LOCATORS.login.submitButton).toBeDefined()
}); })
it('should have main frame locator', () => { it('should have main frame locator', () => {
expect(ERP_LOCATORS.main.mainIframe).toBeDefined(); expect(ERP_LOCATORS.main.mainIframe).toBeDefined()
}); })
it('should have extractor page locators', () => { it('should have extractor page locators', () => {
expect(ERP_LOCATORS.extractor.orderNumberInputRole).toBeDefined(); expect(ERP_LOCATORS.extractor.orderNumberInputRole).toBeDefined()
expect(ERP_LOCATORS.extractor.queryButton).toBeDefined(); expect(ERP_LOCATORS.extractor.queryButton).toBeDefined()
expect(ERP_LOCATORS.extractor.exportButton).toBeDefined(); expect(ERP_LOCATORS.extractor.exportButton).toBeDefined()
expect(ERP_LOCATORS.extractor.confirmButton).toBeDefined(); expect(ERP_LOCATORS.extractor.confirmButton).toBeDefined()
}); })
it('should have cleaner page locators', () => { it('should have cleaner page locators', () => {
expect(ERP_LOCATORS.cleaner.orderNumberInput).toBeDefined(); expect(ERP_LOCATORS.cleaner.orderNumberInput).toBeDefined()
expect(ERP_LOCATORS.cleaner.materialGrid).toBeDefined(); expect(ERP_LOCATORS.cleaner.materialGrid).toBeDefined()
expect(ERP_LOCATORS.cleaner.saveButton).toBeDefined(); expect(ERP_LOCATORS.cleaner.saveButton).toBeDefined()
}); })
}); })

File diff suppressed because one or more lines are too long

View File

@@ -1,4 +1,4 @@
import { defineConfig } from 'vitest/config'; import { defineConfig } from 'vitest/config'
export default defineConfig({ export default defineConfig({
test: { test: {
@@ -9,7 +9,7 @@ export default defineConfig({
setupFiles: ['tests/setup.ts'], setupFiles: ['tests/setup.ts'],
coverage: { coverage: {
provider: 'v8', provider: 'v8',
reporter: ['text', 'json', 'html'], reporter: ['text', 'json', 'html']
}, }
}, }
}); })