upload.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. <?php
  2. require __DIR__ . '/auth.php';
  3. $dbPath = __DIR__ . '/_private/pl.db';
  4. $message = '';
  5. $messageType = '';
  6. function parseMonthLabel(string $label): ?array {
  7. $label = trim($label);
  8. $months = [
  9. 'Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6,
  10. 'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12
  11. ];
  12. if (strtoupper($label) === 'TOTAL') {
  13. return ['year'=>null,'month_num'=>null,'is_total'=>1,'is_partial'=>0];
  14. }
  15. // Partial month: "May 1 - 11, 26"
  16. if (preg_match('/^(\w{3})\s+\d+\s*-\s*\d+,\s*(\d{2})$/', $label, $m)) {
  17. $mn = $months[$m[1]] ?? null;
  18. if (!$mn) return null;
  19. $yy = (int)$m[2];
  20. return ['year'=>$yy>=90?1900+$yy:2000+$yy,'month_num'=>$mn,'is_total'=>0,'is_partial'=>1];
  21. }
  22. // Standard: "May 90"
  23. if (preg_match('/^(\w{3})\s+(\d{2})$/', $label, $m)) {
  24. $mn = $months[$m[1]] ?? null;
  25. if (!$mn) return null;
  26. $yy = (int)$m[2];
  27. return ['year'=>$yy>=90?1900+$yy:2000+$yy,'month_num'=>$mn,'is_total'=>0,'is_partial'=>0];
  28. }
  29. return null;
  30. }
  31. function importCSV(string $filepath, string $dbPath): array {
  32. if (!file_exists($filepath) || !is_readable($filepath)) {
  33. return ['ok'=>false,'msg'=>'File not found or not readable: '.$filepath];
  34. }
  35. $dir = dirname($dbPath);
  36. if (!is_dir($dir) && !mkdir($dir, 0775, true)) {
  37. return ['ok'=>false,'msg'=>'Cannot create database directory.'];
  38. }
  39. try {
  40. $db = new PDO('sqlite:'.$dbPath);
  41. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  42. } catch (Exception $e) {
  43. return ['ok'=>false,'msg'=>'Cannot open database: '.$e->getMessage()];
  44. }
  45. $db->exec('PRAGMA journal_mode=WAL');
  46. $db->exec('DROP TABLE IF EXISTS pl_values');
  47. $db->exec('DROP TABLE IF EXISTS accounts');
  48. $db->exec('DROP TABLE IF EXISTS months');
  49. $db->exec('CREATE TABLE months (
  50. id INTEGER PRIMARY KEY AUTOINCREMENT,
  51. label TEXT NOT NULL,
  52. year INTEGER,
  53. month_num INTEGER,
  54. sort_order INTEGER NOT NULL,
  55. is_total INTEGER NOT NULL DEFAULT 0,
  56. is_partial INTEGER NOT NULL DEFAULT 0
  57. )');
  58. $db->exec('CREATE TABLE accounts (
  59. id INTEGER PRIMARY KEY AUTOINCREMENT,
  60. name TEXT NOT NULL,
  61. row_type TEXT NOT NULL,
  62. indent_level INTEGER NOT NULL DEFAULT 0,
  63. sort_order INTEGER NOT NULL
  64. )');
  65. $db->exec('CREATE TABLE pl_values (
  66. account_id INTEGER NOT NULL,
  67. month_id INTEGER NOT NULL,
  68. value REAL NOT NULL DEFAULT 0,
  69. PRIMARY KEY (account_id, month_id)
  70. )');
  71. $handle = fopen($filepath, 'r');
  72. if (!$handle) return ['ok'=>false,'msg'=>'Cannot open file.'];
  73. // Strip UTF-8 BOM if present
  74. $bom = fread($handle, 3);
  75. if ($bom !== "\xEF\xBB\xBF") rewind($handle);
  76. $header = fgetcsv($handle);
  77. if (!$header) { fclose($handle); return ['ok'=>false,'msg'=>'Empty or invalid CSV.']; }
  78. $db->beginTransaction();
  79. // Insert months from header (col 0 is the row-label column, skip it)
  80. $monthStmt = $db->prepare(
  81. 'INSERT INTO months (label, year, month_num, sort_order, is_total, is_partial) VALUES (?,?,?,?,?,?)'
  82. );
  83. $monthIds = []; // col_index => month.id
  84. for ($i = 1; $i < count($header); $i++) {
  85. $label = trim($header[$i]);
  86. if ($label === '') continue;
  87. $parsed = parseMonthLabel($label);
  88. if (!$parsed || $parsed['is_partial']) continue;
  89. if ($parsed['year'] !== null && $parsed['year'] < 1996) continue;
  90. $monthStmt->execute([
  91. $label, $parsed['year'], $parsed['month_num'],
  92. $i, $parsed['is_total'], $parsed['is_partial']
  93. ]);
  94. $monthIds[$i] = (int)$db->lastInsertId();
  95. }
  96. // Known row classifications
  97. $level0Headers = ['Ordinary Income/Expense','Other Income/Expense'];
  98. $level1Headers = ['Income','Cost of Goods Sold','Expense','Other Income','Other Expense'];
  99. $level0Subtotals = ['Gross Profit','Net Ordinary Income','Net Other Income'];
  100. $level1Subtotals = ['Total Income','Total COGS','Total Expense','Total Other Income','Total Other Expense'];
  101. $totals = ['Net Income'];
  102. $accountStmt = $db->prepare(
  103. 'INSERT INTO accounts (name, row_type, indent_level, sort_order) VALUES (?,?,?,?)'
  104. );
  105. $valueStmt = $db->prepare(
  106. 'INSERT OR REPLACE INTO pl_values (account_id, month_id, value) VALUES (?,?,?)'
  107. );
  108. $sortOrder = 0;
  109. $accountCount = 0;
  110. $valueCount = 0;
  111. while (($row = fgetcsv($handle)) !== false) {
  112. if (empty($row)) continue;
  113. $name = trim($row[0] ?? '');
  114. if ($name === '') continue;
  115. // Detect whether any value columns are non-empty
  116. $hasValues = false;
  117. for ($i = 1; $i < count($row); $i++) {
  118. if (isset($row[$i]) && trim($row[$i]) !== '') { $hasValues = true; break; }
  119. }
  120. if (!$hasValues) {
  121. $rowType = 'header';
  122. $indent = in_array($name, $level0Headers) ? 0 : 1;
  123. } elseif (in_array($name, $totals)) {
  124. $rowType = 'total';
  125. $indent = 0;
  126. } elseif (in_array($name, $level0Subtotals)) {
  127. $rowType = 'subtotal';
  128. $indent = 0;
  129. } elseif (in_array($name, $level1Subtotals)) {
  130. $rowType = 'subtotal';
  131. $indent = 1;
  132. } else {
  133. $rowType = 'item';
  134. $indent = 2;
  135. }
  136. $accountStmt->execute([$name, $rowType, $indent, $sortOrder++]);
  137. $accountId = (int)$db->lastInsertId();
  138. $accountCount++;
  139. if ($hasValues) {
  140. for ($i = 1; $i < count($row); $i++) {
  141. if (!isset($monthIds[$i])) continue;
  142. $raw = trim($row[$i] ?? '');
  143. if ($raw === '') continue;
  144. $val = (float)str_replace([',', ' '], '', $raw);
  145. $valueStmt->execute([$accountId, $monthIds[$i], $val]);
  146. $valueCount++;
  147. }
  148. }
  149. }
  150. $db->commit();
  151. fclose($handle);
  152. $numMonths = count($monthIds);
  153. return [
  154. 'ok' => true,
  155. 'msg' => "Successfully imported $accountCount accounts across $numMonths months ($valueCount data points)."
  156. ];
  157. }
  158. $configPath = __DIR__ . '/_private/config.php';
  159. function loadCodes(string $path): array {
  160. return file_exists($path) ? (require $path) : [];
  161. }
  162. function saveCodes(string $path, array $codes): void {
  163. $export = "<?php\n// Access codes for P&L viewer.\n// Managed via http://rktbds/upload.php — do not edit by hand.\nreturn " . var_export($codes, true) . ";\n";
  164. file_put_contents($path, $export);
  165. }
  166. $accessMsg = '';
  167. $accessType = '';
  168. // Handle POST
  169. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  170. if (isset($_POST['import_existing'])) {
  171. $csvPath = __DIR__ . '/May2026PL.csv';
  172. $result = importCSV($csvPath, $dbPath);
  173. $message = $result['msg'];
  174. $messageType = $result['ok'] ? 'success' : 'error';
  175. } elseif (isset($_FILES['csvfile']) && $_FILES['csvfile']['error'] === UPLOAD_ERR_OK) {
  176. $result = importCSV($_FILES['csvfile']['tmp_name'], $dbPath);
  177. $message = $result['msg'];
  178. $messageType = $result['ok'] ? 'success' : 'error';
  179. } elseif (isset($_POST['add_code'])) {
  180. $label = trim($_POST['code_label'] ?? '');
  181. $pw = $_POST['code_pw'] ?? '';
  182. $pw2 = $_POST['code_pw2'] ?? '';
  183. if ($label === '') {
  184. $accessMsg = 'Label is required.'; $accessType = 'error';
  185. } elseif ($pw === '') {
  186. $accessMsg = 'Access code is required.'; $accessType = 'error';
  187. } elseif ($pw !== $pw2) {
  188. $accessMsg = 'Access codes do not match.'; $accessType = 'error';
  189. } else {
  190. $codes = loadCodes($configPath);
  191. $codes[] = ['label' => $label, 'hash' => password_hash($pw, PASSWORD_BCRYPT)];
  192. saveCodes($configPath, $codes);
  193. $accessMsg = "Access code for \"" . htmlspecialchars($label) . "\" added.";
  194. $accessType = 'success';
  195. }
  196. } elseif (isset($_POST['remove_code'])) {
  197. $idx = (int)$_POST['remove_code'];
  198. $codes = loadCodes($configPath);
  199. if (count($codes) <= 1) {
  200. $accessMsg = 'Cannot remove the last access code.'; $accessType = 'error';
  201. } elseif (isset($codes[$idx])) {
  202. $label = $codes[$idx]['label'];
  203. array_splice($codes, $idx, 1);
  204. saveCodes($configPath, $codes);
  205. $accessMsg = "Access code for \"" . htmlspecialchars($label) . "\" removed.";
  206. $accessType = 'success';
  207. }
  208. } else {
  209. $uploadErr = $_FILES['csvfile']['error'] ?? -1;
  210. $message = 'Upload error (code '.$uploadErr.'). Check php.ini upload_max_filesize.';
  211. $messageType = 'error';
  212. }
  213. }
  214. $hasExistingCsv = file_exists(__DIR__ . '/May2026PL.csv');
  215. $hasDb = file_exists($dbPath) && filesize($dbPath) > 0;
  216. ?>
  217. <!DOCTYPE html>
  218. <html lang="en">
  219. <head>
  220. <meta charset="UTF-8">
  221. <title>Upload P&amp;L Data — ICG Magnetics</title>
  222. <style>
  223. *{box-sizing:border-box;margin:0;padding:0}
  224. body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f1f5f9;color:#1e293b;min-height:100vh;display:flex;align-items:center;justify-content:center}
  225. .card{background:white;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,.08);width:100%;max-width:520px;padding:36px 40px}
  226. .card h1{font-size:22px;font-weight:700;color:#0f172a;margin-bottom:4px}
  227. .card .sub{font-size:13px;color:#64748b;margin-bottom:28px}
  228. .section{margin-bottom:24px;padding:20px;border:1px solid #e2e8f0;border-radius:8px}
  229. .section h2{font-size:13px;font-weight:600;color:#475569;text-transform:uppercase;letter-spacing:.5px;margin-bottom:14px}
  230. .btn{display:inline-block;padding:10px 20px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;border:none;transition:.15s}
  231. .btn-primary{background:#3b82f6;color:white}
  232. .btn-primary:hover{background:#2563eb}
  233. .btn-secondary{background:#e2e8f0;color:#475569}
  234. .btn-secondary:hover{background:#cbd5e1}
  235. .btn-view{background:#10b981;color:white;text-decoration:none;display:inline-block;padding:10px 20px;border-radius:6px;font-size:14px;font-weight:600}
  236. .btn-view:hover{background:#059669}
  237. input[type=file]{display:block;width:100%;padding:10px;border:2px dashed #cbd5e1;border-radius:6px;margin-bottom:12px;font-size:13px;color:#475569;cursor:pointer;background:#f8fafc}
  238. input[type=file]:hover{border-color:#94a3b8}
  239. .alert{padding:14px 16px;border-radius:6px;font-size:13px;margin-bottom:20px;line-height:1.5}
  240. .alert.success{background:#d1fae5;color:#065f46;border:1px solid #6ee7b7}
  241. .alert.error{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5}
  242. .back{display:inline-block;margin-top:20px;color:#3b82f6;text-decoration:none;font-size:13px}
  243. .back:hover{text-decoration:underline}
  244. .note{font-size:11px;color:#94a3b8;margin-top:8px;line-height:1.5}
  245. .existing-badge{display:inline-block;background:#d1fae5;color:#065f46;font-size:11px;padding:2px 7px;border-radius:10px;margin-left:6px;font-weight:500}
  246. .overwrite-warning{font-size:12px;color:#b45309;margin-top:10px;padding:8px 12px;background:#fef3c7;border-radius:5px}
  247. </style>
  248. </head>
  249. <body>
  250. <div class="card">
  251. <h1>Upload P&amp;L Data</h1>
  252. <div class="sub">ICG Magnetics · QuickBooks CSV Import</div>
  253. <?php if ($message): ?>
  254. <div class="alert <?= htmlspecialchars($messageType) ?>">
  255. <?= htmlspecialchars($message) ?>
  256. <?php if ($messageType === 'success'): ?>
  257. <div style="margin-top:12px">
  258. <a href="index.php" class="btn-view">View P&amp;L →</a>
  259. </div>
  260. <?php endif; ?>
  261. </div>
  262. <?php endif; ?>
  263. <?php if ($hasExistingCsv): ?>
  264. <div class="section">
  265. <h2>Quick Import <span class="existing-badge">File Found</span></h2>
  266. <p style="font-size:13px;color:#475569;margin-bottom:12px">
  267. Found <strong>May2026PL.csv</strong> on this server. Click to import it directly.
  268. </p>
  269. <?php if ($hasDb): ?>
  270. <div class="overwrite-warning">⚠ This will replace all existing P&amp;L data.</div>
  271. <?php endif; ?>
  272. <form method="post" style="margin-top:12px">
  273. <button type="submit" name="import_existing" class="btn btn-primary">Import May2026PL.csv</button>
  274. </form>
  275. </div>
  276. <?php endif; ?>
  277. <div class="section">
  278. <h2>Upload New CSV</h2>
  279. <p style="font-size:13px;color:#475569;margin-bottom:12px">
  280. Upload a QuickBooks P&amp;L export (by month). All existing data will be replaced.
  281. </p>
  282. <?php if ($hasDb): ?>
  283. <div class="overwrite-warning">⚠ This will replace all existing P&amp;L data.</div>
  284. <?php endif; ?>
  285. <form method="post" enctype="multipart/form-data" style="margin-top:12px">
  286. <input type="file" name="csvfile" accept=".csv,text/csv">
  287. <div class="note">Export from QuickBooks: Reports → Profit &amp; Loss → Columns: Month → Export to CSV</div>
  288. <button type="submit" class="btn btn-primary" style="margin-top:12px">Upload &amp; Import</button>
  289. </form>
  290. </div>
  291. <!-- ── Access Codes ── -->
  292. <div class="section">
  293. <h2>Access Codes</h2>
  294. <?php if ($accessMsg): ?>
  295. <div class="alert <?= $accessType ?>" style="margin-bottom:14px"><?= $accessMsg ?></div>
  296. <?php endif; ?>
  297. <?php
  298. $codes = loadCodes($configPath);
  299. if ($codes):
  300. ?>
  301. <table style="width:100%;border-collapse:collapse;margin-bottom:14px;font-size:13px">
  302. <thead>
  303. <tr style="border-bottom:1px solid #e2e8f0">
  304. <th style="text-align:left;padding:4px 8px;color:#64748b;font-weight:600">#</th>
  305. <th style="text-align:left;padding:4px 8px;color:#64748b;font-weight:600">Label</th>
  306. <th></th>
  307. </tr>
  308. </thead>
  309. <tbody>
  310. <?php foreach ($codes as $i => $code): ?>
  311. <tr style="border-bottom:1px solid #f1f5f9">
  312. <td style="padding:7px 8px;color:#94a3b8"><?= $i + 1 ?></td>
  313. <td style="padding:7px 8px;font-weight:500"><?= htmlspecialchars($code['label']) ?></td>
  314. <td style="padding:7px 8px;text-align:right">
  315. <form method="post" style="display:inline" onsubmit="return confirm('Remove access for \'<?= htmlspecialchars(addslashes($code['label'])) ?>\'?')">
  316. <button type="submit" name="remove_code" value="<?= $i ?>"
  317. style="background:none;border:none;color:#ef4444;font-size:12px;cursor:pointer;font-weight:600"
  318. <?= count($codes) <= 1 ? 'disabled title="Cannot remove last code"' : '' ?>>
  319. Remove
  320. </button>
  321. </form>
  322. </td>
  323. </tr>
  324. <?php endforeach; ?>
  325. </tbody>
  326. </table>
  327. <?php endif; ?>
  328. <form method="post" style="display:grid;gap:8px">
  329. <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
  330. <div>
  331. <label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:4px">Label (e.g. name)</label>
  332. <input type="text" name="code_label" placeholder="Alice"
  333. style="width:100%;padding:7px 10px;border:1px solid #cbd5e1;border-radius:5px;font-size:13px">
  334. </div>
  335. <div>
  336. <label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:4px">Access Code</label>
  337. <input type="password" name="code_pw" placeholder="access code"
  338. style="width:100%;padding:7px 10px;border:1px solid #cbd5e1;border-radius:5px;font-size:13px">
  339. </div>
  340. </div>
  341. <div>
  342. <label style="font-size:11px;font-weight:600;color:#64748b;display:block;margin-bottom:4px">Confirm Access Code</label>
  343. <input type="password" name="code_pw2" placeholder="repeat access code"
  344. style="width:100%;padding:7px 10px;border:1px solid #cbd5e1;border-radius:5px;font-size:13px">
  345. </div>
  346. <button type="submit" name="add_code" class="btn btn-primary" style="justify-self:start;margin-top:4px">Add Access Code</button>
  347. </form>
  348. </div>
  349. <div style="display:flex;justify-content:space-between;align-items:center;margin-top:4px">
  350. <?php if ($hasDb): ?>
  351. <a href="index.php" class="back">← Back to P&amp;L Viewer</a>
  352. <?php else: ?>
  353. <span></span>
  354. <?php endif; ?>
  355. <a href="logout.php" style="font-size:13px;color:#94a3b8;text-decoration:none">Sign out</a>
  356. </div>
  357. </div>
  358. </body>
  359. </html>