Commit Graph

27 Commits

Author SHA1 Message Date
test
103effcfca ♻️ style: format code with Prettier and fix .gitattributes
- Add *.yaml text eol=lf rule to .gitattributes for consistent line endings
- Format cleaner.ts with Prettier (parameter and chain formatting)
- Format CleanerPage.tsx (JSX formatting)
- Format cleaner.test.ts (array formatting)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 22:42:16 +08:00
test
6a2fba0e57 refactor(cleaner): batch query and controlled parallel order processing 2026-03-16 21:47:13 +08:00
test
9a640b96e6 test(e2e): improve dialog focus tests and code quality
Test improvements:
- Add error handling for Electron app launch in headless environments
- Update dialog selectors to use ARIA attributes for better reliability
- Implement actual test logic (previously skipped placeholders)
- Add screenshot capture evidence for test results
- Update test descriptions to match actual dialog types

Code quality improvements:
- Change 'let' to 'const' for variables that are not reassigned
- Improves code clarity and follows best practices

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 17:59:35 +08:00
test
62e1647eaf feat(a11y): add focus lock dependency and useDialogFocus hook
- Install react-focus-lock@2.13.7 for focus trap functionality
- Create useDialogFocus hook with focus management, Escape key handling,
  initial focus, focus restoration, and body scroll lock
- Create E2E test infrastructure with helper functions for focus testing
- Compatible with React 19 and Electron 39
2026-03-08 17:01:00 +08:00
test
6df16898da feat(logging): Wave 2 - integrate logging throughout application
This commit integrates the logging infrastructure across the entire application:

IPC Layer:
- Add logger-handler.ts with centralized IPC logging channels
- Integrate audit logging into auth, cleaner, extractor handlers
- Add structured logging for IPC operations and data flow

Service Layer:
- Add logger integration to ERP services (extractor, cleaner)
- Integrate logging into excel-parser and user DAO
- Add operation tracking and error logging

Renderer Layer:
- Add useLogger hook for component-level logging
- Update App.tsx with session and user activity logging
- Enable frontend audit trail for critical actions

Testing:
- Add comprehensive IPC logging integration tests
- Enhance unit test coverage for logger and audit-logger
- Add end-to-end logging flow validation

Types:
- Update preload type definitions for logging APIs

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 15:07:03 +08:00
test
5e6898fb40 feat(logging): Wave 1 - logging infrastructure complete
- Add logging config to config.yaml with level, auditRetention, appRetention
- Add 4 global exception handlers (uncaughtException, unhandledRejection, render-process-gone, child-process-gone)
- Create audit-logger.ts with JSONL format and 30-day rotation
- Define IPC logger channels (LOGGER_FORWARD) and preload API
- Define audit types (AuditAction enum, AuditEntry interface, AuditStatus enum)
- Add unit tests for audit logger

All typechecks passing. Wave 1 complete.
2026-03-08 13:49:31 +08:00
test
8f3e5273e2 refactor(ipc): harden channels and unify IPC contracts 2026-03-08 12:35:00 +08:00
test
54a82200b6 refactor: complete migration from .env to YAML configuration
BREAKING CHANGE: Application now uses config.yaml instead of .env files

## Changes:
- Remove dotenv dependency from package.json
- Update all services to use ConfigManager for configuration
- Update tests to use fixed credentials instead of env vars
- Delete obsolete config-manager.test.ts (used old .env API)
- Update documentation (README.md, CLAUDE.md) to reflect new config system

## Configuration Architecture:
- ConfigManager: Centralized YAML configuration with Zod validation
- config.yaml location:
  - Development: Project root (easy to edit and version control)
  - Production: User AppData (persists across updates)
- ERP credentials: Stored in database (dbo_BIPUsers) per user
- Other settings: Stored in config.yaml (database, paths, extraction, etc.)

## Files Modified:
- package.json: Removed dotenv dependency
- cleaner-handler.ts: Use ConfigManager.getDatabaseType()
- run-migration.ts: Read from config.yaml instead of .env
- All integration tests: Use fixed test credentials
- tests/setup.ts: Removed dotenv loading
- README.md, CLAUDE.md: Updated documentation

Migration is complete. Application no longer depends on .env files.
2026-03-07 17:22:13 +08:00
test
6f19890a84 refactor(erp-auth): implement precise login result detection with three outcomes
- Add waitForLoginResult() method using Promise.race to detect:
  - Success: .nc-workbench-icon element visible
  - Failure: '名称或密码错误' error text visible
  - Force login: click confirm button and re-detect
- Extract timeout constants (PAGE_LOAD_TIMEOUT, LOGIN_RESULT_TIMEOUT, FORCE_LOGIN_TIMEOUT)
- Improve error handling with clear error messages
- Add unit tests for class structure verification
- Fix test setup for Electron app mock

Fixes: ERP login success/failure detection was ambiguous
2026-03-07 14:07:08 +08:00
Misaka_Company
c61776a1ff style: apply Prettier formatting across codebase
Apply consistent code formatting using Prettier to improve code readability
and maintain style consistency throughout the project.

Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
2026-03-04 14:24:16 +08:00
Misaka_Company
63ea81e0d6 feat: add automatic database import after ERP data extraction
- Add DataImportService for reading Excel and importing to database
- Extend DiscreteMaterialPlanDAO with deleteBySourceNumbers and batchInsert
- Auto-trigger database write after successful Excel merge
- Support batch delete by SourceNumber and batch insert (1000/batch)
- Update ExtractorPage UI to show import results
- Fix SQL Server query to handle undefined recordset for DELETE/INSERT

Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
2026-03-04 12:50:27 +08:00
Misaka
e23cf71f78 feat: add material type management feature
- Add MaterialTypeManagementDialog component for managing material type keywords
- Add MaterialsTypeToBeDeletedDAO for database operations
- Add material-type-handler IPC handlers
- Update CleanerPage with type management button
- Add database fix scripts for AUTO_INCREMENT
- Update documentation for settings partial save and validation flow

Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
2026-03-03 22:51:11 +08:00
Misaka_Company
f3be0ad01d feat: implement savePartialSettings with validation and rollback
Implements the core savePartialSettings method that:
- Validates fields against UI_EDITABLE_FIELDS whitelist
- Deep merges partial updates with current settings
- Creates backup before saving
- Restores backup on save failure
- Reloads .env file to populate cache with correct keys

Added comprehensive tests:
- Partial update preserves existing fields
- Rejects non-whitelisted fields
- Handles nested object updates
- Restores backup on save failure

Fixed cache key inconsistency bug by clearing cache in loadEnvFile()
and reloading after save to ensure proper cache population.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-03 14:36:50 +08:00
Misaka_Company
7e37a9b1fc fix: use proper logger in ConfigManager backup/restore methods
Replace console.log/console.error with proper logger usage in
backupEnvFile and restoreBackup methods. Use the existing 'log' logger
created with createLogger('ConfigManager') following the same pattern
used in other methods.

Changes:
- Import createLogger and create log instance
- Replace console.log with log.debug in backupEnvFile
- Replace console.error with log.error in both methods
- Pass error and path metadata as objects for structured logging
- Fix test to use correct backup path (process.cwd() + src/main/.env.backup)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-03 14:04:42 +08:00
Misaka_Company
b5ef38f486 feat: add backup and restore mechanism to ConfigManager 2026-03-03 13:50:36 +08:00
Misaka_Company
765fb95644 feat: add deep merge and validation utility functions to ConfigManager
This commit adds utility functions to support partial settings save functionality:
- isObject: Type guard for plain objects
- deepMerge: Recursively merges objects, preserving unspecified fields
- validateEditableFields: Validates settings against UI editable field whitelist
- UI_EDITABLE_FIELDS: Whitelist of fields modifiable through UI

A failing test is included to verify the deep merge behavior.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-03 12:42:34 +08:00
Misaka
a05c8a9037 feat: add TypeORM, logger, schemas, hooks and stores
- Add TypeORM integration with data-source, entities and repositories
- Add logger service for structured logging
- Add Zod validation schemas for auth, cleaner and extractor
- Add custom React hooks (useAuth, useCleaner, useExtractor, useValidation)
- Add Zustand stores (useAppStore, useUserStore)
- Add UI components (Button, Modal, Toast)
- Add error types and ErpBrowserManager
- Refactor IPC handlers and services
- Add unit tests for new modules

Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
2026-03-02 23:10:15 +08:00
Misaka
484ca31d79 test: add E2E test for Extractor workflow using Playwright
- Create tests/e2e/extractor-workflow.test.ts with full workflow tests
- Add playwright.config.ts for E2E test configuration
- Add npm scripts: test:e2e, test:e2e:ui, test:e2e:report
- Update vitest.config.ts to exclude E2E tests
2026-03-01 15:53:03 +08:00
Misaka
5760b56f70 feat: implement IPC handlers, database services and Extractor UI
- Add SqlServerService and MySqlService for database persistence
- Implement IPC handlers for file, extractor, cleaner, and database operations
- Define IPC API types and update preload script
- Create ExtractorPage UI with OrderNumberInput component
- Add unit and integration tests for MySQL and SQL Server
- Update vitest config with path aliases
2026-03-01 15:46:01 +08:00
Misaka
c39e1504aa style: apply prettier formatting
Apply consistent formatting across all files (line endings, spacing)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 14:57:38 +08:00
Misaka
8f6ca7b453 feat: implement CleanerService for ERP material deletion
**Core Implementation (src/main/services/erp/cleaner.ts):**
- CleanerService class with dry-run mode support
- Material deletion logic with safety constraints:
  - Row numbers 7000-7999 are protected
  - Materials with pending quantity are skipped
  - Materials not in delete list are ignored
- Order processing with nested iframe navigation
- Progress callback support for UI integration

**Types (src/main/types/cleaner.types.ts):**
- CleanerInput: order numbers, material codes, dry-run flag
- CleanerResult: processing statistics and details
- OrderCleanDetail: per-order breakdown

**Tests:**
- Unit tests for shouldDeleteMaterial logic
- Integration tests for order processing
- Dry-run mode validation
- Navigation tests

Reference: playwrite/utils/discrete_material_plan_cleaner.py

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 14:53:49 +08:00
Misaka
b22f4995ba feat: implement ERP authentication, data extraction, and Excel parsing
This commit completes the core ERP automation functionality, migrating
from Python Playwright to TypeScript while maintaining full compatibility
with the original implementation.

**ERP Authentication Service (erp-auth.ts):**
- Implement login() with role-based locators for form elements
- Add SSL certificate bypass for internal VPN network
- Handle force login confirmation dialogs
- Return session with mainFrame reference for subsequent operations
- Add session lifecycle management (close, getSession, isActive)

**Data Extractor Service (extractor.ts):**
- Implement precise nested iframe navigation (#forwardFrame → #mainiframe)
- Add batch processing support for multiple order numbers
- Implement order number filling with comma separation
- Handle material selection and download workflows
- Successfully tested with 300 orders in 5 batches

**Excel Parser Service (excel-parser.ts):**
- Fix ExcelJS 1-indexed array access (row[1] for 序号, row[2] for 材料编码)
- Add dynamic table header search to handle empty row skipping
- Add field mapping: "来源单号" → "productionOrder"
- Implement saveAsExcel() method compatible with Python format
- Validate compatibility: 527 rows, 69 orders matching Python output

**Type Definitions (erp.types.ts):**
- Add headless property to ErpConfig for browser mode control
- Add mainFrame reference to ErpSession for frame reuse

**Integration Tests (extractor.test.ts):**
- Modify tests to use independent auth services for isolation
- Add test with 300 orders and batch size 70
- All tests passing with real ERP data

**Test Configuration (vitest.config.ts):**
- Add setupFiles configuration for environment variable loading

**Testing Results:**
-  Successfully logs in to ERP system
-  Processes 300 orders in 5 batches (43.59 seconds)
-  Downloads 5 Excel files (347.62 KB total)
-  Parses 2,131 material plans from 280 unique orders
-  Excel output matches Python format exactly

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 14:22:14 +08:00
Misaka
d9e0091602 feat: implement Excel parser service
Implement Excel parsing module for ERP exported files following TDD principles.

Key features:
- Parse Excel files with multiple orders per file
- Extract order header information (production order, product code, etc.)
- Extract material data rows with 13 fields
- Handle empty orders gracefully
- Detect footer rows (制单人/打印人)
- Map Chinese field names to English property names
- Support field name mapping from Python reference

Implementation:
- ExcelParser class with parse() method
- DiscreteMaterialPlan and ExcelParseOptions types
- OrderHeader interface for order metadata
- Test fixtures with realistic Excel structure
- Comprehensive unit tests (3 tests, all passing)

Reference: playwrite/utils/excel_converter.py

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 13:01:50 +08:00
Misaka
f6b19b50f3 feat: implement Extractor service with download capability
Implement Task 3.1: Core Extractor Logic with TDD approach.

Changes:
- Add ExtractorService class with batch processing and download support
- Update ERP_LOCATORS with extractor-specific selectors from Python reference
- Add integration tests for single and multiple order extraction
- Add unit tests for batch creation logic
- Update existing tests to skip gracefully without ERP credentials

Features:
- Navigate to discrete material plan page with nested iframes
- Setup query interface (search icon, order query, limit settings)
- Batch download with configurable batch size (default: 100)
- Progress callback support for real-time updates
- Error handling for individual batch failures
- File download handling with proper wait strategies

Reference: playwrite/utils/discrete_material_plan_extractor.py

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 12:46:15 +08:00
Misaka
f045d66b65 feat: implement ERP authentication service
Implement ErpAuthService with TDD approach:
- Add login(), close(), getSession(), isActive() methods
- Use Playwright chromium with headless:false for debugging
- Manage browser lifecycle and session state
- Handle authentication flow with ERP_LOCATORS
- Add integration tests for login scenarios
- Add unit tests for session management
- Fix dotenv config path in test setup

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 12:34:54 +08:00
Misaka
c66dc2ecf8 feat: define ERP page element locators
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 12:21:58 +08:00
Misaka
9ac8707921 feat: configure Vitest testing framework
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-01 12:12:33 +08:00