

--- BLOCK 0 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\task.md") ---
"- [/] 1. Modify `app_final.js` `btn-save-contact` to prevent creating sub-accounts.\n- [ ] 2. Update journal generators in `app_final.js` (`generateSalesJournal`, `generatePurchasesJournal`) to use control accounts.\n- [ ] 3. Update journal generators in `vouchers_returns.js` (`generateVoucherJournal`, `generateSalesReturnJournal`, `generatePurchasesReturnJournal`) to use control accounts.\n- [ ] 4. Inject Statement Modal into `index.html`.\n- [ ] 5. Inject Statement Logic into `app_final.js` (`openContactStatement`).\n- [ ] 6. Inject the \"كشف حساب\" button into the Contacts table in `app_final.js`.\n"

--- BLOCK 1 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\task.md") ---
"- [x] 1. Modify `app_final.js` `btn-save-contact` to prevent creating sub-accounts.\n- [x] 2. Update journal generators in `app_final.js` (`generateSalesJournal`, `generatePurchasesJournal`) to use control accounts.\n- [x] 3. Update journal generators in `vouchers_returns.js` (`generateVoucherJournal`, `generateSalesReturnJournal`, `generatePurchasesReturnJournal`) to use control accounts.\n- [x] 4. Inject Statement Modal into `index.html`.\n- [/] 5. Inject Statement Logic into `app_final.js` (`openContactStatement`).\n- [x] 6. Inject the \"كشف حساب\" button into the Contacts table in `app_final.js`."

--- BLOCK 2 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\inject_statement.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\n\nconst codeToAppend = `\n// --- CONTACT STATEMENT (SUB-LEDGER) ---\nwindow.currentStatementContactId = null;\n\nwindow.openContactStatement = function(contactId) {\n  window.currentStatementContactId = contactId;\n  const c = currentContacts.find(x => x.id === contactId);\n  if(!c) return;\n  document.getElementById('statement-header-info').innerText = \\`كشف حساب: \\${c.name} (\\${c.type})\\`;\n  document.getElementById('statement-date-from').value = '';\n  document.getElementById('statement-date-to').value = '';\n  window.refreshContactStatement();\n  showModal('contact-statement-modal');\n}\n\nwindow.refreshContactStatement = function() {\n  const contactId = window.currentStatementContactId;\n  const c = currentContacts.find(x => x.id === contactId);\n  if(!c) return;\n\n  const filterFrom = document.getElementById('statement-date-from').value;\n  const filterTo = document.getElementById('statement-date-to').value;\n\n  const tbody = document.getElementById('statement-tbody');\n  tbody.innerHTML = '';\n\n  let records = [];\n\n  // Gather Invoices (Sales, Purchases, Returns)\n  allInvoices.forEach(inv => {\n    if (inv.contact_id === contactId && inv.status === 'posted') {\n      let typeStr = '';\n      let debit = 0;\n      let credit = 0;\n      const total = inv.total_amount || inv.items.reduce((sum, it) => sum + ((it.price || 0) * (it.qty || 0)), 0);\n      \n      if (inv.type === 'sales') { typeStr = 'فاتورة مبيعات'; debit = total; }\n      else if (inv.type === 'purchases') { typeStr = 'فاتورة مشتريات'; credit = total; }\n      else if (inv.type === 'sales_return') { typeStr = 'مرتجع مبيعات'; credit = total; }\n      else if (inv.type === 'purchases_return') { typeStr = 'مرتجع مشتريات'; debit = total; }\n      else return; // skip others\n\n      records.push({\n        date: inv.date,\n        type: typeStr,\n
<truncated 3250 bytes>

--- BLOCK 3 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\inject_btn.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\n// The exact code in renderContacts\nconst searchStr = `    filtered.forEach(c => { \n      let actions = '';\n      let waLink = c.phone ? \\`<a href=\"https://wa.me/\\${c.phone}\" target=\"_blank\" style=\"color:#25D366; font-weight:bold; text-decoration:none;\">💬 واتساب</a>\\` : '-';\n      if(currentUser.role === 'مدير عام') actions = \\`<button class=\"action-btn btn-edit\" onclick=\"openContactModal(\\${c.id})\">✏️ تعديل</button> <button class=\"action-btn btn-delete\" onclick=\"deleteContact(\\${c.id})\">🗑️ حذف</button>\\`;\n      tbody.innerHTML += \\`<tr><td>\\${c.name}</td><td>\\${c.type}</td><td><span style=\"background:rgba(255,255,255,0.1); padding:2px 5px; border-radius:3px;\">\\${c.tag || '-'}</span></td><td>\\${c.phone || '-'} \\${waLink !== '-' ? ' | ' + waLink : ''}</td><td>\\${actions}</td></tr>\\`; \n    });`;\n\nconst replaceStr = `    filtered.forEach(c => { \n      let actions = \\`<button class=\"action-btn btn-view\" onclick=\"openContactStatement(\\${c.id})\">📄 كشف حساب</button> \\`;\n      let waLink = c.phone ? \\`<a href=\"https://wa.me/\\${c.phone}\" target=\"_blank\" style=\"color:#25D366; font-weight:bold; text-decoration:none;\">💬 واتساب</a>\\` : '-';\n      if(currentUser.role === 'مدير عام') actions += \\`<button class=\"action-btn btn-edit\" onclick=\"openContactModal(\\${c.id})\">✏️ تعديل</button> <button class=\"action-btn btn-delete\" onclick=\"deleteContact(\\${c.id})\">🗑️ حذف</button>\\`;\n      tbody.innerHTML += \\`<tr><td>\\${c.name}</td><td>\\${c.type}</td><td><span style=\"background:rgba(255,255,255,0.1); padding:2px 5px; border-radius:3px;\">\\${c.tag || '-'}</span></td><td>\\${c.phone || '-'} \\${waLink !== '-' ? ' | ' + waLink : ''}</td><td>\\${actions}</td></tr>\\`; \n    });`;\n\nif (app.includes(searchStr
<truncated 1034 bytes>

--- BLOCK 4 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_actions.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\napp = app.replace(\n  `let actions = '<button class=\"action-btn btn-view\" onclick=\"openContactStatement('$($c.id)')\">📄 كشف حساب</button> ';`,\n  `let actions = \\`<button class=\"action-btn btn-view\" onclick=\"openContactStatement(\\${c.id})\">📄 كشف حساب</button> \\`;`\n);\n\napp = app.replace(\n  `let actions = '<button class=\"action-btn btn-view\" onclick=\"openContactStatement('$($c.id)')\">📄 كشف حساب</button> ';`,\n  `let actions = '';`\n);\n\nfs.writeFileSync(appPath, app);\nconsole.log('Fixed syntax!');\n"

--- BLOCK 5 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_all_actions.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\nconst badString = `let actions = '<button class=\"action-btn btn-view\" onclick=\"openContactStatement('$($c.id)')\">📄 كشف حساب</button> ';`;\n\nlet count = 0;\nwhile (app.includes(badString)) {\n  app = app.replace(badString, `let actions = '';`);\n  count++;\n}\n\nfs.writeFileSync(appPath, app);\nconsole.log('Fixed ' + count + ' instances!');\n"

--- BLOCK 6 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\add_btn.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\nconst regex = /function renderContacts\\(\\) \\{[\\s\\S]*?filtered\\.forEach\\(c => \\{ \\n\\s*let actions = '';\\n\\s*let waLink = c\\.phone \\? `.*` : '-';\\n\\s*if\\(currentUser\\.role === 'مدير عام'\\) actions =/;\n\nif (regex.test(app)) {\n  app = app.replace(regex, (match) => {\n    return match.replace(`let actions = '';`, `let actions = \\`<button class=\"action-btn btn-view\" onclick=\"openContactStatement(\\${c.id})\">📄 كشف حساب</button> \\`;`)\n                .replace(`actions =`, `actions +=`);\n  });\n  fs.writeFileSync(appPath, app);\n  console.log('Button added successfully to renderContacts!');\n} else {\n  console.log('Regex did not match.');\n}\n"

--- BLOCK 7 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\add_btn.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\nconst s1 = `    filtered.forEach(c => { \\n      let actions = '';\\n      let waLink = c.phone ? \\`<a href=\"https://wa.me/\\${c.phone}\" target=\"_blank\" style=\"color:#25D366; font-weight:bold; text-decoration:none;\">💬 واتساب</a>\\` : '-';\\n      if(currentUser.role === 'مدير عام') actions = \\`<button class=\"action-btn btn-edit\" onclick=\"openContactModal(\\${c.id})\">✏️ تعديل</button> <button class=\"action-btn btn-delete\" onclick=\"deleteContact(\\${c.id})\">🗑️ حذف</button>\\`;\\n      tbody.innerHTML += \\`<tr><td>\\${c.name}</td><td>\\${c.type}</td><td><span style=\"background:rgba(255,255,255,0.1); padding:2px 5px; border-radius:3px;\">\\${c.tag || '-'}</span></td><td>\\${c.phone || '-'} \\${waLink !== '-' ? ' | ' + waLink : ''}</td><td>\\${actions}</td></tr>\\`; \\n    });`;\nconst r1 = `    filtered.forEach(c => { \\n      let actions = \\`<button class=\"action-btn btn-view\" onclick=\"openContactStatement(\\${c.id})\">📄 كشف حساب</button> \\`;\\n      let waLink = c.phone ? \\`<a href=\"https://wa.me/\\${c.phone}\" target=\"_blank\" style=\"color:#25D366; font-weight:bold; text-decoration:none;\">💬 واتساب</a>\\` : '-';\\n      if(currentUser.role === 'مدير عام') actions += \\`<button class=\"action-btn btn-edit\" onclick=\"openContactModal(\\${c.id})\">✏️ تعديل</button> <button class=\"action-btn btn-delete\" onclick=\"deleteContact(\\${c.id})\">🗑️ حذف</button>\\`;\\n      tbody.innerHTML += \\`<tr><td>\\${c.name}</td><td>\\${c.type}</td><td><span style=\"background:rgba(255,255,255,0.1); padding:2px 5px; border-radius:3px;\">\\${c.tag || '-'}</span></td><td>\\${c.phone || '-'} \\${waLink !== '-' ? ' | ' + waLink : ''}</td><td>\\${actions}</td></tr>\\`; \\n    });`;\n\nif (app.includes(s1)) {\n  app = app.replace(s1, r1);\n  fs.writeFileS
<truncated 142 bytes>

--- BLOCK 8 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_line.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet lines = fs.readFileSync(appPath, 'utf8').split('\\n');\n\n// Find the line index where function renderContacts() starts\nlet renderContactsIdx = -1;\nfor (let i = 0; i < lines.length; i++) {\n  if (lines[i].includes('function renderContacts() {')) {\n    renderContactsIdx = i;\n    break;\n  }\n}\n\nif (renderContactsIdx !== -1) {\n  // Find \"filtered.forEach(c => {\" inside renderContacts\n  let forEachIdx = -1;\n  for (let i = renderContactsIdx; i < renderContactsIdx + 30; i++) {\n    if (lines[i].includes('filtered.forEach(c => {')) {\n      forEachIdx = i;\n      break;\n    }\n  }\n\n  if (forEachIdx !== -1) {\n    // The next line should be let actions = '';\n    let actionsLineIdx = forEachIdx + 1;\n    if (lines[actionsLineIdx].includes(`let actions = '';`)) {\n      lines[actionsLineIdx] = `      let actions = \\`<button class=\"action-btn btn-view\" onclick=\"openContactStatement(\\${c.id})\">📄 كشف حساب</button> \\`;`;\n      fs.writeFileSync(appPath, lines.join('\\n'));\n      console.log('Fixed button exactly on the line!');\n    } else {\n      console.log('Line did not match: ' + lines[actionsLineIdx]);\n    }\n  } else {\n    console.log('forEach not found');\n  }\n} else {\n  console.log('renderContacts not found');\n}\n"

--- BLOCK 9 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_account_statement.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\n// 1. Add statement button to accounts table\nconst targetActions = `      if(currentUser && currentUser.role === 'مدير عام') {\n        actions = \\`<button class=\"action-btn btn-edit\" onclick=\"openAccountModal(\\${acc.id})\">✏️ تعديل</button>\n                   <button class=\"action-btn btn-view\" onclick=\"openAccountModal(null, \\${acc.id})\">➕ فرعي</button>\n                   <button class=\"action-btn btn-delete\" onclick=\"deleteAccount(\\${acc.id})\">🗑️ حذف</button>\\`;\n      }`;\nconst replaceActions = `      if(currentUser && currentUser.role === 'مدير عام') {\n        actions = \\`<button class=\"action-btn btn-view\" onclick=\"openAccountStatement(\\${acc.id})\">📄 كشف</button>\n                   <button class=\"action-btn btn-edit\" onclick=\"openAccountModal(\\${acc.id})\">✏️ تعديل</button>\n                   <button class=\"action-btn btn-view\" onclick=\"openAccountModal(null, \\${acc.id})\">➕ فرعي</button>\n                   <button class=\"action-btn btn-delete\" onclick=\"deleteAccount(\\${acc.id})\">🗑️ حذف</button>\\`;\n      } else {\n        actions = \\`<button class=\"action-btn btn-view\" onclick=\"openAccountStatement(\\${acc.id})\">📄 كشف</button>\\`;\n      }`;\n\napp = app.replace(targetActions, replaceActions);\n\n// 2. Replace the statement logic\nconst targetStatement = app.substring(\n    app.indexOf('window.currentStatementContactId = null;'),\n    app.indexOf('window.printContactStatement = function() {')\n);\n\nconst replaceStatement = `window.currentStatementType = 'contact';\nwindow.currentStatementId = null;\n\nwindow.openContactStatement = function(contactId) {\n  window.currentStatementType = 'contact';\n  window.currentStatementId = contactId;\n  const c = currentContacts.find(x => x.id === contactId);\n  if(!c)
<truncated 6844 bytes>

--- BLOCK 10 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_actions.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\n// We want to insert the button inside the loop.\n// Let's replace the whole `actions = ...` block using regex\napp = app.replace(\n    /actions = `<button class=\"action-btn btn-edit\" onclick=\"openAccountModal\\(\\$\\{acc\\.id\\}\\)\">.*?<\\/button>`;/s,\n    `actions = \\`<button class=\"action-btn btn-view\" style=\"background:#17a2b8;\" onclick=\"openAccountStatement(\\${acc.id})\">📄 كشف</button>\n                   <button class=\"action-btn btn-edit\" onclick=\"openAccountModal(\\${acc.id})\">✏️ تعديل</button>\n                   <button class=\"action-btn btn-view\" onclick=\"openAccountModal(null, \\${acc.id})\">➕ فرعي</button>\n                   <button class=\"action-btn btn-delete\" onclick=\"deleteAccount(\\${acc.id})\">🗑️ حذف</button>\\`;\n      } else {\n        actions = \\`<button class=\"action-btn btn-view\" style=\"background:#17a2b8;\" onclick=\"openAccountStatement(\\${acc.id})\">📄 كشف</button>\\`;`\n);\n\nfs.writeFileSync(appPath, app);\nconsole.log(\"Fixed actions\");"

--- BLOCK 11 ("d:\\برنامج مخازن\\index.html") ---
"        <div class=\"stats-grid\">\n          <div class=\"stat-card\"><h3>إجمالي الأصناف</h3><p id=\"stat-items\">0</p></div>\n          <div class=\"stat-card\"><h3>حركات اليوم</h3><p id=\"stat-transactions\">0</p></div>\n          <div class=\"stat-card\"><h3>المهام المعلقة</h3><p id=\"stat-pending\">0</p></div>\n          <div class=\"stat-card\"><h3>قيمة المخزون الحالية</h3><p id=\"stat-inventory-value\">0 ج.م</p></div>\n          <div class=\"stat-card\" id=\"my-custody-card\" style=\"display:none; border: 2px solid var(--primary);\">\n            <h3 style=\"color:var(--primary);\">رصيد عهدتي المتبقي</h3>\n            <p id=\"my-custody-balance\" style=\"color:var(--primary); font-size:24px; font-weight:bold; margin: 10px 0;\">0</p>\n            <button class=\"btn-primary\" onclick=\"openAccountStatement(currentUser.custody_account_id)\" style=\"width:100%; font-size:14px; padding:8px;\">📄 كشف حساب العهدة</button>\n          </div>\n        </div>"

--- BLOCK 12 ("d:\\برنامج مخازن\\app_final.js") ---
"  document.getElementById('stat-pending').innerText = myNotifs.length;\n  document.getElementById('notif-count').style.display = myNotifs.length > 0 ? 'inline-block' : 'none';\n  document.getElementById('notif-count').innerText = myNotifs.length;\n  \n  const custodyCard = document.getElementById('my-custody-card');\n  if (custodyCard && currentUser) {\n      custodyCard.style.display = 'block';\n      if (currentUser.custody_account_id) {\n          let runningBalance = 0;\n          currentJournals.forEach(j => {\n              if (j.status !== 'posted') return;\n              if (j.rows) {\n                  j.rows.forEach(r => {\n                      if (r.account_id == currentUser.custody_account_id) {\n                          runningBalance += (parseFloat(r.debit) || 0) - (parseFloat(r.credit) || 0);\n                      }\n                  });\n              }\n          });\n          let balStr = Math.abs(runningBalance).toLocaleString('ar-EG');\n          if (runningBalance > 0) balStr += ' مدين';\n          else if (runningBalance < 0) balStr += ' دائن';\n          else balStr = '0';\n          document.getElementById('my-custody-balance').innerText = balStr;\n          document.getElementById('my-custody-balance').style.fontSize = '24px';\n          const btn = document.getElementById('my-custody-card').querySelector('button');\n          if (btn) {\n              btn.style.display = 'block';\n              btn.onclick = function() { openAccountStatement(currentUser.custody_account_id); };\n          }\n      } else {\n          document.getElementById('my-custody-balance').innerText = 'لا يوجد عهدة مربوطة بحسابك';\n          document.getElementById('my-custody-balance').style.fontSize = '16px';\n          const btn = document.getElementById('my-custody-card').querySelector('button');\n          if (btn) btn.style.display = 'none';\n      }\n  }"

--- BLOCK 13 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\add_settlements_ui.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'index.html');\nlet html = fs.readFileSync(appPath, 'utf8');\n\nconst settlementsUI = `\n        <!-- PETTY CASH SETTLEMENTS VIEW -->\n        <div id=\"view-settlements\" class=\"view-section\" style=\"display:none;\">\n          <div class=\"header-actions\">\n            <h2>تسويات العهد</h2>\n            <div>\n              <button class=\"btn btn-primary\" onclick=\"openSettlementModal()\">+ إضافة تسوية جديدة</button>\n            </div>\n          </div>\n          <div class=\"filters\">\n             <input type=\"text\" id=\"settlement-search\" placeholder=\"بحث برقم التسوية أو حساب العهدة...\" onkeyup=\"renderSettlements()\">\n             <select id=\"settlement-status-filter\" onchange=\"renderSettlements()\">\n               <option value=\"all\">كل الحالات</option>\n               <option value=\"pending\">معلقة</option>\n               <option value=\"posted\">معتمدة</option>\n             </select>\n          </div>\n          <div class=\"table-container\">\n            <table class=\"excel-table\">\n              <thead>\n                <tr>\n                  <th>التاريخ</th>\n                  <th>رقم التسوية</th>\n                  <th>حساب العهدة</th>\n                  <th>إجمالي المبلغ</th>\n                  <th>الحالة</th>\n                  <th>إجراءات</th>\n                </tr>\n              </thead>\n              <tbody id=\"settlements-tbody\"></tbody>\n            </table>\n          </div>\n        </div>\n\n        <!-- SETTLEMENT MODAL -->\n        <div id=\"settlement-modal\" class=\"modal\">\n          <div class=\"modal-content\" style=\"width: 900px;\">\n            <div class=\"modal-header\">\n              <h3 id=\"settlement-modal-title\">تسوية عهدة جديدة</h3>\n              <span class=\"close\" onclick=\"closeMo
<truncated 3043 bytes>

--- BLOCK 14 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_ids.js") ---
"const fs = require('fs');\nconst path = require('path');\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\n// Fix approveSettlement\napp = app.replace(\n    \"const s = allInvoices.find(i => i.id === id);\",\n    \"const s = allInvoices.find(i => String(i.id) === String(id));\"\n);\n\n// Fix openSettlementModal\napp = app.replace(\n    \"const s = allInvoices.find(i => i.id === editId);\",\n    \"const s = allInvoices.find(i => String(i.id) === String(editId));\"\n);\n\n// Fix deleteSettlement\nconst oldDelete = `window.deleteSettlement = async function(id) {\n    if (!confirm(\"هل أنت متأكد من حذف هذه التسوية نهائياً؟\")) return;\n    await window.DB.remove('transactions', id);\n    await loadData();\n}`;\n\nconst newDelete = `window.deleteSettlement = async function(id) {\n    if (!confirm(\"هل أنت متأكد من حذف هذه التسوية نهائياً؟\")) return;\n    const s = allInvoices.find(i => String(i.id) === String(id));\n    await window.DB.remove('transactions', s ? s.id : id);\n    await loadData();\n}`;\napp = app.replace(oldDelete, newDelete);\n\nfs.writeFileSync(appPath, app);\nconsole.log(\"Fixes applied!\");\n"

--- BLOCK 15 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_modal_buttons.js") ---
"const fs = require('fs');\nconst path = require('path');\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\n// The line is: window.openSettlementModal = function(id = null) {\n// Let's add the restoration logic right after the first few lines of this function.\n\napp = app.replace(\n  /window\\.openSettlementModal = function\\(id = null\\) \\{\\s*document\\.getElementById\\('settlement-items-tbody'\\)\\.innerHTML = '';/g,\n  `window.openSettlementModal = function(id = null) {\n    const modal = document.getElementById('settlement-modal');\n    modal.querySelectorAll('input, select, button').forEach(el => {\n        if (el.tagName === 'BUTTON') el.style.display = '';\n        else el.disabled = false;\n    });\n    document.getElementById('settlement-items-tbody').innerHTML = '';`\n);\n\nfs.writeFileSync(appPath, app);\nconsole.log(\"Fix applied to openSettlementModal!\");"

--- BLOCK 16 ("C:\\Users\\BS\\.gemini\\antigravity\\brain\\393257b2-e812-421c-92f7-099f2362049e\\scratch\\fix_delete_settlement.js") ---
"const fs = require('fs');\nconst path = require('path');\n\nconst appPath = path.join('d:', 'برنامج مخازن', 'app_final.js');\nlet app = fs.readFileSync(appPath, 'utf8');\n\nconst s1 = `window.deleteSettlement = async function(id) {\n    if (!confirm(\"هل أنت متأكد من حذف هذه التسوية بشكل نهائي؟\")) return;\n    await window.DB.remove('transactions', id);\n    await loadData();\n}`;\n\nconst r1 = `window.deleteSettlement = async function(id) {\n    if (!confirm(\"تحذير: هل أنت متأكد من حذف هذه التسوية بشكل نهائي؟ (سيتم عكس أي قيود مالية وحركات مخزنية مرتبطة بها)\")) return;\n    \n    const inv = allInvoices.find(x => String(x.id) === String(id));\n    if (inv && (inv.status === 'posted' || inv.status === 'pending_store')) {\n        // Remove journal entries\n        const jEntry = currentJournals.find(j => j.reference === String(id) && j.type === 'settlement');\n        if (jEntry) {\n            await window.DB.remove('journal_entries', jEntry.id);\n        }\n        // Remove related notifications\n        const relatedNotifs = allNotifications.filter(n => n.invoice_id === inv.id);\n        for (let n of relatedNotifs) {\n            await window.DB.remove('notifications', n.id);\n        }\n    }\n    \n    await window.DB.remove('transactions', id);\n    await loadData();\n    alert('تم الحذف بنجاح.');\n}`;\n\nif (app.includes(s1)) {\n    app = app.replace(s1, r1);\n    console.log('deleteSettlement updated!');\n} else {\n    console.log('deleteSettlement NOT found! It might have been modified.');\n}\n\nconst s2 = `actions += \\`<button class=\"btn btn-sm btn-primary\" onclick=\"openSettlementModal(\\${s.id})\">✏️ تعديل</button> \\`;\n            actions += \\`<button class=\"btn btn-sm btn-danger\" onclick=\"deleteSettlement(\\${s.id})\">🗑️ حذف</button>\\`;\n        } else {\n            actions += \\`<button class=\"btn btn-sm btn-secondary\" onclick=\"
<truncated 1442 bytes>