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 { ERP_LOCATORS } from './locators';
import type { ErpConfig, ErpSession } from '../../types/erp.types';
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'
import { ERP_LOCATORS } from './locators'
import type { ErpConfig, ErpSession } from '../../types/erp.types'
/**
* ERP Authentication Service
* Manages login session and browser lifecycle
*/
export class ErpAuthService {
private config: ErpConfig;
private session: ErpSession | null = null;
private ignoreHTTPSErrors: boolean;
private config: ErpConfig
private session: ErpSession | null = null
private ignoreHTTPSErrors: boolean
constructor(config: ErpConfig) {
this.config = config;
this.ignoreHTTPSErrors = process.env.ERP_IGNORE_HTTPS_ERRORS === 'true';
this.config = config
this.ignoreHTTPSErrors = process.env.ERP_IGNORE_HTTPS_ERRORS === 'true'
}
/**
@@ -21,7 +21,7 @@ export class ErpAuthService {
*/
async login(): Promise<ErpSession> {
if (this.session?.isLoggedIn) {
return this.session;
return this.session
}
// Launch browser with SSL certificate errors ignored
@@ -33,9 +33,9 @@ export class ErpAuthService {
'--ignore-certificate-errors',
'--ignore-ssl-errors',
'--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({
acceptDownloads: true,
@@ -43,76 +43,76 @@ export class ErpAuthService {
ignoreHTTPSErrors: true, // Ignore SSL certificate errors
acceptAllDownloads: true, // Accept all downloads
// 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)
const loginUrl = `${this.config.url}/yonbip/resources/uap/rbac/login/main/index.html`;
await page.goto(loginUrl);
const loginUrl = `${this.config.url}/yonbip/resources/uap/rbac/login/main/index.html`
await page.goto(loginUrl)
// Wait for page to load
await page.waitForLoadState('domcontentloaded', { timeout: 10000 });
await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
// 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)
// This is the main working frame for all subsequent operations
const frameLocator = page.locator('#forwardFrame');
const contentFrame = await frameLocator.contentFrame();
const frameLocator = page.locator('#forwardFrame')
const contentFrame = await frameLocator.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)
const mainFrame = contentFrame;
const mainFrame = contentFrame
// Fill username using role-based locator (Python: get_by_role("textbox", name="用户名"))
try {
await contentFrame.getByRole('textbox', { name: '用户名' }).fill(this.config.username);
await contentFrame.getByRole('textbox', { name: '用户名' }).fill(this.config.username)
} 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="密码"))
try {
await contentFrame.getByRole('textbox', { name: '密码' }).fill(this.config.password);
await contentFrame.getByRole('textbox', { name: '密码' }).fill(this.config.password)
} 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="登录"))
try {
await contentFrame.getByRole('button', { name: '登录' }).click();
await contentFrame.getByRole('button', { name: '登录' }).click()
} 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
// The login will redirect to the main page which has a different structure
try {
await page.waitForLoadState('domcontentloaded', { timeout: 10000 });
await page.waitForLoadState('domcontentloaded', { timeout: 10000 })
} 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="确定"))
try {
const confirmBtn = mainFrame.getByRole('button', { name: '确定' });
const count = await confirmBtn.count();
const confirmBtn = mainFrame.getByRole('button', { name: '确定' })
const count = await confirmBtn.count()
if (count > 0) {
console.log('Force login detected, clicking confirm button');
await confirmBtn.first().click();
await page.waitForTimeout(2000);
console.log('Force login detected, clicking confirm button')
await confirmBtn.first().click()
await page.waitForTimeout(2000)
} else {
console.log('Normal login, no confirmation dialog');
console.log('Normal login, no confirmation dialog')
}
} catch (e) {
// 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)
@@ -121,10 +121,10 @@ export class ErpAuthService {
context,
page,
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> {
if (this.session) {
await this.session.context.close();
await this.session.browser.close();
this.session = null;
await this.session.context.close()
await this.session.browser.close()
this.session = null
}
}
@@ -143,15 +143,15 @@ export class ErpAuthService {
*/
getSession(): ErpSession {
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
*/
isActive(): boolean {
return this.session?.isLoggedIn ?? false;
return this.session?.isLoggedIn ?? false
}
}

View File

@@ -1,9 +1,9 @@
import path from 'path';
import fs from 'fs/promises';
import { ERP_LOCATORS } from './locators';
import { ErpAuthService } from './erp-auth';
import type { ExtractorInput, ExtractorResult } from '../../types/extractor.types';
import type { ErpSession } from '../../types/erp.types';
import path from 'path'
import fs from 'fs/promises'
import { ERP_LOCATORS } from './locators'
import { ErpAuthService } from './erp-auth'
import type { ExtractorInput, ExtractorResult } from '../../types/extractor.types'
import type { ErpSession } from '../../types/erp.types'
/**
* ERP Data Extractor Service
@@ -12,15 +12,15 @@ import type { ErpSession } from '../../types/erp.types';
* Reference: playwrite/utils/discrete_material_plan_extractor.py
*/
export class ExtractorService {
private authService: ErpAuthService;
private downloadDir: string;
private authService: ErpAuthService
private downloadDir: string
constructor(authService: ErpAuthService, downloadDir = './downloads') {
this.authService = authService;
this.downloadDir = downloadDir;
this.authService = authService
this.downloadDir = downloadDir
// Ensure download directory exists
fs.mkdir(downloadDir, { recursive: true }).catch(() => {});
fs.mkdir(downloadDir, { recursive: true }).catch(() => {})
}
/**
@@ -31,43 +31,49 @@ export class ExtractorService {
downloadedFiles: [],
mergedFile: null,
recordCount: 0,
errors: [],
};
errors: []
}
try {
const session = this.authService.getSession();
const session = this.authService.getSession()
// 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
const batchSize = input.batchSize || 100;
const batches = this.createBatches(input.orderNumbers, batchSize);
const batchSize = input.batchSize || 100
const batches = this.createBatches(input.orderNumbers, batchSize)
for (let i = 0; i < batches.length; i++) {
const batch = batches[i];
const progress = ((i + 1) / batches.length) * 100;
const batch = batches[i]
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 {
const filePath = await this.downloadBatch(session, popupPage, workFrame, batch, i, batches.length);
result.downloadedFiles.push(filePath);
const filePath = await this.downloadBatch(
session,
popupPage,
workFrame,
batch,
i,
batches.length
)
result.downloadedFiles.push(filePath)
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
result.errors.push(`Batch ${i + 1}: ${message}`);
const message = error instanceof Error ? error.message : 'Unknown error'
result.errors.push(`Batch ${i + 1}: ${message}`)
}
}
// TODO: Merge files (implement in separate task)
// result.mergedFile = await this.mergeFiles(result.downloadedFiles);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
result.errors.push(`Extraction failed: ${message}`);
const message = error instanceof Error ? error.message : 'Unknown error'
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
* 5. setup_query_interface(work_frame) - Setup query interface
*/
private async navigateToExtractorPage(session: ErpSession): Promise<{ popupPage: any; workFrame: any }> {
const { page, mainFrame } = session;
private async navigateToExtractorPage(
session: ErpSession
): Promise<{ popupPage: any; workFrame: any }> {
const { page, mainFrame } = session
// Step 1: Click menu icon (Python line 266)
// 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)
const popupPromise = page.waitForEvent('popup');
await mainFrame.getByTitle('离散备料计划维护', { exact: true }).first().click();
const popupPage = await popupPromise;
const popupPromise = page.waitForEvent('popup')
await mainFrame.getByTitle('离散备料计划维护', { exact: true }).first().click()
const popupPage = await popupPromise
// Step 3 & 4: Get nested frame structure in popup window (Python lines 273-276)
// popup page contains #forwardFrame, which contains #mainiframe
const forwardFrameLocator = popupPage.locator('#forwardFrame');
const fFrame = await forwardFrameLocator.contentFrame();
const forwardFrameLocator = popupPage.locator('#forwardFrame')
const fFrame = await forwardFrameLocator.contentFrame()
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');
await innerFrameLocator.waitFor({ state: 'visible', timeout: 15000 });
const workFrame = await innerFrameLocator.contentFrame();
const innerFrameLocator = fFrame.locator('#mainiframe')
await innerFrameLocator.waitFor({ state: 'visible', timeout: 15000 })
const workFrame = await innerFrameLocator.contentFrame()
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)
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> {
// 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)
await innerFrame.getByText('订单号查询').click();
await innerFrame.getByText('订单号查询').click()
// 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)
const inputBox = innerFrame.locator('#rc_select_0');
await inputBox.fill('5000');
await inputBox.press('Enter');
const inputBox = innerFrame.locator('#rc_select_0')
await inputBox.fill('5000')
await inputBox.press('Enter')
}
/**
@@ -149,43 +157,40 @@ export class ExtractorService {
totalBatches: number
): Promise<string> {
// Fill order numbers (Python lines 143-145)
const textbox = workFrame.getByRole('textbox', { name: '来源生产订单号' });
await textbox.fill('');
await textbox.fill(orderNumbers.join(','));
const textbox = workFrame.getByRole('textbox', { name: '来源生产订单号' })
await textbox.fill('')
await textbox.fill(orderNumbers.join(','))
// 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)
await this.waitForLoading(workFrame);
await this.waitForLoading(workFrame)
// 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)
await workFrame.getByRole('button', { name: '更多' }).hover();
await workFrame.getByText('输出', { exact: true }).click();
await workFrame.getByRole('button', { name: '更多' }).hover()
await workFrame.getByText('输出', { exact: true }).click()
// Set threshold (Python lines 159-164)
const thresholdBox = workFrame
.locator('div')
.filter({ hasText: /^行数阈值$/ })
.locator('input[type="text"]');
await thresholdBox.fill('300000');
.locator('input[type="text"]')
await thresholdBox.fill('300000')
// Setup download handler and click confirm (Python lines 166-172)
const downloadPath = path.join(
this.downloadDir,
`temp_batch_${batchIndex + 1}.xlsx`
);
const downloadPath = path.join(this.downloadDir, `temp_batch_${batchIndex + 1}.xlsx`)
const downloadPromise = popupPage.waitForEvent('download');
await workFrame.getByRole('button', { name: '确定(Y)' }).click();
const downloadPromise = popupPage.waitForEvent('download')
await workFrame.getByRole('button', { name: '确定(Y)' }).click()
const download = await downloadPromise;
await download.saveAs(downloadPath);
const download = await downloadPromise
await download.saveAs(downloadPath)
return downloadPath;
return downloadPath
}
/**
@@ -193,11 +198,14 @@ export class ExtractorService {
* Reference: Python lines 148-153
*/
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 {
await loadingLocator.waitFor({ state: 'visible', timeout: 3000 });
await loadingLocator.waitFor({ state: 'hidden', timeout: 0 });
await loadingLocator.waitFor({ state: 'visible', timeout: 3000 })
await loadingLocator.waitFor({ state: 'hidden', timeout: 0 })
} catch {
// Loading completed quickly or never appeared
}
@@ -208,10 +216,10 @@ export class ExtractorService {
* Reference: Python group_order_ids() method lines 128-131
*/
private createBatches<T>(items: T[], batchSize: number): T[][] {
const batches: T[][] = [];
const batches: T[][] = []
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: {
usernameInput: '#username',
passwordInput: '#password',
submitButton: 'button[type="submit"]',
submitButton: 'button[type="submit"]'
},
// Main Frame
@@ -22,7 +22,7 @@ export const ERP_LOCATORS = {
// Inner iframe (inside forward frame)
innerIframe: '#mainiframe',
// Loading overlay text
loadingText: '加载中',
loadingText: '加载中'
},
// Extractor (Data Export) Page
@@ -43,7 +43,7 @@ export const ERP_LOCATORS = {
// Export dialog - threshold input
thresholdInputSelector: 'div:has-text(/^行数阈值$/) input[type="text"]',
// Confirm button
confirmButton: 'internal:has-text="确定(Y)"',
confirmButton: 'internal:has-text="确定(Y)"'
},
// Menu navigation
@@ -55,7 +55,7 @@ export const ERP_LOCATORS = {
// "All" tab
allTab: 'internal:role=tab[name="全部"]',
// Select input for setting limits
selectInput: '#rc_select_0',
selectInput: '#rc_select_0'
},
// Discrete material plan menu item
@@ -65,7 +65,7 @@ export const ERP_LOCATORS = {
cleaner: {
orderNumberInput: 'input[name="orderNumber"]',
materialGrid: 'table.material-grid tbody tr',
saveButton: 'button:has-text("保存")',
saveButton: 'button:has-text("保存")'
},
// Common Elements
@@ -74,6 +74,6 @@ export const ERP_LOCATORS = {
errorMessage: '.message.error',
confirmDialog: '.confirm-dialog',
confirmButton: 'button:has-text("确定")',
cancelButton: 'button:has-text("取消")',
},
};
cancelButton: 'button:has-text("取消")'
}
}