You are working on the existing Kifi application. Use the senior architect, Flutter UI/UX, Spring Boot/R2DBC, PostgreSQL/DBA, accounting/finance, AI and Indian jewellery-domain rules defined in the active skill. Keep responses short and token-efficient. After each logical checkpoint, report: ```text Progress: XX% ``` Do not repeat requirements already understood. ## Objective When account setup is completed with: ```text Account Type = BUSINESS Nature of Business = JEWELLERY ``` the application must operate in **Jewellery Business Mode**. This mode must provide a robust jewellery retail/inventory/accounting system suitable for Indian jewellery businesses. This specification is directional, not exhaustive. Do not blindly implement only the fields listed here. Use your jewellery, accounting, GST, inventory and ERP expertise to identify missing requirements, correct flawed assumptions and build the smallest robust production-grade architecture. Before changing anything: 1. Inspect existing jewellery/inventory modules. 2. Inspect current category/product/purchase/customer/invoice flows. 3. Inspect existing double-entry accounting implementation. 4. Inspect current ledger/chart-of-accounts design. 5. Inspect daily metal-price synchronization. 6. Inspect barcode/SKU/EAN logic. 7. Inspect existing settings/configuration. 8. Inspect reports and dashboard statistics. 9. Reuse existing architecture where sound. 10. Refactor flawed areas instead of creating duplicate systems. --- # 1. Jewellery Business Mode When: ```text BUSINESS + JEWELLERY ``` is selected during setup: * Persist this business nature in backend. * Load Jewellery-specific navigation/modules after login. * Do not rely only on Flutter state. * Backend remains source of truth. Jewellery mode should expose relevant modules such as: ```text Dashboard Inventory Categories Products Purchases Vendors Customers Sales / Invoices Reports Configuration ``` Adjust based on existing architecture. --- # 2. Category Hierarchy Support hierarchical jewellery categories up to 3 nested levels. Example: ```text Gold Jewellery ↓ Rings ↓ Ladies Rings ``` or: ```text Diamond Jewellery ↓ Necklace ↓ Bridal Necklace ``` Each category should support: * Name * Parent category * Active/inactive * Sort order if useful * `hasChild` * Default HSN code * Default GST rate * Calculation unit/type * Default rate-calculation behaviour * Other domain-relevant configuration ## Leaf Category Rule Configuration intended for actual saleable products should only be collected on the **leaf category**. If: ```text hasChild = true ``` do not require product-level defaults such as: * HSN * GST * calculation unit * auto-rate calculation * other leaf-only product rules Those should be configured at the last category level where products are actually created. Do not duplicate inherited configuration unnecessarily. Consider inheritance/fallback where appropriate. --- # 3. Calculation Unit Support jewellery-specific calculation modes. Examples: ```text Quantity × Gram Quantity × Piece Weight-based Piece-based Fixed ``` Do not hardcode only these values if the domain requires more. Design calculation units as controlled/configurable values. Examples of later use: ```text Gold jewellery → weight-based Loose items → piece-based Accessories → quantity-based ``` --- # 4. Rate Auto Calculation Leaf categories/products should support: ```text Auto Calculate Rate = ON/OFF ``` When enabled, selling value may be derived from: ```text Current metal rate × purity × applicable net/fine weight + making charges + stone/diamond value + certification/other charges ``` Do not overwrite original purchase cost. Current market rate and purchase cost are different concepts. Keep pricing rules configurable. --- # 5. Product / Inventory Master Refactor Inventory/Product Master so creating a product definition produces a: ```text product_id ``` Product master should contain attributes such as: * Product name * Category * Subcategory hierarchy * Photo * SKU * EAN where applicable * Barcode configuration * Metal/type * Default purity if appropriate * Default HSN * Default GST * Default making charges * Making-charge calculation type * Default certification charge * HUID required toggle * Rate auto-calculation toggle * Calculation unit * Active/inactive * Other useful jewellery attributes Making-charge calculation types must support at least: ```text PERCENTAGE FLAT PER_GRAM ``` Use stable backend enum values and user-friendly labels. Do not confuse: ```text Product Master ``` with: ```text Physical Inventory Item / Tag ``` A product represents the design/type. Purchases populate actual stock instances under that product. --- # 6. Inventory Item / Tag Level Each purchased physical jewellery item should create a unique inventory record when required. Track relevant attributes such as: ```text product_id tag/barcode SKU HUID purity gross weight net weight stone weight diamond weight fine weight making charges making charge type purchase cost metal cost stone cost certification cost tax branch/location vendor purchase reference status ``` Apply jewellery-domain rules. Do not store only aggregate quantity if uniquely identifiable pieces require tag-level traceability. Support statuses such as: ```text AVAILABLE RESERVED SOLD TRANSFERRED RETURNED REPAIR MELTED DAMAGED ``` as appropriate. --- # 7. Vendor Module Vendor form already exists. Inspect it first. Add only missing fields needed for: * Jewellery purchasing * GST * Payments * Accounts payable * Double-entry accounting * Vendor ledger * Purchase returns Potential information may include: ```text Business name Contact person Mobile Email Address State GSTIN PAN Payment terms Opening balance Credit limit Bank details if needed Ledger/account mapping ``` Do not add unnecessary fields. Sensitive identifiers must follow existing PII encryption/masking rules. Each vendor must be able to participate in accounting entries. --- # 8. Purchases Existing Purchases module must be inspected and refactored. A purchase should support: ## Header * Vendor * Vendor invoice number * Invoice date * Purchase date/business date if different * GST treatment * Place/state of supply where required * Discounts * Shipping/freight charges * Other charges * Tax * Round-off * Payment status * Payment mode if immediate * Credit purchase * Notes * Attachments if existing architecture supports them ## Purchase Items User selects: ```text Product ``` and adds one or more physical inventory items. For each item capture relevant values including: * Purity * Gross weight * Net weight * Stone weight where applicable * Fine weight if applicable * Quantity/pieces * Making charges * Making-charge calculation type * Certification charges * HSN * GST rate * HUID when required * Stone/diamond values where applicable * Rate * Discount where appropriate * Other jewellery-specific costing components Defaults may inherit from product/category but must remain editable where business rules allow. If: ```text HUID Required = true ``` HUID must be validated before the item can be finalized, unless a legitimate workflow requires temporary pending status. --- # 9. Multi-Product Purchase Invoice One vendor purchase invoice may contain multiple products. Flow: ```text Select Vendor ↓ Select Product A ↓ Add one/multiple inventory items ↓ Select Product B ↓ Add items ↓ ... ↓ Review ↓ Post Purchase ``` Do not require separate purchase invoices for each product. --- # 10. Immutable Purchase Cost The original purchase cost is critical. Never overwrite historical purchase cost because: * Metal rates change * Making charges change * Selling rate changes * Product defaults change Preserve immutable purchase-cost components needed for: ```text COGS Gross profit Net profit Margin analysis Stock valuation Audit ``` If corrections are required, use controlled edit/reversal/adjustment rules with audit history. --- # 11. Purchase Accounting Every posted purchase must generate correct accounting entries. Depending on GST/payment mode, conceptually: ```text Dr Inventory Asset Dr Input GST Dr Freight/Eligible Cost if applicable Cr Vendor Payable / Cash / Bank ``` Actual journal structure must follow the project's chart of accounts and accounting configuration. Do not hardcode accounting account IDs. Use configurable accounting mappings. Purchase posting must be transactionally consistent with inventory creation. If accounting fails: ```text Purchase + Inventory ``` must not remain partially posted. --- # 12. Inventory Asset Mapping Inventory is a Current Asset. Do not automatically create one GL ledger for every jewellery category. Prefer configurable mapping such as: ```text Category / Product Type ↓ Inventory Asset Account COGS Account Sales Account Purchase Return Account Sales Return Account ``` Allow multiple categories to map to the same inventory account. Example: ```text Gold Rings Gold Bangles Gold Chains ↓ Gold Jewellery Inventory ``` A business may optionally configure more granular ledgers later. Support sensible fallback mapping. --- # 13. Customer Module Customer form already exists. Inspect and extend only where necessary. Potential requirements: * Name * Mobile * Email * Address * State * GSTIN for B2B * PAN where required * Customer type * Credit limit * Opening balance * Customer ledger * Notes Support: * Cash sales * Credit sales * Customer receivables * Payments * Sales returns * Old-gold exchange if implemented Maintain a queryable customer ledger. --- # 14. Sales / Invoice Refactor Existing invoice logic must be inspected and refactored around the new inventory model. Invoice should allow: ```text Select Customer ↓ Scan/Search Inventory ↓ Add Items ↓ Calculate Current Selling Value ↓ Discount / Charges ↓ GST ↓ Payment ↓ Post Invoice ``` Item lookup should support where applicable: * Barcode * SKU * EAN * Tag * HUID * Product search A sold unique inventory item must transition from: ```text AVAILABLE → SOLD ``` within the same transaction as invoice/accounting posting. Prevent double selling through backend concurrency controls. --- # 15. Sales Price Calculation Current selling value may be calculated using the latest applicable rate. Do not modify the item's historical purchase cost. Conceptually: ```text Current Selling Value = Current Metal Value + Making Charges + Stone/Diamond Value + Certification/Other Charges - Discount + GST ``` Apply correct purity/weight logic. Support manual override where business rules permit, with audit if necessary. --- # 16. Sales Accounting Posting an invoice generally produces two accounting effects. Revenue: ```text Dr Customer / Cash / Bank Cr Sales Revenue Cr Output GST ``` COGS: ```text Dr Cost of Goods Sold Cr Inventory Asset ``` Use actual mapped accounts. Ensure: ```text Total Debit = Total Credit ``` for every posted journal. Do not calculate COGS using today's metal rate. Use appropriate historical inventory cost/valuation logic. --- # 17. Gross Profit and Net Profit Preserve data required to calculate: ```text Gross Profit = Sales Revenue - Cost of Goods Sold ``` and: ```text Net Profit = Gross Profit + Other Income - Operating Expenses - Other Expenses ``` Do not calculate profit simply as: ```text Invoice Total - Purchase Invoice Total ``` because taxes, discounts, inventory cost allocation, freight, returns and expenses may affect the result. Apply proper accounting principles. --- # 18. Daily Price Sync Daily price synchronization already exists. Inspect it. Refactor so new market rates are stored as history. Never overwrite historical pricing. Conceptual structure: ```text metal_rate_history metal purity/basis rate effective_at source created_at ``` Latest applicable rate should be used for real-time valuation/selling calculations. Inventory's original cost must remain unchanged. --- # 19. Inventory Valuation Clearly distinguish: ```text Historical Cost Value Current Market/Estimated Value Selling Value ``` These must not overwrite one another. Dashboard and reports must state which valuation is being shown. For accounting balance sheet/current assets, use the appropriate accounting valuation method configured by the system/business. Do not silently use live gold price as the accounting book value. --- # 20. Barcode / SKU / EAN Existing barcode scan, SKU and EAN logic already exists. Inspect before modifying. Adapt to the new model: ```text Product Master ↓ Physical Inventory Item / Tag ``` Determine whether barcode belongs to: ```text Product or Individual Inventory Item ``` based on use case. For unique jewellery, tag/barcode will commonly identify the physical inventory item. Preserve existing functionality where compatible. --- # 21. Configuration Module Move relevant business configuration currently located in: ```text User Profile ``` or scattered elsewhere into the dedicated: ```text Configuration ``` navigation destination. Potential configuration groups: ```text Business Jewellery Tax/GST Pricing Inventory Accounting Invoice Numbering Barcode Metal Rates Making Charges Reports ``` Do not move identity/profile fields into Configuration. Profile and Configuration remain separate. --- # 22. Chart of Accounts / Ledgers Create or correct the required accounting structure so every transaction is queryable. Do not call accounting accounts "wallets" internally if they are actually GL accounts. Use proper concepts: ```text Chart of Accounts Ledger Accounts Journal Entries Journal Lines Sub-ledgers ``` If the existing system uses the term Wallet for a valid payment account abstraction, preserve it only where appropriate. At minimum jewellery businesses may require accounts such as: ```text ASSETS Current Assets Cash Bank Accounts Receivable Inventory LIABILITIES Accounts Payable GST Payable INCOME Jewellery Sales Other Income EXPENSES Cost of Goods Sold Making/Labour Expenses Freight Operating Expenses ``` Do not hardcode this exact chart if an existing configurable COA exists. --- # 23. Sub-Ledgers Vendor and customer transactions should remain individually queryable. Support: ```text Vendor Ledger Customer Ledger Inventory Ledger Cash Ledger Bank Ledger GST Ledger ``` without creating unnecessary GL accounts for every entity if a sub-ledger architecture is more appropriate. The user must be able to query transaction history at any time. --- # 24. Double-Entry Accounting Audit Inspect the current accounting implementation for flaws. Validate: * Debit = Credit * No orphan journal lines * Proper transaction references * Purchase posting * Sales posting * Payments * Vendor payable * Customer receivable * Purchase returns * Sales returns * Discounts * Freight * GST * Round-off * Inventory/COGS * Cancellation/reversal Fix incorrect architecture where necessary. Do not silently patch symptoms. --- # 25. Reversal Instead of Delete Posted financial/inventory transactions should generally not be destructively deleted. Use: ```text Cancel Reverse Return Adjustment ``` with audit history. Examples: ```text Purchase → Purchase Return / Reversal Invoice → Sales Return / Cancellation Payment → Reversal Inventory → Adjustment Journal → Reversal ``` --- # 26. Reports Module In Business Mode, show a dedicated: ```text Reports ``` card/module. At minimum support or architect for: * GSTR-1 * GSTR-3B * Profit & Loss * Balance Sheet * Trial Balance * Current Assets * Inventory Valuation * Inventory Movement * Sales Report * Purchase Report * Customer Ledger * Vendor Ledger * GST Summary * Stock Ageing * Gross Profit * Product/category profitability Use correct term: ```text Profit & Loss ``` not "Profile and Loss". GST reports should derive from transaction data, not manually maintained totals. --- # 27. Monthly GST Reports Design transaction records so monthly GST reports can be generated accurately. Consider: * B2B * B2C * CGST * SGST * IGST * Taxable value * HSN * GST rate * Credit/debit notes * Returns Do not claim statutory filing compliance without validating current GST requirements. Build report architecture capable of adapting to regulatory changes. --- # 28. Dashboard Statistics For Jewellery Business Mode, the Stats section should include at least: ```text Total Sales Total Asset / Inventory Value ``` Existing dashboard filters must apply consistently. For example: ```text Today This Week This Month This Financial Year Custom Range Branch ``` where supported. Clearly distinguish: ```text Book Inventory Value Current Estimated/Market Value ``` Do not label current gold-price valuation as accounting assets unless that is the configured accounting basis. --- # 29. Jewellery Dashboard Consider useful jewellery business metrics such as: ```text Today's Sales Monthly Sales Inventory Cost Value Current Estimated Inventory Value Gross Profit Outstanding Receivables Outstanding Payables Gold Stock Weight Silver Stock Weight Low/Old Stock Recent Purchases Recent Sales ``` Do not overload the dashboard. Use strong information hierarchy and follow UI/UX skill rules. --- # 30. Inventory History Maintain complete inventory movement history. Examples: ```text PURCHASE SALE SALE_RETURN PURCHASE_RETURN TRANSFER RESERVATION RELEASE REPAIR MELTING ADJUSTMENT ``` Each movement should record enough information to answer: ```text What changed? Why? When? Who? Which transaction caused it? ``` --- # 31. Jewellery-Specific Domain Gaps The specification above is incomplete by design. Use domain expertise to evaluate whether architecture should support concepts such as: * Gross/net/fine weight * Purity * Stone weight * Diamond carat * Stone/diamond valuation * Hallmark/HUID * Old-gold exchange * Repairs * Memo/approval stock * Branch transfer * Tagging * Purchase returns * Sales returns * Stock ageing * Wastage * Labour/job work * Certification * Multiple payment modes * Advance payments * Credit sales * Rate locking * Manual rate override * Audit history Do not implement every advanced feature immediately. But ensure today's database/architecture does not block sensible future expansion. --- # 32. Security Protect sensitive data such as: * GST * PAN * Bank details * Customer identifiers * Vendor identifiers Follow existing PII encryption/masking rules. Do not log sensitive values. Invoice/legal documents may display values in plain form where required. --- # 33. Transactions and Concurrency Important operations must be atomic. Examples: ```text Purchase posting = Purchase + Inventory creation + GST + Vendor payable + Journal ``` and: ```text Sales posting = Invoice + Inventory status change + Customer/payment + GST + Revenue journal + COGS journal ``` If one critical component fails, do not leave partially posted records. Prevent two users from selling the same inventory tag simultaneously. --- # 34. Database Requirements Inspect schema first. Use proper: * Primary keys * Foreign keys * Unique constraints * Check constraints * Monetary NUMERIC types * Weight precision * Audit timestamps * Status enums/controlled values * Useful indexes Do not store money using floating-point types. Do not introduce unnecessary indexes. --- # 35. Migration Strategy This is an existing application. Preserve existing: * Inventory * Products * Purchases * Invoices * Customers * Vendors * Journals * Rates * Barcodes Create migration/backfill strategy where necessary. Do not drop/recreate business data simply to fit the new design. --- # 36. UI/UX Follow the active skill's mandatory Material 3 modern UI rules. Do not create generic CRUD screens. Jewellery workflows should be: * Fast * Searchable * Scanner-friendly * Keyboard-friendly * Responsive * High information density without clutter For purchase/invoice item entry, prioritize operational speed. --- # 37. Implementation Strategy Do NOT implement everything blindly in one uncontrolled pass. First produce a concise architecture assessment. Then execute in logical phases. Suggested phases: ```text Phase 1 Audit existing architecture/accounting Phase 2 Category + Product Master Phase 3 Inventory/Tag model Phase 4 Vendor + Purchase refactor Phase 5 Customer + Invoice/Sales refactor Phase 6 Double-entry accounting correction Phase 7 Metal-rate history/valuation Phase 8 Barcode/SKU/EAN integration Phase 9 Configuration migration Phase 10 Reports + Dashboard Phase 11 Migration/testing/security review ``` Adjust if project dependencies require another order. At every phase report: ```text Progress: XX% ``` --- # 38. Before Coding First return only a concise assessment containing: ```text 1. Existing architecture found 2. Major flaws/risks 3. Proposed target architecture 4. Tables/entities that likely need change 5. Accounting model 6. Jewellery inventory model 7. Implementation phases ``` Keep it short. Then proceed with implementation. Do not ask for confirmation unless a genuinely blocking business decision cannot be safely inferred. --- # 39. Final Quality Gate Before marking complete, verify: * Jewellery business mode works from account type * Category hierarchy works * Leaf-category configuration works * Product master is distinct from stock items * Purchases create inventory correctly * Original cost is preserved * Live rates do not overwrite cost * Sales consume exact inventory * COGS is correct * Debit = Credit * Customer/vendor ledgers work * GST data is reportable * Barcode/tag logic works * Settings moved appropriately * Dashboard filters work * Reports derive from source transactions * Existing users/data remain valid * Concurrency is safe * Audit trail exists * UI follows modern Material 3 standards Do not claim completion if important parts remain broken. ## Final Directive This is not merely an inventory feature. Build the foundation of a **production-grade jewellery ERP/accounting system for Indian jewellery shop owners**. Use domain expertise to correct our assumptions where needed. Prefer accounting correctness, inventory traceability and operational usability over quick CRUD implementation.