{
  "App": {
    "Version": "2057",
    "VersionText": "2.0.5.7",
    "UpdateType": "Recommended",
    "Migration": 1,
    "DownLink": "https://i-connect-pos.pages.dev/Updates/2.0.5.7.zip",
    "Changes": [
      "**Sales & Purchase Reports Performance Modernization (`frmSaleReports` & `frmPurchaseReports`)**:",
      "**Unified Database API Integration**: Replaced legacy data access (`readDataV2`, `readData`) with async unified database methods (`_db.GetDataAsync(..., isStoredProcedure: true)`).",
      "**DevExpress Animated Overlay Loading Spinner**: Integrated `SplashScreenManager.ShowOverlayForm(DGV)` to provide sleek, non-blocking visual feedback during asynchronous report fetching.",
      "**High-Performance On-Demand (Lazy) Detail Loading**: Master queries load only top-level invoice summaries upfront in ~50–150ms, while line items are loaded lazily on demand when expanding rows via `GRD_MAIN_MasterRowGetChildList` and cached in-memory (`_detailsCache`), eliminating memory and network overhead for multi-year queries.",
      "**Secure Invoice Deletion & Confirmation Dialog**: Upgraded delete actions to use `frmConfirmDialog.ShowConfirmation(..., ConfirmDialogType.Danger)` with upfront permission checks (`DeleteSale`, `DeletePurchase`), atomic transaction handling, and cross-form synchronization (`clsFillData.RefreshSalesRelatedForms()` and `clsFillData.RefreshPurchaseRelatedForms()`).",
      "**Clean Code & Professional Method Naming**: Standardized methods (`LoadUsers`, `LoadProductsLookup`, `LoadSalesReportAsync`, `LoadPurchaseReportAsync`, `OpenEditInvoice`, `PrintSelectedInvoice`, `DeleteSelectedInvoiceAsync`) with backward-compatible bridges (`FillSaleReportClass`, `FillPurchaseReportClass`).",
      "**Database Performance & Optimization Migration (`Migration_022_2026-09-23.sql`)**:",
      "**High-Performance Covering Indexes**: Added non-clustered covering indexes on `Sale(Sale_Date)`, `Sale_Details(Order_ID, Prod_ID)`, `Buy(Buy_Date, Sup_ID)`, and `Buy_Details(BuyOrder_ID, Prod_ID)` to convert table scans into instant index seeks.",
      "**SARGable Stored Procedures (`sp_GetSalesReport` & `sp_GetPurchaseReport`)**:",
      "Normalized `@DateFrom` and `@DateTo` parameters to `yyyy/MM/dd` (`style 111`) at procedure entry.",
      "SARGable direct index range filtering `(Sale_Date >= @DateFrom AND Sale_Date <= @DateTo)` and `(Buy_Date >= @DateFrom AND Buy_Date <= @DateTo)`.",
      "Single-order detail retrieval support via `@OrderID INT = NULL` in Mode 2 (~1ms execution).",
      "Explicit `CAST(... AS DECIMAL(18, 2))` on all divided, discounted, and calculated currency/quantity columns to eliminate .NET SqlClient `Conversion overflows`.",
      "**Global Date Format Normalizer (Section 2)**:",
      "Standardized legacy date strings to unified `yyyy/MM/dd` (`style 111`) across operational tables (`Sale`, `Sale_Details`, `Sale_Profits`, `Buy`, `Buy_Details`, `Buy_Order`, `Returns`, `Returns_Details`, `SafeMoney_Insert`, `SafeMoney_Cashout`, `Safe_Transfir`, `Customers_Paid`, `Suppliers_Paid`, `Expenses`, `Sanad_Kabd`, `Sanad_Sarf`).",
      "**Invoice Payment & Change Dialog Layout Overhaul (\frmInvoicePayment)**: Re-architected form layout into docked header, body, and bottom action panels with responsive button alignment. Completely resolved clipped / invisible action buttons (\btnConfirm, \btnCancel) across non-standard Windows DPI scaling (125%, 150%) and high-resolution displays."
    ]
  },
  "OldVersions": [
    {
      "Version": "2056",
      "VersionText": "2.0.5.6",
      "UpdateType": "Recommended",
      "Migration": 1,
      "DownLink": "https://i-connect-pos.pages.dev/Updates/2.0.5.6.zip",
      "Changes": [
        "**Sales Invoices & Master Price Update Synchronization (`frmInvoiceSale`)**:",
        "**Automatic Post-Save Catalog Reload**: Integrated `LoadProducts()` and `LoadCustomers(filterOutCash: false)` into invoice completion and reset logic, ensuring newly modified prices and customer accounts are immediately available on subsequent invoices.",
        "**Product Master Price Update Checkbox (`chkPriceChange`)**: Renamed checkbox from `chkNoPriceChange` to `chkPriceChange` with Arabic caption `🔒 تغيير الأسعار عند حفظ الفاتورة`. Checking it passes `@AllowPriceUpdate = 1` to update database prices for products and sub-units; unchecking keeps master prices unchanged.",
        "**Auditory Feedback Standardized**: Quantity increments / duplicate barcode scans trigger `SoundHelper.BeepType.Increase` 🎵, new items trigger `SoundHelper.BeepType.Normal`, errors trigger `SoundHelper.BeepType.Error`, and invoice saving triggers `SoundHelper.BeepType.SaveInvoice`.",
        "**Out-of-Stock Visual Styling**: Added `RowCellStyle` in `slkProduct` popup view to highlight items with `Prod_Qty <= 0` in bold gold text on a dark background.",
        "**Online Sales (`SaleTypeID = 4`) Subsystem & Receipt Vouchers (`frmCustomerTrans`)**:",
        "**Customer Transactions Context Menu**: Updated \"سند قبض\" menu item visibility in `frmCustomerTrans` to support all sales invoice types including Online Sales (`فاتورة مبيعات اونلاين`) whenever an invoice has an outstanding credit balance.",
        "**Comprehensive Database Migration ([`Migration_021_2026-09-20.sql`](file:///c:/00%20-%20I-Connect%20POS%20CODE%20VS2019/IConnectPOSV1.0/IConnectPOSV1.0/TEMP/Migration%202.0.5.6/sql/Migration_021_2026-09-20.sql))**:",
        "`dbo.sp_InsertSaleOrder`: Implemented `@AllowPriceUpdate = 1` logic to update `Products.Sale_Price`, `Products.SaleGomla_Price`, `Products.Sale_PriceByTax`, `Product_Unit.UnitSale_Price`, `Product_Unit.TotalSale_Price`, store-level `Product_Qty`, and audit tracking in `PriceChangesLog`.",
        "`dbo.GetCustomerOrdersProc`: Added `WHEN 4 THEN N'مبيعات اونلاين'` mapping for receipt voucher lookup.",
        "`dbo.vw_ProfitAndReturnSummary`: Added `WHEN 4 THEN N'فاتورة مبيعات اونلاين'` mapping.",
        "`dbo.sp_GetDailySummaryReport` & `dbo.sp_GetDailyTransactionsReport`: Added active classification and reporting for Online Sales.",
        "`dbo.sp_ManageUnitType`: Added full CRUD stored procedure with product and ledger link protection for global unit types.",
        "`dbo.sp_GetProductUnits` & `dbo.sp_ManageProductUnit`: Added unified stored procedures for managing product-specific units with alias compatibility, automatic price calculations, and deletion safety.",
        "**Modernized Product Units Management Subsystem (`Forms\\Products\\frmProductUnits.cs`)**:",
        "**Modern DevExpress UI & UX**: Re-engineered the product unit management modal with live calculation of unit sale and wholesale prices based on main unit quantities, integrated beep sound notifications, and grid view controls.",
        "**Single-Thread Modal Refresh**: Eliminated duplicate grid row population race conditions upon closing modal dialogs.",
        "**Safe CRUD Lifecycle**: Added atomic add, edit, and delete operations backed by `sp_ManageProductUnit` with database-level validation.",
        "**Master Products Form Overhaul (`Forms\\Products\\frmProducts.cs`)**:",
        "**Isolated Product Units Filtering**: Populates `cbxMainUnit`, `cbxBuyUnits`, and `cbxSaleUnits` exclusively with units configured for the active product.",
        "**Automatic Fallback Selection**: If a unit is deleted, unit selectors automatically fall back to the main unit or first available unit, preventing empty or locked combobox states.",
        "**Single-Unit Live Synchronization**: When a product has only 1 unit, changing `cbxMainUnit` dynamically updates `cbxBuyUnits` and `cbxSaleUnits`.",
        "**Race Condition Resolution**: Structured `PopulateUnitsGridAsync` and `PopulateStoreGridAsync` to clear rows immediately before appending items, completely resolving duplicate grid rows.",
        "**Purchase Invoice Barcode Scanner Fix (`frmInvoicePurchase`)**:",
        "Restricted barcode scanning search query in `ProcessBarcodeAsync` to strictly match `Prod_Barcode` without falling back to `Prod_Ref`."
      ]
    },
    {
      "Version": "2055",
      "VersionText": "2.0.5.5",
      "UpdateType": "Recommended",
      "Migration": 1,
      "DownLink": "https://i-connect-pos.pages.dev/Updates/2.0.5.5.zip",
      "Changes": [
        "**Enterprise Redesign of HR & Employee Management Subsystem (Phase 6)**:",
        "**Unified Enterprise Database Schema & Ledger Architecture**:",
        "Replaced 6 fragmented legacy tables (`Employee`, `Employee_Solfa`, `Employee_BorrowItems`, `Employee_SalaryCashout`, `Employee_deductions`, `Employee_Money_Deductions`) with a unified, professional 6-table enterprise schema:",
        "`dbo.Employees`: Comprehensive employee profile master (National ID, Phone, Job Title, Basic Salary, Hire Date, Status).",
        "`dbo.Employee_Advances`: Cash advance disbursements with safe cashout tracking and settlement lifecycle flags (`Is_Settled`, `Settled_Date`, `Settled_Payroll_ID`).",
        "`dbo.Employee_Purchases` & `dbo.Employee_Purchase_Details`: Multi-item store merchandise purchases on credit with multi-unit conversions and atomic stock sync via `sp_AdjustProductStock`.",
        "`dbo.Employee_Payroll` & `dbo.Employee_Payroll_Lines`: Monthly payroll settlements with itemized deduction lines.",
        "`dbo.Employee_Adjustments`: Unified bonuses, allowances, penalties, and deductions.",
        "`dbo.Employee_Ledger`: Centralized chronological financial ledger with debit/credit running balances.",
        "Automated historical data migration and all stored procedures consolidated into [`Migration_020_2026-09-17.sql`](file:///c:/00%20-%20I-Connect%20POS%20CODE%20VS2019/IConnectPOSV1.0/IConnectPOSV1.0/TEMP/Migration%202.0.5.5/sql/Migration_020_2026-09-17.sql).",
        "**Employee Profiles & Directory Hub (`frmEmployeeManagement`)**:",
        "Comprehensive employee directory with full CRUD lifecycle (National ID, Phone, Job Title, Basic Salary, Hire Date, Status).",
        "Real-time balance tracking displaying basic salary, un-settled cash advances, un-settled store purchases, and total outstanding employee debt.",
        "Transactional delete protection preventing removal of employees with financial records or stock borrowing history.",
        "**Cash Advance Vouchers (`frmEmployeeAdvances`)**:",
        "Cash advance voucher issuance with real-time safe balance validation.",
        "Safe cash-out integration with Arabic audit notes, `Employee_Ledger` sync, and voucher creation via `sp_RecordEmployeeAdvance`.",
        "Live settlement badge in grid (`مسواة بالراتب` vs `غير مسواة (معلقة)`).",
        "Standardized confirmation prompt via `frmConfirmDialog`.",
        "**Store Merchandise Purchases on Credit (`frmEmployeePurchases`)**:",
        "Modern credit purchase voucher with `SearchLookUpEdit` product selector, fast barcode scanning, multi-unit conversions, line discounts, and live totals.",
        "Atomic database execution via Table-Valued Parameter (`dbo.EmployeePurchaseDetailType`), `dbo.sp_RecordEmployeePurchase`, and `Employee_Ledger` sync.",
        "Integrated with `sp_AdjustProductStock` for dual-table inventory reduction (`EMPLOYEE_PURCHASE` audit event) without 0-qty row deletions.",
        "**Modernized Dual-Card Salary Settlement & Cashout Dashboard (`frmEmployeeSalarySettlement`)**:",
        "Replaced stacked panels with a sleek **Dual-Card Dashboard Header**:",
        "*Right Card (`grpEmployeeDetails`)*: Employee selector, payroll month & year, safe selector, live safe balance badge, payout date, and visual duplicate payout warning banner (`lblAlreadyPaid`).",
        "*Left Card (`grpFinancials`)*: Basic salary, additions/bonus in green, deductions/penalties in red, individual deduction checkboxes with auto-populated pending balances, notes, and a prominent emerald-green Net Salary callout (`txtNetSalary`).",
        "Automated settlement: Automatically transitions unsettled advances and store purchases to `Is_Settled = 1` and creates itemized `Employee_Payroll_Lines`.",
        "Overrode `ProcessCmdKey` for global keyboard shortcut capture (**F5** to process and approve salary, **Esc** to close/clear) regardless of inner control focus.",
        "**Unified 4-Tab HR Analytics & Archive Hub (`frmEmployeeReports`)**:",
        "Rebuilt designer with complete DevExpress controls, toolbars, and date/employee filters across all 4 tabs: 1. *Account Statement*: Full chronological ledger from `dbo.sp_GetEmployeeAccountStatement` with running debt/credit balance. 2. *Cash Advances Archive*: Historical log of all cash advances with settlement status filters (`All`, `Pending`, `Settled`). 3. *Store Purchases Archive*: Historical merchandise credit purchase vouchers. 4. *Payroll & Settlements Archive*: Historical salary payout logs and deductions breakdown.",
        "Integrated one-click Excel export across all 4 tabs.",
        "Asynchronous query execution (`async Task`) and lazy tab loading on tab switch.",
        "**HR Menu Ribbon Integration**:",
        "Updated `frmMain.cs` to launch the 5 modernized `Forms.Employee.*` modules with user permission checks.",
        "**Store Management, Transfers & Damaged Stock Modernization (Phase 3 & Phase 7)**:",
        "**Modernized Store Management Hub (`frmStoreManagement`)**:",
        "Complete asynchronous CRUD lifecycle for warehouses/stores with auto-generated Store ID.",
        "Integrated real-time store valuation matrix grid displaying total SKU count, total on-hand stock quantity, total wholesale valuation, and total retail valuation for each store.",
        "Added database-level delete protection preventing store removal if items have non-zero inventory balances.",
        "Initialized zero-balance `Product_Qty` matrix on store creation to guarantee database consistency.",
        "**Multi-Item Store Transfer Voucher (`frmStoreTransfer`)**:",
        "High-performance multi-item transfer voucher with barcode scanner integration, search lookups, and multi-unit selector with dynamic price auto-filling.",
        "Real-time source store stock availability checks preventing transfers exceeding available quantity.",
        "Atomic database execution via Table-Valued Parameter (`dbo.StoreTransferDetailType`) and `dbo.sp_TransferProductStore`.",
        "Zero-deletion policy: Source store quantity decrements without row deletion; destination store quantity increments. Dual `TRANSFER_OUT` and `TRANSFER_IN` audit records logged to `Products_Qty_History`.",
        "**Damaged Goods Write-Off Module (`frmStoreDamaged`)**:",
        "Multi-item write-off voucher with barcode scanning, multi-unit conversions, loss reason tracking, and real-time loss valuation calculation.",
        "Atomic database execution via `dbo.DamagedProductDetailType` TVP and `dbo.sp_RecordDamagedProduct`.",
        "Synchronized dual-table deduction (`Product_Qty.Qty` and global `Products.Prod_Qty`) with `DAMAGED` audit logging in `Products_Qty_History`.",
        "**Unified Store Analytics Hub (`frmStoreReports`)**:",
        "4-tab DevExpress analytics dashboard: 1. *Stock Movement Audit Trail*: Date-filtered log with document filtering and visual indicators based on `dbo.vw_Products_Qty_History`. 2. *Store Inventory & Valuation*: Live warehouse breakdown by SKU, category, stock balances, and financial valuation. 3. *Store Transfers Log*: Comprehensive transfer voucher archive. 4. *Damaged Goods Log*: Historical damage write-off archive with financial loss totals.",
        "Integrated one-click Excel export for all analytics tabs.",
        "**Menu Navigation & Integration**:",
        "Wired all Ribbon menu buttons in `frmMain.cs` to launch the modernized Store forms, removing previous maintenance placeholders.",
        "**Centralized Inventory Audit & Stock Movement Trail (`Products_Qty_History` & `sp_LogProductQtyHistory`)**:",
        "Created `[dbo].[Products_Qty_History]` table to capture an immutable audit log of every stock alteration across all system workflows, tracking `Prod_ID`, `Store_ID`, `Old_Store_Qty`, `New_Store_Qty`, `Diff_Qty`, `Old_Master_Qty`, `New_Master_Qty`, `Doc_Type`, `Doc_ID`, `User_Name`, `Change_Date`, and `Notes`.",
        "Added indexes (`IX_Products_Qty_History_Prod_Store`, `IX_Products_Qty_History_Doc`, `IX_Products_Qty_History_Date`) for fast real-time auditing and stock ledger inquiries.",
        "Implemented `[dbo].[sp_LogProductQtyHistory]` stored procedure to streamline audit entry recording.",
        "**Atomic Stock Adjustment Engine (`sp_AdjustProductStock`)**:",
        "Implemented `[dbo].[sp_AdjustProductStock]` stored procedure for transactional stock increments and decrements across any store or base unit.",
        "Automatically handles multi-unit conversion dynamically via `dbo.fn_GetProdSmallUnitQty(@Prod_ID, @Unit_Name, @Qty)`.",
        "Implements concurrency locking (`UPDLOCK, ROWLOCK`) to eliminate race conditions.",
        "Simultaneously synchronizes `Products.Prod_Qty` and `Product_Qty.Qty`, inserting store-level rows on demand rather than deleting zero-balance records.",
        "Automatically records every adjustment into `Products_Qty_History`.",
        "**Sales & Purchase Invoices Real-Time Stock History Integration**:",
        "**Sales Invoices & POS (`sp_InsertSaleOrder` & `sp_DeleteSaleOrder`)**:",
        "Added dedicated `cbxStores` (`SearchLookUpEdit`) store selection control to `frmPOS` header bar, removing hardcoded store IDs and enabling dynamic store routing for POS terminal transactions.",
        "Synchronized batch stock deductions with `Products_Qty_History` (`Doc_Type = 'SALE'`).",
        "Synchronized order cancellation and edit reversals with `Products_Qty_History` (`Doc_Type = 'DELETE_SALE'`).",
        "Fully active across modern sales (`frmInvoiceSale`), classic sales (`frmINV_Sale`), and POS transactions (`frmPOS`).",
        "**Purchase Invoices (`sp_InsertPurchaseOrder` & `sp_DeletePurchaseOrder`)**:",
        "Synchronized purchase stock additions with `Products_Qty_History` (`Doc_Type = 'PURCHASE'`).",
        "Fixed store-level `Product_Qty` deduction synchronization upon purchase order deletion/reversal and logged to `Products_Qty_History` (`Doc_Type = 'DELETE_PURCHASE'`).",
        "Fully active across modern purchases (`frmInvoicePurchase`) and classic purchases (`frmINV_Purchase`).",
        "**Returns Modules Modernization (`frmINV_ReturnSale` & `frmINV_ReturnPurchase`)**:",
        "Replaced legacy multi-step inline SQL statements with atomic, transactional calls to `sp_AdjustProductStock`.",
        "Integrated full history auditing for return sales (`RETURN_SALE`), return purchases (`RETURN_PURCHASE`), and return modifications (`REVERT_RETURN_SALE`, `REVERT_RETURN_PURCHASE`).",
        "**Quantity Fix & Stock Realignment Hub (`frmFixProductQty` & `frmFixProductQtyLog`)**:",
        "**Modernized DevExpress UI & KPI Metrics**: Redesigned layout with split-container workflow, product `SearchLookUpEdit`, `SpinEdit` quantity selectors, and 4 real-time KPI status cards (Total Audited Items, Zero-Stock SKUs, Negative Stock Discrepancies, and Actionable Records).",
        "**Unified Database Engine Migration**: Replaced legacy `excuteDataV2` / `readData` calls with high-performance synchronous and asynchronous unified database APIs (`GetDataAsync`, `ExecuteDataAsync`, `GetData`, `ExecuteData`).",
        "**Dual-Table Synchronization & History Auditing**: Synchronized atomic stock updates across `Products.Prod_Qty` and store-level `Product_Qty.Qty` with dual audit logging (`Fix_Product_Qty` + `Products_Qty_History` with `Doc_Type = 'Fix Qty'`).",
        "**Enterprise Confirmation Dialog**: Replaced basic message boxes with `frmConfirmDialog` for single, bulk, and negative stock realignment actions.",
        "**Bulk Quantity Correction Fix**: Resolved an issue where bulk fixes previously failed to assign the user-specified custom target quantity dynamically.",
        "**Centralized Stock Movement Audit Trail Viewer (`frmProductQtyHistory`)**:",
        "**Comprehensive Audit Dashboard**: Engineered dedicated DevExpress audit explorer for `Products_Qty_History` with `SearchLookUpEdit` product selector, warehouse filter, movement document type filter, and dynamic date ranges with quick presets.",
        "**KPI Metrics Header**: Real-time KPI cards displaying Total Movement Records, Total Stock Inflow (+), Total Stock Outflow (-), and Net Stock Change.",
        "**Visual Data Grid**: Formatted chronological movement log with color-coded quantity deltas (Emerald green for additions, Coral red for deductions), Arabic document badge mapping, Excel export, and print preview.",
        "**User Permissions Synchronization & Security (`Migration_020_2026-09-17.sql` & `frmUsers`)**:",
        "Added Section 8 to `Migration_020_2026-09-17.sql` to synchronize all 77 master system permissions across existing users and explicitly grant `Settings.AdminTools` and `Settings.FixQuantities` permissions to Admin (`User_ID = 101`).",
        "Aligned permission schema and seeding across `frmUsers.cs`, `frmPrepairDb.cs`, `frmLogin.cs`, `frmMain.cs`, and `frmMainMenu.cs`.",
        "**Sales Invoice Focus & Grid Numeric Auto-Selection (`frmInvoiceSale`)**:",
        "**Grid In-Place SpinEdit Editors**: Enhanced `gridViewItems_ShownEditor` and `Editor_Click` to bind `MouseUp`, `Click`, and `Enter` events to active in-place `SpinEdit` editors (`colQty`, `colPrice`, `colDiscount`), ensuring full text selection occurs automatically whether navigating via keyboard focus or mouse clicks.",
        "**Form-Wide Numeric Controls Hook**: Added `HookNumericUpDownEvents` and `SelectAllNumericText` to recursively traverse and attach automatic select-all behavior to all `NumericUpDown` and standalone `SpinEdit` controls (such as `spnVatPercent`, `spnGlobalDiscountValue`) upon focus/click, matching the workflow in `frmProducts`.",
        "**System-Wide Quantity Analyses & Modernization Roadmap**:",
        "Authored comprehensive `QTYAnalyses.md` cataloging every form, method, table, and stored procedure affecting inventory quantities across the application.",
        "Authored `Modernization Roadmap.md` detailing multi-phase modernization for inventory transactions, multi-store movements, and unified reporting.",
        "Added master vs store stock discrepancy diagnostic and sync options (A & B) to `Diagnostics.sql`.",
        "**Bulk Negative Stock Fix Target Quantity Assignment (`frmFixProductQty`)**:",
        "Fixed a logic bug where applying bulk fixes to negative stock items did not set the custom `desiredQty` specified in the target quantity editor.",
        "**Cash Safe Refund Duplication Loop Bug (`frmINV_ReturnSale` & `frmINV_ReturnPurchase`)**:",
        "Fixed a critical issue where `DeductMoneyFromSafe` (Return Sale) and `ReturnMoneytoSafe` (Return Purchase) were invoked inside the grid row loop, causing the full return invoice amount to be deducted/added repeatedly for each item in the return invoice.",
        "Moved safe ledger calls outside the loop to execute strictly once per invoice.",
        "**Defective Legacy Forms Controlled Deactivation**:",
        "Temporarily deactivated entry points for legacy/multi-store forms that did not synchronize master `Products.Prod_Qty` (`frmTransfirProductsStore`, `frmEditProducts`, `frmFailProductsStore`, `frmRealyGard`, `frmGardQuantity`, `frmGardValues`, `frmStore`, `frmEmployeeBorrowed`, `frmItemsFirstTermCasheir`, `frmItemsFirstTerm`, `frmItemsFirstTermEdit`, `frmImportFromExcell`, `frmImportFirstTirmExcell`), routing users to maintenance notifications pending phase-by-phase modernization.",
        "**Multi-Unit Price & Cost Dynamic Recalculation Bug (`frmINV_ReturnSale` & `frmINV_ReturnPurchase`)**:",
        "Fixed an issue where changing the product unit in the return grid failed to update unit prices or invoice totals for multi-unit products.",
        "Linked `frmINV_ReturnSale` to `clsFillData.GetPriceByUnit` (supporting retail and wholesale pricing) and `frmINV_ReturnPurchase` to `clsFillData.GetProductCostByUnit`.",
        "Enhanced `clsFillData.GetProductCostByUnit` and `GetProductCostByUnit_Trans` to accurately scale product cost across all multi-unit tiers using `(cost / buyQtyInMain) * targetQtyInMain`.",
        "Integrated real-time grid cell value recalculation, currency factor conversions, and automatic invoice total refresh (`UpdateTotal()`) upon unit changes.",
        "**Arabic Text & Notification Encoding**:",
        "Resolved character encoding inconsistencies (mojibake) in return forms and progress panels, ensuring clean UTF-8 rendering for all Arabic alerts and log entries."
      ]
    },
    {
      "Version": "2054",
      "VersionText": "2.0.5.4",
      "UpdateType": "Normal",
      "Migration": 1,
      "DownLink": "https://i-connect-pos.pages.dev/Updates/2.0.5.4.zip",
      "Changes": [
        "**Product Smallest Unit Price Synchronization (`sp_UpdateProduct` & `frmProducts`)**:",
        "Enhanced `sp_UpdateProduct` in `Migration_019_2026-09-16.sql` to automatically synchronize `UnitSale_Price` and `TotalSale_Price` in `Product_Unit` specifically for the single smallest / base unit (`ORDER BY ISNULL(QtyInMain, 1) ASC`) whenever the product price is edited in `frmProducts`.",
        "Ensured multi-unit pricing for larger packaging (cartons, boxes, dozens) remains strictly protected and managed via `frmProductUnits` without accidental price overwrites.",
        "**Smallest Unit Database Helper Functions (`fn_GetProdSmallUnitName` & `fn_GetProdSmallUnitID`)**:",
        "Added user-defined SQL scalar functions `dbo.fn_GetProdSmallUnitName` and `dbo.fn_GetProdSmallUnitID` to resolve a product's base unit dynamically based on minimum `QtyInMain`.",
        "**Multi-Unit Product Price Overwrite Isolation**:",
        "Fixed an issue where modifying product sale prices in `frmProducts` could overwrite multiple unit rows in `Product_Unit` if `cbxMainUnit` matched a higher unit ID."
      ]
    },
    {
      "Version": "2053",
      "VersionText": "2.0.5.3",
      "UpdateType": "Normal",
      "Migration": 1,
      "DownLink": "https://i-connect-pos.pages.dev/Updates/2.0.5.3.zip",
      "Changes": [
        "**Sales Invoice Form Defaults & Reset Workflow (`frmSaleInvoice`)**:",
        "**Auto-Reset Sale Type**: Updated `ResetFormForNewInvoice` to always reset `rgSaleType` to the default retail sale type (`مبيعات`, `EditValue = 1`) and synchronize `_currentSaleTypeId = 1` for every new invoice.",
        "**Dynamic Open Forms Refresh**: Integrated `clsFillData.RefreshSalesRelatedForms()` into `SaveAndPayAsync` upon both new invoice creation and invoice modifications, automatically refreshing data in open analytical forms such as `frmSaleReports` (`FillSaleReportClass()`) and `frmCustomerTrans` (`FillDgvCusTransactions()`).",
        "**Edit Mode Cash Conversion Payment Handling**: Fixed payment calculation when converting an existing credit/debt invoice to a cash invoice in edit mode (`tglIsCredit.IsOn == false`). Set `initialPaid` to `null` so `frmInvoicePayment` automatically initializes `spinPaid` to the full invoice total rather than retaining previous partial or zero payments.",
        "**Product Master Price Update Checkbox (`chkNoPriceChange`)**:",
        "Corrected the parameter mapping for `sp_InsertSaleOrder` so that checking `chkNoPriceChange` properly passes `@AllowPriceUpdate = 1` to update product master prices upon saving.",
        "Updated `ResetFormForNewInvoice` and `frmSaleInvoice_Load` to automatically reset `chkNoPriceChange.Checked` to `false` after saving and payment.",
        "**Sales Invoice Workflow & Ergonomic Enhancements (`frmSaleInvoice`)**:",
        "**Intelligent Stock-Aware Unit Fallback**: Enhanced product addition (`ValidateAndAddProductAsync` / `ResolveBestUnitForStockAsync`) to check available stock against the default unit (e.g. Box). If the warehouse balance is less than a full box (e.g. 8 pcs available when a box contains 10), it automatically falls back to adding the item in its smallest available unit (Piece / `قطعة`) with the corresponding piece price, preventing false out-of-stock blocks.",
        "**MDI-Compliant New Invoice Window (`btnNewInvoice` / `F2`)**: Refactored `btnNewInvoice` and shortcut `F2` to launch new sales invoices through `clsFillData.OpenMdiForm<frmSaleInvoice>(this.MdiParent, \"Sales\", \"Sale\")`, ensuring proper permission checks and integrating instances as tabs/windows inside the main MDI container.",
        "**Auto-Focus Add Button on Product Selection**: Configured `slkProduct.EditValueChanged` to automatically transfer focus to `btnAddProduct`, allowing instant addition to the invoice with a single **Enter** keypress without touching the mouse.",
        "**Dynamic Auto-Scroll on Grid Addition**: Integrated `gridViewItems.MakeRowVisible` whenever products are inserted or incremented, ensuring newly added items remain immediately visible across all screen sizes and resolutions without manual vertical scrolling.",
        "**Fast Barcode Auto-Focus on Grid Value Edit**: Bound `gridItems.ProcessGridKey` and `ActiveEditor.KeyDown` to commit changes and immediately return focus to `txtBarcode` (`SelectAll()`) upon pressing **Enter** in any grid cell (Quantity, Price, Discount, Unit), dramatically speeding up keyboard-only cashier workflows.",
        "**Credit Invoice Payment Dialog Enhancements (`frmInvoicePayment`)**:",
        "**Responsive Form Title for Credit Sales**: Dynamically adjust `lblFormTitle` text and dimensions to fit compact credit mode (`فاتورة مبيعات آجلة (ذمم)`), eliminating text clipping when the right panel is collapsed.",
        "**Live Remaining Debt Display**: Added `grpDebtRemaining` with dual-currency conversion (`lblDebtRemaining` & `lblDebtRemainingSub`) in the left section that updates dynamically in real-time as `spinPaid` changes, allowing cashiers and customers to clearly see remaining debt before confirming.",
        "**Database API Modernization (`frmSaleInvoice`)**:",
        "Eliminated all legacy `_db.readDataV2` calls and converted them to fast synchronous `_db.GetData` calls from the Unified Database API for instantaneous UI operations (stock verification, unit loading, currency resolution).",
        "**Product Unit Price Overwrite Bug Fix (`sp_UpdateProduct` & `frmProducts`)**:",
        "Resolved an issue where selecting or changing default purchase/sale units (`cbxBuyUnits` / `cbxSaleUnits`) and saving product edits overwritten custom unit sale prices in `Product_Unit` table.",
        "Updated `sp_UpdateProduct` in `Migration_018_2026-09-13.sql` to avoid updating `Product_Unit`, ensuring unit prices remain strictly isolated and managed via `frmProductUnits` (`sp_ManageProductUnit`).",
        "**Barcode Lookup Invalid Column Exception (`frmSaleInvoice`)**:",
        "Resolved `SqlException: Invalid column name 'Unit_Barcode'` in `ProcessBarcodeAsync` by cleaning the fallback query to strictly check against existing columns in the database schema when scanning unknown or unmatched barcodes.",
        "**Sales Invoice Order ID Duplicate Key Violation Fix (`frmSaleInvoice`)**:",
        "Resolved `PK_Sale` primary key duplicate violation exception when saving new invoices in `frmSaleInvoice`.",
        "Updated `SaveAndPayAsync` to re-fetch the latest available `SaleOrder_ID` right before saving in non-edit mode, preventing race conditions or stale order ID conflicts when multiple transactions or delays occur.",
        "**AdminTools Permission Reinstallation Migration (`Migration_017_Reinstall_UserPermissions.sql`)**:",
        "Added the `Settings.AdminTools` module permission definition to the migration script with default values set to disabled (`0`).",
        "Configured explicit granting of `Settings.AdminTools` exclusively to `User ID: 101` (`HasPermission = 1`), safeguarding advanced maintenance tools while granting full access to the primary system administrator."
      ]
    },
    {
      "Version": "2052",
      "VersionText": "2.0.5.2",
      "UpdateType": "Normal",
      "Migration": 1,
      "DownLink": "https://i-connect-pos.pages.dev/Updates/2.0.5.2.zip",
      "Changes": [
        "**Synchronous Database Methods (`Database.GetData` and `Database.ExecuteData`)**:",
        "Implemented fast synchronous `GetData` and `ExecuteData` APIs with transaction support in `Database.cs` to eliminate async loading delays and layout flicker when opening small dataset forms like `frmSaleInvoice`.",
        "Added support for passing custom `SqlParameter` objects (including `OUTPUT` parameters and `Structured` TVP parameters) into `GetData` and `ExecuteData`.",
        "**Preserve Paid Amount in Sales Invoice Payment**:",
        "Enhanced `frmInvoicePayment` to accept and preserve previously paid amounts (`initialPaidAmount`) during invoice editing instead of resetting paid values to zero or total amount.",
        "**Online Sales Type (SaleTypeID = 4)**:",
        "Added full support across the entire system for Online Sales (`مبيعات اونلاين`), integrating seamlessly with retail (`مبيعات تجزئة`), wholesale (`مبيعات جملة`), and no-profit (`مبيعات بدون ربح`) sales types.",
        "Implemented `clsFillData.GetSaleTypeName(int typeId)` to provide unified localized naming.",
        "Updated `vw_ProfitAndReturnSummary` and database migrations to classify and aggregate Online Sales transactions.",
        "Updated Customer Transactions screens (`frmCustomerTrans`) and DevExpress reports (`RPT_CUS_TRANS`, `RPT_CUS_TRANS_BD`) to render and filter Online Sales with proper badge styling.",
        "Added Online Sales radio button (`rb_Online`) in `frmINV_Sale` and full radio selection in `frmSaleInvoice`.",
        "**Modernized Sales Invoice (`frmSaleInvoice`)**:",
        "Implemented completely overhauled Sales Invoice form with customizable DevExpress layout, enhanced shortcuts, multi-currency display, and barcode scanning support.",
        "Built interactive confirmation dialog (`frmConfirmDialog`) for invoice actions and deletions.",
        "**Revamped Invoice Payment Dialog (`frmInvoicePayment`)**:",
        "Engineered advanced payment dialog with multi-currency calculations, dual currency conversion (Primary vs Secondary), quick cash amount shortcuts, and safe/bank routing.",
        "**Daily Transactions Summary Reports (A4 & 8CM Thermal Receipt)**:",
        "Added `sp_GetDailySummaryReport` stored procedure implementing accurate dual-track accounting: tracks both Invoice Volume / Debt Created (`TotalBilled`, `TotalDebt`) and Treasury Cash Movement (`TotalIn`, `TotalOut`, `NetCash`).",
        "Correctly aggregates partial and pure credit/debt sales from `Sale` & `Sale_Details` as well as supplier purchases from `Buy` & `Buy_Details`, preventing row multiplication and accurately reporting new credit liabilities vs collected cash drawer inflows.",
        "Developed `RPT_DailySummary_A4` with 4 high-level KPI cards (Cash In, Cash Out, Total Debt Created, Net Treasury Cash Flow), daily date groupings with 7-column breakdown (Type, Count, Billed, In, Out, Debt, Net Cash), and period grand totals.",
        "Developed `RPT_DailySummary_8CM` with continuous 80mm roll paper layout, RTL alignment, compact header, daily grouped aggregates, and grand totals for counter receipt printers.",
        "Updated `frmDailyTransactionsReport` UI to select report format: Daily Summary (A4), Daily Summary (8CM Receipt), or Detailed Ledger (A4).",
        "**Comprehensive Daily Transactions Report Module**:",
        "Created modern DevExpress filter dialog (`frmDailyTransactionsReport`) styled with `29LT Bukra` and `Arial` typography, taller inputs, custom gradients, and default filters (Today's date, All Safes, All Users).",
        "Developed full-featured DevExpress XtraReport (`RPT_DailyTransactions`) containing dynamic company branding, high-level KPI cards (Total Inflows, Total Outflows, Net Movement), and a detailed ledger table.",
        "Implemented `sp_GetDailyTransactionsReport` stored procedure providing unified daily ledger details with sale category classifications (Retail, Wholesale, No Profit, and Online) compatible with SQL Server 2014.",
        "**Enhanced Safe & Daily Transactions View (`vw_SafeTransactions`)**:",
        "Unified Cash In (`SafeMoney_Insert`), Cash Out (`SafeMoney_Cashout`), and Expenses (`Expenses`) into a single consolidated view.",
        "Added dedicated branch for `Expenses` table and excluded direct `مصروفات` entries from `SafeMoney_Cashout` to prevent ledger duplication.",
        "**Thread-Safe Order ID Generation (`sp_GetNextSaleOrderId`)**:",
        "Added stored procedure using `(UPDLOCK, HOLDLOCK)` to fetch the next sale invoice order ID reliably in multi-user concurrent POS environments.",
        "**Advanced Cash Drawer Configurations**: Implemented a local `TerminalConfigManager` with a new `frmPrinterAdvanced` UI to allow robust, per-PC cash drawer kick configurations (Epson, Star, Custom Bytes), bypassing standard .NET Settings for improved stability.",
        "**Multi-Currency & Bank/Safe Routing in Expenses**: Expanded the Expenses module to natively support multi-currency calculations and route deductions to either the Safe or Bank ledger.",
        "**Dashboard Statistics**: Introduced `sp_GetDashboardStatistics` for advanced sales, expenses, and growth analytics.",
        "**New Forms & Security**: Added a new Registration form powered by the `AppProtection` security class, and a new `StatisticsMenu` form utilizing DevExpress Charts.",
        "**Brand new Safe and Bank Management UI** (`frmSafeBankManagement`).",
        "Added dynamic fetching of the next available ID via `sp_SafeBank_GetNextId`.",
        "New Cash In, Cash Out, and Transfer screens for Safes and Banks.",
        "Implemented auto-fill logic for `txtActionName` using `SessionManager.UserName` and restricted `slkAccount` access based on `ChangeSafes` permissions.",
        "Centralized Safe and Bank Transactions Report (`frmSafeBankReports`).",
        "**Centralized Expenses Report**: Added a standalone DevExpress report (`RPT_Expemses`) with a dynamic title and multi-currency total calculations injected from the grid's custom summary drawer.",
        "**Product Transactions Summary**: Implemented a full-width custom drawer in `frmProductTransaction` to dynamically calculate Total In, Total Out, and Total Transactions based on base unit quantities using `fn_GetProdSmallUnitQty`.",
        "Added `vw_ProductTransactions` and `sp_ProductTransactions` to `Migration_016_2026-08-23.sql`.",
        "**Real-Time Data Refreshing**: Added `RefreshSalesRelatedForms()` to `clsFillData` to automatically broadcast data updates to open analytical forms (`frmSaleReports`, `frmCustomerTrans`) immediately upon saving an invoice.",
        "**Expense Management Modernization:**",
        "Revamped the existing \"Deserves\" module to \"Expenses\" for better clarity.",
        "Implemented new DevExpress RTL forms (`frmExpenseTypes`, `frmExpenses`, `frmExpenseReports`).",
        "Added robust Stored Procedures (`sp_ExpenseType_GetAll`, `sp_Expense_Insert`, etc.) for improved performance and separation of concerns.",
        "Implemented Safe Balance constraint checking (`sp_GetSafeBalance`) to prevent overdrawing accounts during expense entry.",
        "Upgraded `frmExpenses` to default load only current-year data for dramatically improved grid performance.",
        "Enforced a single `main` branch Git workflow and optimized repository footprint by updating `.gitignore` (ignoring TEMP, scratch, and setup folders).",
        "**Sales Invoice Edit Mode Enhancements (`frmSaleInvoice`)**:",
        "Converted initial form loading (`LoadCustomers`, `LoadStores`, `LoadCurrencies`, `LoadProducts`, `LoadInvoiceForEdit`) to synchronous execution, preventing right-dock sidebar delay and layout jumps.",
        "Improved credit status restoration in edit mode: dynamically checks debt balance (`Baqy > 0` or customer debt from `Sale_Details` / `Customers_Money`), accurately sets `tglIsCredit.IsOn`, and restores invoice due dates and currency factors.",
        "**Unified User Permissions Harmonization**:",
        "Aligned permission keys across `frmMain`, `frmLogin`, `frmPrepairDb`, `frmUsers`, and `frmUsersPermitions`.",
        "Updated Fix Quantity tools permission lookup in `frmMain.cs` from `\"FixQty\"` to canonical `\"FixQuantities\"` under the `\"Settings\"` table.",
        "Synchronized default Administrator (ID 101) seed permissions across `frmLogin.cs` and `frmPrepairDb.cs` to include all 14 permission groups and complete `UserManagement` permissions.",
        "**Unified Safe & Bank Ledger Architecture**: Merged legacy Bank accounts into the unified `SafeMoney` table (`AccountType`), completely removing redundant Bank tables and heavily streamlining stored procedures.",
        "Refactored core transaction stored procedures (`sp_InsertSaleOrder`, `sp_DeleteSaleOrder`, `sp_InsertPurchaseOrder`, `sp_DeletePurchaseOrder`) to route all financial impacts through the unified Safe ledger structure regardless of whether a Safe or a Bank is selected.",
        "Corrected database migration syntax for SQL Server 2014 compatibility by replacing all `DROP IF EXISTS` statements and `TRY_CAST` calls with backward-compatible object checks and `ISNUMERIC/CAST`.",
        "**POS & User Session Resolution**:",
        "Updated `frmPOS` (`InsertPOSOrderTVP`) and `frmMain` to consistently resolve `UserName` and `Safe_ID` from `SessionManager` and `clsFillData` across POS ticket operations.",
        "**Sale Return Parameterization**:",
        "Refactored `frmSaleReturn` to accept dynamic invoice parameters and automatically load target order details for faster return processing.",
        "**Unified User Permissions Architecture**: Replaced 13 fragmented, hard-coded permission tables with a single, highly optimized `UserPermissions` table.",
        "Formally renamed and standardized system-wide permission tags in SQL migrations and C# logic (e.g. `DeleteSaleReport` -> `DeleteSale`, `Backup_` -> `BackupDB`, `Settings` -> `GeneralSettings`).",
        "Consolidated overlapping `Reports` permissions (removed redundant `checkSaleReport`, `checkBuyReport`, etc., relying on the parent module's permissions).",
        "Restructured `frmUsersPermitions` code-behind to align with the new consolidated permission checkboxes.",
        "Engineered the database initialization flow to safely drop and recreate the `UserPermissions` table if missing, using `OldPermissionTables.sql` for admin seed data.",
        "**Database Architecture:**",
        "Introduced unified Database API wrappers (`GetDataAsync`, `ExecuteDataAsync`) in `Database.cs` to handle parameterized execution safely.",
        "Updated `frmProductTransaction` and other forms to use the unified `GetDataAsync` database API for improved performance and safety.",
        "Refactored legacy `frmMainMenu` database calls to exclusively use the modernized `GetDataAsync` API, cleanly separating query definitions.",
        "**C# Core Performance**:",
        "Migrated from slow, per-click database permission checks to a lightning-fast static memory cache loaded at login.",
        "Replaced over 140 legacy permission checks across all C# forms (`frmMain`, etc.) with a unified method.",
        "Re-architected `frmMainMenu` loading logic to be completely synchronous using `DashboardDataManager` global caching.",
        "Moved heavy dashboard data preloading to the background in `frmSplash`, drastically reducing wait time at the login screen for an instant transition.",
        "Migrated legacy SafeMoney and SafeTransactions schemas.",
        "Replaced hardcoded legacy layout loads with manual DevExpress XML appearance templating.",
        "Re-added and customized `CreateDxMenu` for stylized popup menus (bold, lime/black styling) in `frmCustomers`.",
        "Improved User Permissions logic in `frmUsers` to manually set default Admin permissions upon creation without querying `INFORMATION_SCHEMA`.",
        "Organized and relocated all Safe and Bank forms (e.g., `frmSafeTransactions`) into a dedicated `Forms/SafeAndBank` folder.",
        "**frmBackupRestoreProfessional Modernization**: Renamed and refactored to `frmBackupRestore`, modernized `LoadSettings()` to use the universal `GetDataAsync` API via `SecureConfig.LoadConnectionString()`, and enforced a standardized default network backup path (`D:\\I-Connect\\Backup`).",
        "Executed massive refactoring and cleanup of `frmMain.cs` and `frmMain.Designer.cs` code-behind, organizing hundreds of UI handlers into dedicated regions (`#region Tabs Buttons`) and fixing MSB3823 designer file issues.",
        "**Legacy Cleanup**: Cleared old, unused forms from the solution.",
        "**Redundant Tables Dropped**: `Bank_Balance`, `Bank_Transfir`, `BankMoney_Cashout`, `BankMoney_Insert`, and 13 legacy `Users_*_Perm` tables.",
        "Deleted the deprecated `UCInstructions` and `UCAbout` user controls and removed their references from the `frmMain` backstage view.",
        "Deleted deprecated permission checkboxes (like `checkNetSale`) and streamlined the permissions GUI.",
        "**Invoice Re-Save Primary Key Violation & Stored Procedure Execution (`sp_DeleteSaleOrder`)**:",
        "Resolved `sp_DeleteSaleOrder expects parameter '@Result', which was not supplied` error in `frmSaleInvoice.DeleteInvoiceFromDb` by supplying `@Result` as an `OUTPUT` parameter (`SqlParameter`).",
        "Fixed duplicate primary key error (`PK_Sale` on resave) caused by previous invoice deletion failures.",
        "**Select All Checkbox in User Permissions Screen (`frmUsersPermitions`)**:",
        "Upgraded `ToggleCheckboxesInGroup` to recursively traverse `XtraTabControl`, `XtraTabPage`, and `GroupBox` controls so that toggling \"Select All\" (`checkAll`) properly updates all checkboxes across all tabs.",
        "**Expenses Table Schema & Form Integration**:",
        "Added missing `UserName` column to `Expenses` table and updated `sp_Expense_Insert`, `sp_Expense_Update`, `sp_Expense_GetAll`, and `sp_Expense_GetByDate`.",
        "Normalized date formatting in `frmExpenses.cs` and `frmExpenseReports.cs` to consistent `yyyy/MM/dd` to match system-wide date standards and SQL range queries.",
        "**RPT_DailyTransactions Summary & Formatting Fixes**:",
        "Fixed missing ReportFooter totals by assigning dedicated `XRSummary` instances (`SummaryRunning.Report`) to all summary labels.",
        "Formatted detail table cells and summary cards to display `0.00` cleanly instead of blank/null values.",
        "Adjusted header and footer summary cards layout to guarantee proper alignment and visibility under Right-to-Left (RTL) mode.",
        "**Customer Transaction Reports**:",
        "Fixed customer transactions query and report definitions in `RPT_CUS_TRANS` and `RPT_CUS_TRANS_BD` to correctly account for all sale types including Online Sales.",
        "Stabilized database connections and eliminated inline SQL injections for Expense entries.",
        "Addressed various application bugs and database synchronization issues.",
        "Fixed legacy dashboard crash issue where 'Deserved' table was incorrectly queried after being renamed to 'Expenses'.",
        "Made the User Migration SQL script idempotent (checking both legacy and modern tables).",
        "Addressed missing Expense/Vouchers permissions in the default permissions migration logic.",
        "Fixed a missing `#endregion` directive in `frmUsersPermitions.cs`.",
        "Fixed the background image mirroring glitch in `frmMain` where the background flickered un-flipped by relocating `RotateFlip` to the constructor.",
        "Fixed severe Arabic text corruption issues by strictly enforcing Windows-1256 (CP1256) encoding across all script interactions.",
        "Resolved `FileLoadException` crashes related to missing `System.Resources.Extensions` and `WinFormAnimation` assembly references.",
        "Legacy Safe Forms (`frmSafesActionReport`, etc.) and legacy Safe Crystal Reports are now slated for deletion. See TEMP/Future_Deprecations.md for details."
      ]
    }
  ],
  "Updater": {
    "Version": "2.0.0.2",
    "VersionText": "2.0.0.2",
    "Description": "CheckUpdate application performance improvements, cloud updates endpoint configuration, and bug fixes.",
    "DownLink": "https://i-connect-pos.pages.dev/Updates/Updater2.0.0.2.zip"
  }
}