upload.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. $dbPath = __DIR__ . '/_private/pl.db';
  3. $message = '';
  4. $messageType = '';
  5. function parseMonthLabel(string $label): ?array {
  6. $label = trim($label);
  7. $months = [
  8. 'Jan'=>1,'Feb'=>2,'Mar'=>3,'Apr'=>4,'May'=>5,'Jun'=>6,
  9. 'Jul'=>7,'Aug'=>8,'Sep'=>9,'Oct'=>10,'Nov'=>11,'Dec'=>12
  10. ];
  11. if (strtoupper($label) === 'TOTAL') {
  12. return ['year'=>null,'month_num'=>null,'is_total'=>1,'is_partial'=>0];
  13. }
  14. // Partial month: "May 1 - 11, 26"
  15. if (preg_match('/^(\w{3})\s+\d+\s*-\s*\d+,\s*(\d{2})$/', $label, $m)) {
  16. $mn = $months[$m[1]] ?? null;
  17. if (!$mn) return null;
  18. $yy = (int)$m[2];
  19. return ['year'=>$yy>=90?1900+$yy:2000+$yy,'month_num'=>$mn,'is_total'=>0,'is_partial'=>1];
  20. }
  21. // Standard: "May 90"
  22. if (preg_match('/^(\w{3})\s+(\d{2})$/', $label, $m)) {
  23. $mn = $months[$m[1]] ?? null;
  24. if (!$mn) return null;
  25. $yy = (int)$m[2];
  26. return ['year'=>$yy>=90?1900+$yy:2000+$yy,'month_num'=>$mn,'is_total'=>0,'is_partial'=>0];
  27. }
  28. return null;
  29. }
  30. function importCSV(string $filepath, string $dbPath): array {
  31. if (!file_exists($filepath) || !is_readable($filepath)) {
  32. return ['ok'=>false,'msg'=>'File not found or not readable: '.$filepath];
  33. }
  34. $dir = dirname($dbPath);
  35. if (!is_dir($dir) && !mkdir($dir, 0775, true)) {
  36. return ['ok'=>false,'msg'=>'Cannot create database directory.'];
  37. }
  38. try {
  39. $db = new PDO('sqlite:'.$dbPath);
  40. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  41. } catch (Exception $e) {
  42. return ['ok'=>false,'msg'=>'Cannot open database: '.$e->getMessage()];
  43. }
  44. $db->exec('PRAGMA journal_mode=WAL');
  45. $db->exec('DROP TABLE IF EXISTS pl_values');
  46. $db->exec('DROP TABLE IF EXISTS accounts');
  47. $db->exec('DROP TABLE IF EXISTS months');
  48. $db->exec('CREATE TABLE months (
  49. id INTEGER PRIMARY KEY AUTOINCREMENT,
  50. label TEXT NOT NULL,
  51. year INTEGER,
  52. month_num INTEGER,
  53. sort_order INTEGER NOT NULL,
  54. is_total INTEGER NOT NULL DEFAULT 0,
  55. is_partial INTEGER NOT NULL DEFAULT 0
  56. )');
  57. $db->exec('CREATE TABLE accounts (
  58. id INTEGER PRIMARY KEY AUTOINCREMENT,
  59. name TEXT NOT NULL,
  60. row_type TEXT NOT NULL,
  61. indent_level INTEGER NOT NULL DEFAULT 0,
  62. sort_order INTEGER NOT NULL
  63. )');
  64. $db->exec('CREATE TABLE pl_values (
  65. account_id INTEGER NOT NULL,
  66. month_id INTEGER NOT NULL,
  67. value REAL NOT NULL DEFAULT 0,
  68. PRIMARY KEY (account_id, month_id)
  69. )');
  70. $handle = fopen($filepath, 'r');
  71. if (!$handle) return ['ok'=>false,'msg'=>'Cannot open file.'];
  72. // Strip UTF-8 BOM if present
  73. $bom = fread($handle, 3);
  74. if ($bom !== "\xEF\xBB\xBF") rewind($handle);
  75. $header = fgetcsv($handle);
  76. if (!$header) { fclose($handle); return ['ok'=>false,'msg'=>'Empty or invalid CSV.']; }
  77. $db->beginTransaction();
  78. // Insert months from header (col 0 is the row-label column, skip it)
  79. $monthStmt = $db->prepare(
  80. 'INSERT INTO months (label, year, month_num, sort_order, is_total, is_partial) VALUES (?,?,?,?,?,?)'
  81. );
  82. $monthIds = []; // col_index => month.id
  83. for ($i = 1; $i < count($header); $i++) {
  84. $label = trim($header[$i]);
  85. if ($label === '') continue;
  86. $parsed = parseMonthLabel($label);
  87. if (!$parsed || $parsed['is_partial']) continue;
  88. if ($parsed['year'] !== null && $parsed['year'] < 1996) continue;
  89. $monthStmt->execute([
  90. $label, $parsed['year'], $parsed['month_num'],
  91. $i, $parsed['is_total'], $parsed['is_partial']
  92. ]);
  93. $monthIds[$i] = (int)$db->lastInsertId();
  94. }
  95. // Known row classifications
  96. $level0Headers = ['Ordinary Income/Expense','Other Income/Expense'];
  97. $level1Headers = ['Income','Cost of Goods Sold','Expense','Other Income','Other Expense'];
  98. $level0Subtotals = ['Gross Profit','Net Ordinary Income','Net Other Income'];
  99. $level1Subtotals = ['Total Income','Total COGS','Total Expense','Total Other Income','Total Other Expense'];
  100. $totals = ['Net Income'];
  101. $accountStmt = $db->prepare(
  102. 'INSERT INTO accounts (name, row_type, indent_level, sort_order) VALUES (?,?,?,?)'
  103. );
  104. $valueStmt = $db->prepare(
  105. 'INSERT OR REPLACE INTO pl_values (account_id, month_id, value) VALUES (?,?,?)'
  106. );
  107. $sortOrder = 0;
  108. $accountCount = 0;
  109. $valueCount = 0;
  110. while (($row = fgetcsv($handle)) !== false) {
  111. if (empty($row)) continue;
  112. $name = trim($row[0] ?? '');
  113. if ($name === '') continue;
  114. // Detect whether any value columns are non-empty
  115. $hasValues = false;
  116. for ($i = 1; $i < count($row); $i++) {
  117. if (isset($row[$i]) && trim($row[$i]) !== '') { $hasValues = true; break; }
  118. }
  119. if (!$hasValues) {
  120. $rowType = 'header';
  121. $indent = in_array($name, $level0Headers) ? 0 : 1;
  122. } elseif (in_array($name, $totals)) {
  123. $rowType = 'total';
  124. $indent = 0;
  125. } elseif (in_array($name, $level0Subtotals)) {
  126. $rowType = 'subtotal';
  127. $indent = 0;
  128. } elseif (in_array($name, $level1Subtotals)) {
  129. $rowType = 'subtotal';
  130. $indent = 1;
  131. } else {
  132. $rowType = 'item';
  133. $indent = 2;
  134. }
  135. $accountStmt->execute([$name, $rowType, $indent, $sortOrder++]);
  136. $accountId = (int)$db->lastInsertId();
  137. $accountCount++;
  138. if ($hasValues) {
  139. for ($i = 1; $i < count($row); $i++) {
  140. if (!isset($monthIds[$i])) continue;
  141. $raw = trim($row[$i] ?? '');
  142. if ($raw === '') continue;
  143. $val = (float)str_replace([',', ' '], '', $raw);
  144. $valueStmt->execute([$accountId, $monthIds[$i], $val]);
  145. $valueCount++;
  146. }
  147. }
  148. }
  149. $db->commit();
  150. fclose($handle);
  151. $numMonths = count($monthIds);
  152. return [
  153. 'ok' => true,
  154. 'msg' => "Successfully imported $accountCount accounts across $numMonths months ($valueCount data points)."
  155. ];
  156. }
  157. // Handle POST
  158. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  159. if (isset($_POST['import_existing'])) {
  160. $csvPath = __DIR__ . '/May2026PL.csv';
  161. $result = importCSV($csvPath, $dbPath);
  162. } elseif (isset($_FILES['csvfile']) && $_FILES['csvfile']['error'] === UPLOAD_ERR_OK) {
  163. $result = importCSV($_FILES['csvfile']['tmp_name'], $dbPath);
  164. } else {
  165. $uploadErr = $_FILES['csvfile']['error'] ?? -1;
  166. $result = ['ok'=>false,'msg'=>'Upload error (code '.$uploadErr.'). Check php.ini upload_max_filesize.'];
  167. }
  168. $message = $result['msg'];
  169. $messageType = $result['ok'] ? 'success' : 'error';
  170. }
  171. $hasExistingCsv = file_exists(__DIR__ . '/May2026PL.csv');
  172. $hasDb = file_exists($dbPath) && filesize($dbPath) > 0;
  173. ?>
  174. <!DOCTYPE html>
  175. <html lang="en">
  176. <head>
  177. <meta charset="UTF-8">
  178. <title>Upload P&amp;L Data — ICG Magnetics</title>
  179. <style>
  180. *{box-sizing:border-box;margin:0;padding:0}
  181. 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}
  182. .card{background:white;border-radius:12px;box-shadow:0 4px 24px rgba(0,0,0,.08);width:100%;max-width:520px;padding:36px 40px}
  183. .card h1{font-size:22px;font-weight:700;color:#0f172a;margin-bottom:4px}
  184. .card .sub{font-size:13px;color:#64748b;margin-bottom:28px}
  185. .section{margin-bottom:24px;padding:20px;border:1px solid #e2e8f0;border-radius:8px}
  186. .section h2{font-size:13px;font-weight:600;color:#475569;text-transform:uppercase;letter-spacing:.5px;margin-bottom:14px}
  187. .btn{display:inline-block;padding:10px 20px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;border:none;transition:.15s}
  188. .btn-primary{background:#3b82f6;color:white}
  189. .btn-primary:hover{background:#2563eb}
  190. .btn-secondary{background:#e2e8f0;color:#475569}
  191. .btn-secondary:hover{background:#cbd5e1}
  192. .btn-view{background:#10b981;color:white;text-decoration:none;display:inline-block;padding:10px 20px;border-radius:6px;font-size:14px;font-weight:600}
  193. .btn-view:hover{background:#059669}
  194. 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}
  195. input[type=file]:hover{border-color:#94a3b8}
  196. .alert{padding:14px 16px;border-radius:6px;font-size:13px;margin-bottom:20px;line-height:1.5}
  197. .alert.success{background:#d1fae5;color:#065f46;border:1px solid #6ee7b7}
  198. .alert.error{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5}
  199. .back{display:inline-block;margin-top:20px;color:#3b82f6;text-decoration:none;font-size:13px}
  200. .back:hover{text-decoration:underline}
  201. .note{font-size:11px;color:#94a3b8;margin-top:8px;line-height:1.5}
  202. .existing-badge{display:inline-block;background:#d1fae5;color:#065f46;font-size:11px;padding:2px 7px;border-radius:10px;margin-left:6px;font-weight:500}
  203. .overwrite-warning{font-size:12px;color:#b45309;margin-top:10px;padding:8px 12px;background:#fef3c7;border-radius:5px}
  204. </style>
  205. </head>
  206. <body>
  207. <div class="card">
  208. <h1>Upload P&amp;L Data</h1>
  209. <div class="sub">ICG Magnetics · QuickBooks CSV Import</div>
  210. <?php if ($message): ?>
  211. <div class="alert <?= htmlspecialchars($messageType) ?>">
  212. <?= htmlspecialchars($message) ?>
  213. <?php if ($messageType === 'success'): ?>
  214. <div style="margin-top:12px">
  215. <a href="index.php" class="btn-view">View P&amp;L →</a>
  216. </div>
  217. <?php endif; ?>
  218. </div>
  219. <?php endif; ?>
  220. <?php if ($hasExistingCsv): ?>
  221. <div class="section">
  222. <h2>Quick Import <span class="existing-badge">File Found</span></h2>
  223. <p style="font-size:13px;color:#475569;margin-bottom:12px">
  224. Found <strong>May2026PL.csv</strong> on this server. Click to import it directly.
  225. </p>
  226. <?php if ($hasDb): ?>
  227. <div class="overwrite-warning">⚠ This will replace all existing P&amp;L data.</div>
  228. <?php endif; ?>
  229. <form method="post" style="margin-top:12px">
  230. <button type="submit" name="import_existing" class="btn btn-primary">Import May2026PL.csv</button>
  231. </form>
  232. </div>
  233. <?php endif; ?>
  234. <div class="section">
  235. <h2>Upload New CSV</h2>
  236. <p style="font-size:13px;color:#475569;margin-bottom:12px">
  237. Upload a QuickBooks P&amp;L export (by month). All existing data will be replaced.
  238. </p>
  239. <?php if ($hasDb): ?>
  240. <div class="overwrite-warning">⚠ This will replace all existing P&amp;L data.</div>
  241. <?php endif; ?>
  242. <form method="post" enctype="multipart/form-data" style="margin-top:12px">
  243. <input type="file" name="csvfile" accept=".csv,text/csv">
  244. <div class="note">Export from QuickBooks: Reports → Profit &amp; Loss → Columns: Month → Export to CSV</div>
  245. <button type="submit" class="btn btn-primary" style="margin-top:12px">Upload &amp; Import</button>
  246. </form>
  247. </div>
  248. <?php if ($hasDb && !$message): ?>
  249. <a href="index.php" class="back">← Back to P&amp;L Viewer</a>
  250. <?php endif; ?>
  251. </div>
  252. </body>
  253. </html>