Commit Graph

350 Commits

Author SHA1 Message Date
test
975bee6ce8 docs(cleaner): add comprehensive order error collection analysis
Add complete technical documentation for the material cleaning module's order error collection mechanism, including:
- System architecture and error collection flow diagrams
- Complete checklist of 52 error points across all layers
- Multi-layer error handling (IPC/service/retry layers)
- Frontend error display flow
- Retry mechanism and audit trail

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 22:30:45 +08:00
test
6a2fba0e57 refactor(cleaner): batch query and controlled parallel order processing 2026-03-16 21:47:13 +08:00
Misaka_Company
9248be6310 ♻️ refactor(ui): use global toast system in SettingsPage
- Replace local message state with global showSuccess/showError
- Remove inline message display component from SettingsPage
- Center toast notifications for better visibility

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 16:16:06 +08:00
Misaka_Company
ad8b3deb00 feat(order-resolver): add deduplication logic for production order number resolution
- Add P0: DISTINCT in SQL query to prevent database duplicates
- Add P1: Input layer deduplication to avoid redundant queries
- Add P2: Return layer deduplication in getValidOrderNumbers()
- Optimize resolve() to use batch query instead of loop queries
- Add getDeduplicationReport() for human-readable mapping summary
- Improve extraction logs to show deduplication statistics
- Only log merged mappings (multiple productionIDs → one order number)
- Remove duplicate marking as error (normal business scenario)
- Bump version to 1.0.1

Example log output:
  输入 5 个总排号 → 解析为 2 个唯一订单号(3 个重复已合并)
  重复合并详情:
    SC70202603120085 ← 26B12214、26B12213、26B12212 (共 3 个总排号)
    SC70202603120131 ← 26B12125、26B12126 (共 2 个总排号)
2026-03-16 16:02:52 +08:00
Misaka_Company
cccc4e4c8c feat(ui): display version and git hash in header
Add version info display below "ERP Auto" logo showing format:
${version}(${git-hash})

- Inject __APP_VERSION__ and __GIT_HASH__ via vite define
- Add TypeScript declarations for global constants
- Simplify portable artifact name (remove version)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 15:00:38 +08:00
Misaka_Company
9e577a2226 fix(types): add missing clearSharedProductionIds to ValidationAPI
The method was implemented in preload/index.ts but missing from the
type definition, causing TypeScript compilation to fail.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 09:59:36 +08:00
Misaka_Company
715dfb4d71 feat(cleaner): add automatic retry mechanism for failed orders
- Add retry logic with max 2 attempts per failed order
- Track retry statistics (retriedOrders, successfulRetries)
- Generate detailed retry report section in execution reports
- Display retry metrics in ExecutionReportDialog UI

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-13 15:59:10 +08:00
test
a25ffd75c5 Merge branch 'dev' of github.com:Misaka-Dev-Hub/ERPAuto into dev 2026-03-10 19:20:54 +08:00
Misaka_Company
8eaba79c26 fix(order-resolver): correct SQL Server table name conversion for productionId lookup
- Fix getTableName to properly split schema_tablename format
- Convert productionContractData_26年压力表合同数据 to [productionContractData].[26年压力表合同数据]
- Extend productionId pattern to support 1-6 digit serial numbers

Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
2026-03-09 09:31:32 +08:00
Misaka_Company
05a44bb464 chore: add .npmrc to gitignore
Co-Authored-By: Claude (glm-5) <noreply@anthropic.com>
2026-03-09 09:10:24 +08:00
test
77fabf2018 fix(shared-state): clear shared Production IDs when input is cleared
Fixes a bug where clearing the order number input in the extraction page
did not clear the shared Production IDs in the main process. This caused
the data cleanup page to continue using stale data when filtering by
Production ID.

Changes:
- Add VALIDATION_CLEAR_SHARED_PRODUCTION_IDS IPC channel
- Register handler to clear shared Production IDs by sender ID
- Expose clearSharedProductionIds API in preload script
- Update ExtractorPage to call clear when order numbers are empty

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 21:58:56 +08:00
test
13187ddce1 feat(validation): add source number validation checks with localized error messages
Add validation to detect and report when no order numbers are found from Production IDs (either from shared inputs or file). Provides clear Chinese error messages to guide users when their inputs don't match any database records.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 19:18:54 +08:00
test
33b17e278d refactor(ui): replace native alerts with toast notifications and confirm dialogs
This commit refactors all native browser alert() and confirm() dialogs to use
the app's custom UI components for consistent user experience.

**Changes:**
- Add ConfirmDialog component with danger/warning/info variants
- Add useConfirmDialog hook for promise-based dialog API
- Add formatListMessage utility for truncating long lists
- Replace 18 alert() calls with toast notifications in useCleaner.ts
- Replace 7 alert()/confirm() calls in MaterialTypeManagementDialog.tsx
- Render Toast component in App.tsx for global notifications
- Add keyboard shortcuts (Enter to confirm, Escape to cancel)

**Benefits:**
- Consistent UI design across all notifications
- Non-blocking notifications for better UX
- Better accessibility with proper ARIA roles and focus management
- Multi-line message support with truncation for long lists

**Files Modified:**
- src/renderer/src/components/ui/ConfirmDialog.tsx (new)
- src/renderer/src/stores/useAppStore.ts (add formatListMessage)
- src/renderer/src/hooks/useCleaner.ts (refactor error handling)
- src/renderer/src/components/MaterialTypeManagementDialog.tsx (refactor dialogs)
- src/renderer/src/pages/CleanerPage.tsx (add ConfirmDialog)
- src/renderer/src/App.tsx (render Toast component)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 19:13:25 +08:00
test
bcfe0eecca fix(a11y): improve focus restoration with timing fixes, validation, and error handling
Core improvements:
- Fix focus restoration timing by using queueMicrotask only (removed double-layer async)
- Add comprehensive error handling with dev-mode logging for all failure scenarios
- Validate element visibility (display: none, visibility: hidden) before restoring focus
- Check disabled state and implement fallback to nearest focusable ancestor
- Add findNearestFocusableElement() helper for robust fallback strategy
- Add tabindex="-1" to focusable selectors for better focus management
- Use preventScroll option when calling focus() to prevent scroll jumps

Additional fixes:
- Remove unnecessary type conversion in Modal.tsx
- Fix TypeScript unused variable errors in main process
- Clean up unused imports in bip-users-dao.ts
- Add ARIA attributes and focus management to LoginDialog
- Add triggerRef support to UserSelectionDialog and ExecutionReportDialog
- Refactor ExecutionReportDialog to use Modal component
- Improve MaterialTypeManagementDialog with focus management

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 18:29:39 +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
5b4d7fab49 refactor(a11y): optimize dialog focus management with centralized Escape handling
Enhanced the useDialogFocus hook to support conditional Escape key handling,
removing redundant Escape key listeners from individual dialog components.

Changes:
- Added shouldCloseOnEscape option to useDialogFocus (boolean or function callback)
- Removed redundant Escape key handlers from Modal, ExecutionReportDialog, and LoginDialog
- ExecutionReportDialog now uses shouldCloseOnEscape: () => !isExecuting to prevent
  closing during execution
- LoginDialog no longer has manual focus effect (handled by initialFocusSelector)
- Fixed React hooks order violations in ExecutionReportDialog
- Added proper TypeScript return types throughout

Benefits:
- Centralized Escape key logic in one place
- Consistent behavior across all dialogs
- Reduced code duplication (~50 lines removed)
- Easier to maintain and extend

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 17:58:16 +08:00
test
72d8d981b1 feat(a11y): add focus management to UserSelectionDialog and ExecutionReportDialog
UserSelectionDialog:
- Add ARIA attributes (role, aria-modal, aria-labelledby)
- Integrate useDialogFocus hook with FocusLock
- Add Escape key handling (was missing)
- Initial focus on first user card

ExecutionReportDialog:
- Add ARIA attributes with dynamic aria-labelledby
- Add aria-live for progress updates
- Integrate useDialogFocus hook with FocusLock
- Escape key only closes when not executing
2026-03-08 17:16:53 +08:00
test
d1f2f40123 feat(a11y): add focus management to LoginDialog
- Add role="dialog", aria-modal="true", aria-labelledby
- Add aria-live="polite" and role="alert" on error messages
- Integrate useDialogFocus hook with FocusLock
- Maintain initial focus on username input
- Maintain Enter key submit and Escape key close
- Refactor error handling with internal state
2026-03-08 17:09:37 +08:00
test
545048045d feat(a11y): add ARIA attributes and focus trap to Modal component
- Add role="dialog" and aria-modal="true" to modal container
- Add aria-labelledby linked to title element
- Integrate useDialogFocus hook for focus management
- Wrap content with FocusLock from react-focus-lock
- Add triggerRef prop for focus restoration
- Add titleId prop for custom aria-labelledby
- Preserve existing Escape key and backdrop click behavior
2026-03-08 17:04:04 +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
fba2c73782 feat(logging): Wave 3 - add comprehensive error serialization with stack traces
- Add error-utils module with serializeError and sanitizeError utilities
- Enhance IPC error handling to capture full error context including stack traces
- Add logError helper function for consistent error logging across the application
- Update console and file log formats to properly serialize error objects
- Replace all basic error logging in BIPUsersDAO with structured logError calls
- Add ErrorLike and SerializedError type interfaces for type safety

This improves debugging capability by preserving full error details in development
while sanitizing sensitive information in production logs.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 16:10:23 +08:00
test
c4fff84848 style: format code with Prettier
Apply Prettier formatting to maintain consistent code style across the codebase.
Changes include formatting improvements for:
- IPC handlers (database, file, material-type, resolver, user-erp-config, validation)
- Type definitions (ipc-api.types)
- React components (MaterialTypeManagementDialog)
- React hooks (useAuth, useCleaner, useValidation)
- Pages (SettingsPage)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 15:17:40 +08:00
test
57c3452d82 fix(types): resolve TypeScript unused variable errors
Fix all TS6133 errors (unused variables) across service layer:

- Remove unused imports (path, ExtractionProgress type)
- Prefix unused parameters with underscore (_session, _totalBatches, etc.)
- Remove unused _verbose field and constructor from ExcelParser
- Remove unused _importToDatabase method from ExtractorService
- Remove unused _importProgress variable

This ensures clean type checking and eliminates dead code.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 15:16:26 +08:00
test
f412e0e72c chore: ignore TypeScript build info files
Remove tsbuildinfo files from version control and add to .gitignore.
These are incremental compilation cache files that should be generated locally.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 15:08:54 +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
f45d3df385 fix(component): fix stale closure in MaterialTypeManagementDialog
Fix issue where keyword field was not editable after adding new row via Insert key or Add button. Root cause was incomplete useCallback dependencies in handleKeyDown, causing it to capture stale references to insertNewRow, deleteRow, saveEdit, and cancelEdit functions.

Changes:
- Wrap insertNewRow with useCallback (deps: isAdmin, currentUsername)
- Wrap deleteRow with useCallback (deps: none)
- Wrap startEdit with useCallback (deps: rows)
- Wrap saveEdit with useCallback (deps: editingCell, editValue)
- Wrap cancelEdit with useCallback (deps: none)
- Update handleKeyDown dependency array to include all referenced functions

This ensures all callbacks have access to the latest props and state, preventing the edit mode initialization failure.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-08 13:22:43 +08:00
test
8f3e5273e2 refactor(ipc): harden channels and unify IPC contracts 2026-03-08 12:35:00 +08:00
test
616e2b31a5 fix: add 'nul' to .gitignore to prevent tracking of nul files 2026-03-08 11:22:00 +08:00
test
b3abad7fae feat(playwright): enable Playwright in production builds with custom browser path
Move Playwright from dev to production dependencies and implement robust browser
management for company deployment environment:

- Move playwright and playwright-core to dependencies
- Set PLAYWRIGHT_BROWSERS_PATH to user data directory before imports
- Add startup validation for Chromium browser with friendly error dialog
- Update build scripts to skip browser download during build process
- Configure electron-builder to unpack Playwright for native module access
- Add deployment documentation for browser setup in restricted environments

This allows manual browser installation in company environments where direct
downloads are blocked during build.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 19:03:29 +08:00
test
9d15f7aca9 Merge branch 'cleanup/remove-env-variables' into dev 2026-03-07 17:28:14 +08:00
test
310d5e462f fix(hook): fix race condition in progress dialog initialization
Initialize progress state before opening the execution report dialog to ensure the progress view displays correctly from the start.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 17:26:57 +08:00
test
c4bacdaf2a fix: correct TypeScript type for YAML config parsing in migration script 2026-03-07 17:25:12 +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
2d6838c0e7 fix(component): fix race condition in MaterialTypeManagementDialog row addition
Use functional setState to correctly calculate new row index based on
latest state, preventing stale closure issues.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 15:50:47 +08:00
test
73b8f2409a fix(validation): migrate DB config from env to ConfigManager
- Refactor getValidationDatabaseService() to use ConfigManager
- Refactor getTableName() to use ConfigManager.getDatabaseType()
- Replace all process.env.DB_TYPE references with ConfigManager API
- Simplify isSqlServer checks from 'sqlserver||mssql' to 'sqlserver'
- Preserve all business logic and dual-database support
- Typecheck passes successfully

Fixes issue where Cleaner page failed with 'Failed to connect to MySQL'
due to validation-handler.ts not being migrated in commit c13be9e
2026-03-07 15:14:15 +08:00
test
c7c192a703 chore(extractor): add error logging for ERP login failures
Added error message extraction and logging to improve user feedback and debugging when ERP login fails during material plan extraction.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 14:51:50 +08:00
test
42bd6dcb8a chore: remove config.yaml from tracking
Runtime config file should not be tracked in git

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 14:23:23 +08:00
test
e4a92e9be4 chore: ignore runtime config files and reorganize .gitignore
- Ignore *.yaml and *.yaml.backup files
- Reorganize sections with clear comments

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 14:17:49 +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
test
1ee33672dd refactor: implement precise login result detection in ERP auth service
Add waitForLoginResult() method with Promise.race to detect three login outcomes:
- Success: detects .nc-workbench-icon element
- Failure: detects '名称或密码错误' error text
- Force login: clicks confirm button and re-detects

Improves login reliability by properly handling all authentication scenarios.

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-opencode)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-03-07 13:48:41 +08:00
test
8e0c37bf74 feat: add ERP login debug tool with documentation
Add interactive debugging tool for ERP login flow analysis:
- Add tsx dependency for TypeScript script execution
- Add npm scripts: debug:erp-login and debug:config-path
- Add erp-login-debug.ts with automated login and element inspection
- Add comprehensive usage guide and quick reference documentation

The debug tool automates ERP login and provides pause points for
manual element inspection using browser DevTools or Playwright Inspector.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-07 13:16:43 +08:00
test
c13be9e19a refactor: migrate configuration to YAML-based system 2026-03-07 11:30:09 +08:00
Misaka
48f1f51d76 refactor: remove unused UI and execution configuration
Remove unused configuration options that were not consumed by the UI:

- Remove UI configuration (UI_FONT_FAMILY, UI_FONT_SIZE, UI_PRODUCTION_ID_INPUT_WIDTH)
  - No UI components were using these settings
  - Settings page had no inputs for these options

- Remove execution configuration (EXECUTION_DRYRUN)
  - Dry run mode is controlled by Cleaner page UI toggle
  - State is managed via sessionStorage, not config file

Files modified:
- src/main/types/settings.types.ts: Remove UiConfig and ExecutionConfig interfaces
- src/main/services/config/config-manager.ts: Remove config read/write logic
- src/main/ipc/settings-handler.ts: Remove filtered fields
2026-03-05 22:02:53 +08:00
Misaka
5977254180 feat: migrate ERP configuration from .env to per-user database storage
- Moved ERP credentials (URL, username, password) from environment variables to dbo_BIPUsers table
- Each user now has their own ERP configuration stored in the database
- Added UserErpConfigService for managing per-user ERP settings
- Updated cleaner and extractor handlers to fetch ERP config from database instead of .env
- Removed ERP fields from ConfigManager UI editable fields
- Added new IPC handlers and preload APIs for user ERP config management
- Includes migration script to transfer existing .env ERP settings to database
- Added migration guide documentation

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-05 21:52:54 +08:00
Misaka
3d2127b660 fix: correct ComputerNmae typo to ComputerName in BIPUsers DAO
- Fix column name typo in BIP_USERS_CONFIG constant
- Update SQL queries to use correct ComputerName column
- Add migration scripts for database schema fix (JS and SQL)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-03-05 20:35:33 +08:00
google-labs-jules[bot]
7db7f513be refactor: hardcode erp headless and browser settings instead of env vars
- Removed ERP_HEADLESS, ERP_IGNORE_HTTPS_ERRORS, ERP_AUTO_CLOSE_BROWSER from ConfigManager .env operations.
- Hardcoded these values in ConfigManager's default settings and getAllSettings() return.
- Hardcoded ignoreHTTPSErrors to true inside ErpBrowserManager when creating a new browser context.

Co-authored-by: luwamgere15-crypto <255338376+luwamgere15-crypto@users.noreply.github.com>
2026-03-05 10:48:50 +00:00
Misaka_Company
a906f34ac2 feat: auto-generate markdown report after cleaner execution
- Add CleanerReportGenerator service to create execution reports
- Extend OrderCleanDetail with skippedMaterials for detailed tracking
- Record skip reasons for each material (protected range, pending qty, etc.)
- Generate timestamped markdown reports in logs/reports/ directory
- Reports include execution summary, order details, skip reasons, and errors
2026-03-05 16:19:40 +08:00
Misaka_Company
224a42e44b docs: update cleaner execution report error details section 2026-03-05 15:07:17 +08:00
Misaka_Company
7d2cf934f8 feat: add estimated completion time to cleaner progress dialog
- Display remaining time estimate (in minutes) when progress >= 5%
- Show estimated completion time in 12-hour format (上午/下午 HH:MM:SS)
- Update every second during execution
- Add startTime state tracking in useCleaner hook
2026-03-05 14:17:34 +08:00