23 Commits

Author SHA1 Message Date
Misaka_Company
314c9baefe fix: resolve duplicate variable declaration compilation errors
All checks were successful
NTFY Notification / notify (push) Successful in 5s
- Move shouldExclude declaration to function level in MatchAllMaterialTypesWithValidation
- Move rawMat and result declarations to function level in BOMExtraction
- Remove duplicate Dim statements inside loops

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 13:22:10 +08:00
Misaka_Company
dd931eba53 fix: implement dual collection system for component materials and fix inventory comparison
All checks were successful
NTFY Notification / notify (push) Successful in 4s
- Add outRawMaterials parameter to ProcessSingleModel and MatchAllMaterialTypesWithValidation
- Implement dual collection system: filtered materials (allMaterials) and raw materials (outRawMaterials)
- Filter out component markers when isStockSufficient=False for BOM extraction results
- Preserve component markers in raw materials for inventory comparison worksheet
- Add productionOrderNo field to rawMaterials for proper order tracking
- Fix sequence number generation in WriteInventoryComparisonResults (start from 10)
- Adapt data access from array format to dictionary format in WriteInventoryComparisonResults
- Add debug output for troubleshooting order number propagation

This ensures:
- BOM extraction results show actual materials used (component or sub-components)
- Inventory comparison worksheet always shows component information regardless of inventory status
- Proper order number mapping and sequence number generation

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 13:07:29 +08:00
Misaka_Company
c08a2f34e1 refactor: rename RunBOMExtraction to BOMExtraction for consistency
All checks were successful
NTFY Notification / notify (push) Successful in 4s
Rename the main BOM extraction function from RunBOMExtraction to BOMExtraction
to follow consistent naming conventions across the codebase.

Changes:
- M09_BOMExtractor.bas: Rename function RunBOMExtraction → BOMExtraction
- M01_Main.bas: Update function call to use new name
- Update all internal return statements and logger references

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 12:24:12 +08:00
Misaka_Company
7cb025c243 fix: resolve ByRef parameter type mismatch in error logger calls
All checks were successful
NTFY Notification / notify (push) Successful in 4s
Convert Long rowIdx parameters to String using CStr() for clsErrorLogger.Record/RecordWarning methods.

Changes:
- M03_Logic.bas: Add CStr() to 5 logger calls (lines 37, 112, 200, 208, 215)
- M03_Logic.bas: Change ParseAtom syntax error from Record to RecordWarning (non-blocking)
- M05_PreProcessor.bas: Add CStr() to mapping warning (line 318)

This resolves VBA compilation errors caused by passing Long type to ByRef String parameters.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 09:24:43 +08:00
Misaka_Company
0fc2cd1e92 feat: add worksheet button handlers for BOM systems
All checks were successful
NTFY Notification / notify (push) Successful in 3s
Add CommandButton click event handlers to worksheets:
- Sheet10: Trigger BOM Configuration System (RunBOMConversion)
- Sheet3: Trigger BOM Extraction System (RunBOMExtraction)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 08:39:01 +08:00
Misaka_Company
45d1c1780f style: standardize VBA property and method name casing
All checks were successful
NTFY Notification / notify (push) Successful in 11s
Standardize all VBA property and method names to lowercase for consistent code style:
- Err object: Err.Description → err.Description, Err.Number → err.Number
- Collection properties: .Count → .count
- Range properties: .Rows.Count → .Rows.count, .Row → .row
- Dictionary methods: .Keys → .keys, .Exists → .exists
- Worksheet properties: .Sheets.Count → .Sheets.count
- Fix typo: Thisworkbook.Path → ThisWorkbook.Path

VBA is case-insensitive, but consistent lowercase convention improves readability.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-27 08:34:49 +08:00
Misaka_Company
c696057cd4 feat: implement inventory comparison worksheet for component materials
All checks were successful
NTFY Notification / notify (push) Successful in 5s
Add new "库存比对" worksheet that displays component inventory status
alongside material requirements for production planning.

Changes:
- M04_Config: Add INVENTORY_COMPARISON_SHEET_NAME constant
- M08_ComponentProcessor: Enhance component processing to return both
  component and sub-components when inventory insufficient; add
  GetComponentInventoryInfo() read-only function for inventory lookup
- M09_BOMExtractor: Add WriteInventoryComparisonResults() function
  to generate inventory comparison worksheet with 7 columns showing
  material code, name, required quantity, stock quantity, and status

Output format:
- Columns: 序号, 生产订单号, 物料编码, 物料名称, 所需数量, 库存数量, 库存充足
- Color coding: Green (sufficient) / Red (insufficient)
- Sequence numbering: 10+0, 10+1 per order

Backward compatibility: Existing BOM提取结果 and BIP上传 worksheets
remain unchanged.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 17:55:20 +08:00
Misaka_Company
e086dee920 feat: implement BIP upload worksheet with quantity calculation fix
All checks were successful
NTFY Notification / notify (push) Successful in 4s
This commit implements the BIP upload worksheet functionality for ERP system integration and fixes a critical bug in quantity calculation.

Changes:
1. Added BIP upload configuration constants to M04_Config.bas
   - BIP_UPLOAD_SHEET_NAME = "BIP上传"
   - BIP_ROW_NUMBER_BASE = 7000
   - BIP_SUPPLY_MODE = "一般发料"
   - BIP_ISSUE_ORG = "重庆布莱迪仪器仪表有限公司"

2. Extended input data reading to 4 columns (M09_BOMExtractor.bas)
   - Column D: Product Code (产品编码)
   - Updated ReadInputModels to read columns A:D

3. Added product code mapping in main flow
   - Created productCodeMap Dictionary to store order number -> product code mappings
   - Stored product codes during input processing loop

4. Created WriteBIPUploadResults function
   - Generates 9-column BIP upload worksheet
   - Implements row number generation (7000 + material sequence number)
   - Resets sequence counter for each new order
   - Includes all rows (including error rows)
   - Formats worksheet with borders, column widths, and freeze panes

5. **CRITICAL FIX**: Corrected quantity calculation logic
   - Added order quantity lookup from inputModels
   - Changed from: materialQty = result(12) (BOM base quantity only)
   - Changed to: finalQty = bomQty * currentOrderQty
   - Applied fix to both "生产数量" (column 3) and "计划出库数量" (column 9)
   - Updated comment to clarify result(12) is BOM base quantity

Output Format (9 columns):
1. 来源单据号 (Source Document Number) - Production Order No
2. 产品编码 (Product Code)
3. 生产数量 (Production Quantity) = Order Qty × Material Qty
4. 行号 (Row Number) = 7000 + sequence (resets per order)
5. 材料编码 (Material Code)
6. 供应方式 (Supply Mode) = "一般发料"
7. 需用日期 (Required Date) = Current date (yyyy/m/d format)
8. 发料组织 (Issue Organization) = "重庆布莱迪仪器仪表有限公司"
9. 计划出库数量 (Planned Output Qty) = Order Qty × Material Qty

Business Rules Implemented:
- Error rows are included (material code is empty, quantities are 0)
- Empty product codes are written as empty strings
- Row numbers reset to 7001 for each new order
- Material quantities are correctly calculated as order quantity × BOM quantity

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 14:41:58 +08:00
Misaka_Company
44d6bdb750 fix: display all matched materials when multiple matches found in BOM extraction
All checks were successful
NTFY Notification / notify (push) Successful in 3s
Fixed a bug where materials matching multiple BOM library records would not
appear in the BOM extraction output. Previously, only the first match was
extracted when success=True, but multiple matches set success=False, causing
all materials to be skipped.

Changes:
- Modified M09_BOMExtractor.MatchAllMaterialTypesWithValidation()
- Changed condition from checking 'success' to checking 'rowCount > 0'
- Added loop to process ALL matching rows instead of just the first one
- Moved BuildWorksheetHeaderMap() outside loop for performance
- Enhanced debug logging to show row processing details

Impact:
- "机芯" (Movement) and "边" (Edge) sheets now show all matched materials
- Users can see and manually resolve ambiguous matches in output
- Component sheet handling unchanged (uses different code path)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 11:06:53 +08:00
Misaka_Company
c4d7b248c4 fix: improve component inventory insufficient error handling
All checks were successful
NTFY Notification / notify (push) Successful in 4s
- Change component inventory insufficient from Error to Warning type in error report
- Propagate productionOrderNo to M08_ComponentProcessor functions for proper error tracking
- Update CheckComponentInventory to record warnings instead of errors for insufficient inventory
- Pass productionOrderNo through ProcessComponentRecord call chain

Changes:
- M08_ComponentProcessor: Add productionOrderNo parameter to ProcessComponentRecord and CheckComponentInventory
- M08_ComponentProcessor: Change insufficient inventory Record to RecordWarning
- M08_ComponentProcessor: Use productionOrderNo in all error/warning recordings
- M09_BOMExtractor: Pass productionOrderNo to ProcessComponentRecord call

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 10:27:10 +08:00
Misaka_Company
7fea574531 refactor: replace row index with production order number in error reports
All checks were successful
NTFY Notification / notify (push) Successful in 12s
Replace "原表行号" (original row number) field with "生产订单号" (production order number) in BOM Extraction System error reporting to improve traceability.

Changes:
- clsErrorLogger: Update Record/RecordWarning signatures to accept OrderNo (String) instead of RowIndex (Long)
- M09_BOMExtractor: Propagate productionOrderNo through validation chain for context-aware error reporting
- M06/M07/M08: Use empty string for system-level errors without production order context
- Error report header: Change column B from "原表行号" to "生产订单号"

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-26 10:12:59 +08:00
Misaka_Company
8477792d41 feat: integrate inventory verification for component materials in BOM extraction
All checks were successful
NTFY Notification / notify (push) Successful in 7s
Implement inventory-based component selection logic that accumulates demand
across orders and falls back to sub-components (joint + element) when stock
is insufficient.

**Changes:**
- M04_Config: Add inventory worksheet configuration constants
  - INVENTORY_SHEET_NAME = "现存量"
  - INVENTORY_HEADER_ROW = 3 (headers on row 3)
  - INVENTORY_COL_CODE = "B" (material code)
  - INVENTORY_COL_QTY = "J" (stock quantity)

- M08_ComponentProcessor: Implement inventory tracking and verification
  - Add module-level variables: g_InventoryDict, g_AccumulatedDemandDict
  - Add LoadInventoryData() to load stock from [现存量] worksheet
  - Add InitComponentProcessorWithInventory() for initialization with inventory
  - Rewrite CheckComponentInventory() with actual inventory logic:
    * Calculate cumulative demand = orderQty × bomQty + previousAccumulated
    * Compare with available stock
    * Return True if stock sufficient, False otherwise
    * Update accumulated demand after each order
  - Update ProcessComponentRecord() to accept orderQty parameter

- M09_BOMExtractor: Integrate inventory check into main workflow
  - Modify ReadInputModels() to read 3 columns (orderNo, model, qty)
  - Initialize component processor with inventory support
  - Extract order quantity from column C and pass through call chain
  - Update ProcessSingleModel() and MatchAllMaterialTypesWithValidation()
    signatures to accept orderQty parameter

**Logic Example:**
- 3 orders (PO-001, PO-003, PO-006) use component A
- Each order: quantity=2, BOM qty=1, stock=5
- PO-001: cumulative=2, stock 5>=2 ✓ → return component
- PO-003: cumulative=4, stock 5>=4 ✓ → return component
- PO-006: cumulative=6, stock 5<6 ✗ → return sub-components

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-24 16:21:18 +08:00
Misaka_Company
24a54bd1ea feat: add production order number column to BOM extraction output
All checks were successful
NTFY Notification / notify (push) Successful in 4s
- Add 生产订单号 as the first column in output (13 columns total)
- Read production order number from column A of input worksheet
- Only display production order number on first row for each product model
- Set material code column to text format to preserve leading zeros
- Update OutputColumns enum indices in M04_Config.bas
- Update ReadInputModels to return 2 columns (order number + model)
- Update ProcessSingleModel, GenerateMaterialRow, GenerateErrorRow signatures
- Update WriteExtractionResults to write 13 columns with text formatting

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-24 14:28:24 +08:00
Misaka_Company
0579a546d3 feat: auto-save output workbook as BOM库.xlsx and clean default sheets
All checks were successful
NTFY Notification / notify (push) Successful in 6s
- Delete default sheets (Sheet1, Sheet2, etc.) created by Workbooks.Add
- Save output workbook as BOM库.xlsx in the same directory as source file
- Auto-close workbook after saving
- Update completion message to show save path
- Use ThisWorkbook.Path to get source file directory

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-24 12:50:35 +08:00
Misaka_Company
541bbfe0ad refactor: replace CODE field source from column C to column I (66代码)
All checks were successful
NTFY Notification / notify (push) Successful in 14s
- Add COL_IDX_CODE66 constant for column I in M04_Config.bas
- Extend data reading range to include column I in M02_DataIO.ReadSourceData
- Use .Text property for column I to preserve leading zeros
- Update baseInfo array to use column I instead of column C in M01_Main.bas
- Set output code column to text format to prevent numeric conversion

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-24 12:44:31 +08:00
Misaka_Company
53b3568412 feat: add special validation for edge material based on azxs parameter
All checks were successful
NTFY Notification / notify (push) Successful in 3s
Implement edge material validation logic that behaves differently based on azxs value:
- When azxs is A0, Z0, or B0: Edge material is NOT required (0 matches = OK, 1+ matches = ERROR)
- When azxs is AH, AT, BH, BT, BZ, ZH, ZT, or ZZ: Standard validation applies (exactly 1 match required)
- Supports dual-value azxs format (e.g., "A0,径向" extracts "A0" for validation)

Changes:
- M09_BOMExtractor.bas:
  - Update MatchAllMaterialTypesWithValidation to pass params to validation
  - Update ValidateAllMatchResults signature to accept params parameter
  - Add "边" to special sheets array
  - Implement Phase 3.5: Edge material validation with azxs-based rules
  - Update function header comments

- docs/BOM匹配错误判断机制详解.md:
  - Add section 6.5: Edge material special handling
  - Update error type table with EdgeMaterialError
  - Update function index and version history

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 18:31:33 +08:00
Misaka_Company
1d5bad86f7 feat: add preprocessing with value mapping to BOM Extraction System
All checks were successful
NTFY Notification / notify (push) Successful in 4s
Add a preprocessing step to the BOM Extraction System to enhance parameter
extraction with mapping values from "对照表" worksheet. For azxs (安装形式)
and lcfw (量程范围), the system now stores both the raw parsed value AND the
mapped value from the lookup table, enabling flexible dual-value matching.

Changes:
- Create M06A_Mapper.bas: New module for value mapping
  - Load azxs/lcfw mappings from "对照表" worksheet
  - Return dual-value format "raw,mapped" (e.g., "A0,径向")
  - Support graceful degradation if "对照表" not found
  - Define constants locally to avoid VBA cross-module reference issues

- Modify M06_ModelParser.bas:
  - Extract raw parameter values first
  - Apply mapping via M06A_Mapper if initialized
  - Store dual values for azxs and lcfw parameters

- Modify M07_BOMMatcher.bas:
  - Update EvaluateCellCondition() to support dual-value matching
  - Split by comma and check if ANY value matches
  - Backward compatible with single-value parameters

- Modify M09_BOMExtractor.bas:
  - Initialize M06A_Mapper during RunBOMExtraction()
  - Add WorksheetExists() helper function
  - Log warning if "对照表" worksheet not found
  - Define MAPPING_SHEET_NAME constant locally

- Modify M04_Config.bas:
  - Add mapping table configuration constants
  - MAPPING_SHEET_NAME, MAPPING_COL_LCFW_KEY, etc.

- Update CLAUDE.md:
  - Document new M06A_Mapper module
  - Update data flow diagram with mapping step
  - Document dual-value matching behavior
  - Update system architecture diagram

- Update docs/RunBOMExtraction_运行机制详解.md:
  - Add M06A_Mapper to all diagrams and documentation
  - Add detailed value mapping section
  - Update sequence diagrams with mapping flow
  - Update parameter examples with dual-value format
  - Bump documentation version to 3.0

Example:
  Input:  Product model "YTHN-100.A0.531.G123.M04.Y3"
  Parse:  azxs="A0", lcfw="M04"
  Map:    azxs="A0,径向", lcfw="M04,高压"
  Match:  BOM库 with azxs="径向" OR "A0" → MATCH

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 17:52:03 +08:00
Misaka_Company
78241f2b8d fix: component worksheet rowCount false positive validation error
Some checks failed
NTFY Notification / notify (push) Failing after 3s
Fix critical bug in BOM matching validation: when [部件] worksheet matches 1 record
but returns 2 sub-components, system incorrectly reports "matched 2 records".

Root Cause:
- matchResult("rowCount") incorrectly used componentMaterials.count (material count)
- instead of bomMatchResult("rowCount") (worksheet row count)
- Caused 1-row match returning 2 sub-components to be misreported as "2 matches"

Solution:
1. M08_ComponentProcessor.ProcessComponentRecord: Add matchedRowNum parameter,
   receive matched row number from caller, avoid redundant internal matching

2. M09_BOMExtractor: Implement two-phase matching flow
   - Phase 1: Call MatchBOMRecord to get standard match result (with correct rowCount)
   - Phase 2: If match succeeds, call ProcessComponentRecord to process component logic
   - matchResult("rowCount") always uses standard match's rowCount (worksheet row count)

Fix Results:
- Scenario 1: [部件] matches 1 row, returns 1 component → rowCount=1 
- Scenario 2: [部件] matches 1 row, returns 2 sub-components → rowCount=1  (no false positive)
- Scenario 3: [部件] matches 0 rows → rowCount=0, correct error 
- Scenario 4: [部件] matches 2+ rows → rowCount=2, correct error 

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 15:54:50 +08:00
Misaka_Company
8271958adf refactor: implement two-phase BOM matching error validation with warning support
All checks were successful
NTFY Notification / notify (push) Successful in 4s
Major refactoring of BOM matching error handling mechanism to separate
matching phase from validation phase, enabling cross-worksheet validation
and non-blocking warnings.

Changes:
- clsErrorLogger: Add warning support
  - Add RecordWarning() method for non-blocking issues
  - Add HasWarnings and HasIssues properties
  - Update PrintReport() to show errors and warnings with color coding
  - Add "Type" column to distinguish errors from warnings

- M09_BOMExtractor: Implement two-phase validation
  - Replace MatchAllMaterialTypes() with MatchAllMaterialTypesWithValidation()
  - Add ValidateAllMatchResults() for unified cross-worksheet validation
  - Phase 1 (Collection): Gather all worksheet matches without recording errors
  - Phase 2 (Validation): Validate all results with special rules for components
  - Phase 3 (Generation): Create final material collection based on validation
  - Add ToArray() helper for Collection to Array conversion

- Enhanced component/joint/element validation:
  - Support warnings for non-blocking conflicts (e.g., component + joint both matched)
  - Better cross-validation between "部件", "接头", "弹性元件" worksheets
  - Distinguish between errors (blocking) and warnings (non-blocking)

- Documentation updates:
  - Update BOM匹配错误判断机制详解.md to v2.0
  - Document two-phase verification approach
  - Add warning scenarios and handling

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 15:36:23 +08:00
Misaka_Company
867b1979af refactor: improve BOM library matching logic with column-name-based lookup
All checks were successful
NTFY Notification / notify (push) Successful in 3s
- Add BOM library column name constants (名称, 编码, 数量, etc.)
- Add GetBOMConditionFields() and IsConditionField() utility functions
- Refactor ExtractMaterialInfo to use column names instead of hardcoded positions
- Refactor ExtractSingleSubComponent to use column names for 接头/弹性元件
- Refactor ExtractComponentInfo to use column names
- Improve MatchAllMaterialTypes to iterate all worksheets dynamically
- Add debug logging for troubleshooting

This fix resolves issues where worksheets with non-standard column counts
(like 表壳, 罩壳) could not extract material information properly.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 13:59:48 +08:00
Misaka_Company
c204a8878e docs: add BOM extraction requirements and minor code fixes
All checks were successful
NTFY Notification / notify (push) Successful in 2s
- Add BOM auto-extraction system requirements specification
- Minor property name fixes in M05_PreProcessor (.Pattern -> .pattern)
- Fix .Row property references to .row for consistency

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 13:03:56 +08:00
Misaka_Company
093a2d0a3b feat: implement BOM auto-extraction system
All checks were successful
NTFY Notification / notify (push) Successful in 11s
Add complete BOM auto-extraction system with the following modules:

- M06_ModelParser: Parse product model strings to extract parameters
  (azxs, bkxs, gclj, jycz, lcfw, fjgn)
  - Extracts header part from full model (ignores dial/attachment parts)
  - Splits process connection and material code (G123 -> G12, 3)
  - Supports multiple additional features with comma/dot separators

- M07_BOMMatcher: Match materials in BOM library
  - Exact match, wildcard (empty cell), negative match (!=)
  - Special fjgn contains matching logic
  - Array-based performance optimization for bulk operations

- M08_ComponentProcessor: Handle component material special logic
  - Component inventory check (interface reserved)
  - Sub-component extraction (joint + elastic element)
  - Combination validation rules (1 component OR 1 joint + 1 element)

- M09_BOMExtractor: Main extraction orchestrator
  - Reads input models from worksheet
  - Processes each model and matches all material types
  - Outputs to "BOM提取结果" worksheet
  - Error reporting and non-blocking design

- M06B_TestRunner: Comprehensive unit tests
  - 8 test cases for model parsing
  - 5 test cases for BOM matching
  - 5 test cases for component processing

- M04_Config: Add BOM extraction constants
  - BOM library filename and configuration
  - Input/output column definitions
  - Output column enumeration

- M01_Main: Add RunBOMExtraction entry point

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-12 13:02:14 +08:00
Misaka_Company
c6c31f81c8 refactor: rename VBA directory to VBA_BOMConverter
All checks were successful
NTFY Notification / notify (push) Successful in 20s
Rename VBA/ directory to VBA_BOMConverter/ for better clarity.
This change reflects the module's purpose as the BOM converter component.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-11 10:11:40 +08:00