Repository navigation
Expand file tree
/
Copy pathorders.php
More file actions
466 lines (436 loc) · 22.4 KB
/
Copy pathorders.php
File metadata and controls
466 lines (436 loc) · 22.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
<?php
require_once 'includes/auth.php';
requireLogin();
require_once 'includes/nav.php';
$db = getDB();
$user = getCurrentUser();
$msg = '';
$msgType = 'success';
$action = $_GET['action'] ?? '';
$viewId = (int)($_GET['view'] ?? 0);
// Handle CSV export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['q'] ?? '');
$where = "WHERE 1=1";
$params = [];
if ($statusFilter) { $where .= " AND o.status=?"; $params[] = $statusFilter; }
if ($search) { $where .= " AND (o.order_number LIKE ? OR c.name LIKE ? OR c.email LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
$stmt = $db->prepare("SELECT o.order_number, c.name AS customer_name, c.email AS customer_email, o.description, o.quantity, o.unit_price, o.total_price, o.status, o.machine, o.due_date, o.created_at, o.notes FROM orders o JOIN customers c ON o.customer_id=c.id $where ORDER BY o.id DESC");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="orders_' . date('Ymd_His') . '.csv"');
header('Pragma: no-cache');
$out = fopen('php://output', 'w');
fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF)); // UTF-8 BOM for Excel
fputcsv($out, ['Order Number','Customer','Email','Description','Qty','Unit Price (IDR)','Total (IDR)','Status','Machine','Due Date','Created At','Notes']);
foreach ($rows as $row) {
fputcsv($out, [
$row['order_number'],
$row['customer_name'],
$row['customer_email'],
$row['description'],
$row['quantity'],
$row['unit_price'],
$row['total_price'],
$row['status'],
$row['machine'] ?? '',
$row['due_date'] ? date('d/m/Y', strtotime($row['due_date'])) : '',
date('d/m/Y H:i', strtotime($row['created_at'])),
$row['notes'] ?? '',
]);
}
fclose($out);
exit;
}
// Handle status update via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
$oid = (int)$_POST['order_id'];
$status = $_POST['status'];
$allowed = ['pending','plating','printing','finishing','packing','completed','cancelled'];
if (in_array($status, $allowed, true)) {
$stmt = $db->prepare("SELECT order_number FROM orders WHERE id=?");
$stmt->execute([$oid]);
$on = $stmt->fetchColumn();
$db->prepare("UPDATE orders SET status=? WHERE id=?")->execute([$status, $oid]);
$db->prepare("INSERT INTO order_activity (order_id, order_number, status) VALUES (?,?,?)")->execute([$oid, $on, $status]);
$msg = "Order status updated to " . statusLabel($status);
}
}
// Handle new order
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_order'])) {
$custId = (int)$_POST['customer_id'];
$desc = trim($_POST['description']);
$qty = (int)$_POST['quantity'];
$unitPrice = (float)$_POST['unit_price'];
$total = $qty * $unitPrice;
$notes = trim($_POST['notes']);
$due = $_POST['due_date'] ?: null;
$machine = trim($_POST['machine'] ?? '');
$orderNum = trim($_POST['order_number'] ?? '') ?: generateOrderNumber();
// Check for duplicate order number
$dupCheck = $db->prepare("SELECT COUNT(*) FROM orders WHERE order_number=?");
$dupCheck->execute([$orderNum]);
if ($dupCheck->fetchColumn() > 0) {
$msg = "Order number '$orderNum' already exists. Please use a different number.";
$msgType = 'error';
} else {
$stmt = $db->prepare("INSERT INTO orders (order_number,customer_id,status,description,quantity,unit_price,total_price,notes,due_date,machine) VALUES (?,?,'pending',?,?,?,?,?,?,?)");
$stmt->execute([$orderNum, $custId, $desc, $qty, $unitPrice, $total, $notes, $due, $machine]);
$newId = $db->lastInsertId();
$db->prepare("INSERT INTO order_activity (order_id, order_number, status, note) VALUES (?,?,?,?)")->execute([$newId, $orderNum, 'pending', 'Order created']);
$msg = "Order $orderNum created successfully!";
$action = '';
}
}
// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_order'])) {
$oid = (int)$_POST['order_id'];
$db->prepare("DELETE FROM orders WHERE id=?")->execute([$oid]);
$msg = "Order deleted.";
}
// Filters
$statusFilter = $_GET['status'] ?? '';
$search = trim($_GET['q'] ?? '');
$page = max(1, (int)($_GET['p'] ?? 1));
$perPage = 15;
$offset = ($page-1)*$perPage;
$where = "WHERE 1=1";
$params = [];
if ($statusFilter) { $where .= " AND o.status=?"; $params[] = $statusFilter; }
if ($search) { $where .= " AND (o.order_number LIKE ? OR c.name LIKE ? OR c.email LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s,$s]); }
$countStmt = $db->prepare("SELECT COUNT(*) FROM orders o JOIN customers c ON o.customer_id=c.id $where");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);
$stmt = $db->prepare("SELECT o.*, c.name AS customer_name, c.email AS customer_email FROM orders o JOIN customers c ON o.customer_id=c.id $where ORDER BY o.id DESC LIMIT $perPage OFFSET $offset");
$stmt->execute($params);
$orders = $stmt->fetchAll();
// View single order
$viewOrder = null;
if ($viewId) {
$s = $db->prepare("SELECT o.*, c.name AS customer_name, c.email AS customer_email, c.phone AS customer_phone FROM orders o JOIN customers c ON o.customer_id=c.id WHERE o.id=?");
$s->execute([$viewId]);
$viewOrder = $s->fetch();
if ($viewOrder) {
$sa = $db->prepare("SELECT * FROM order_activity WHERE order_id=? ORDER BY id ASC");
$sa->execute([$viewId]);
$viewActivity = $sa->fetchAll();
}
}
$customers = $db->query("SELECT id, name FROM customers ORDER BY name")->fetchAll();
$statuses = ['pending','plating','printing','finishing','packing','completed','cancelled'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Orders — PrintFlow</title>
<link rel="stylesheet" href="assets/css/app.css">
<style>
@media print {
nav, .modal-overlay, form[method="GET"], .pagination,
.btn, button, .action-btn { display: none !important; }
body { background: #fff !important; color: #000 !important; font-size: 11pt; }
.page-content { padding: 0 !important; max-width: 100% !important; }
.panel, .track-card { border: 1px solid #ddd !important; box-shadow: none !important; }
table { width: 100% !important; border-collapse: collapse !important; }
th, td { border: 1px solid #ccc !important; padding: 6px 8px !important; font-size: 10pt; }
th { background: #f5f5f5 !important; }
.status-badge { border: 1px solid #999 !important; background: #eee !important; color: #000 !important; }
a { color: #000 !important; text-decoration: none !important; }
.track-info-grid { display: grid !important; grid-template-columns: repeat(3,1fr) !important; gap: 10px !important; }
.timeline { margin-top: 16px; border-top: 1px solid #ddd; padding-top: 12px; }
.timeline-list { list-style: none; padding: 0; }
.timeline-item { padding: 4px 0; border-bottom: 1px solid #eee; font-size: 10pt; }
.page-header::after { content: "Printed: " attr(data-print-date); display: block; font-size: 9pt; color: #666; margin-top: 4px; }
}
</style>
</head>
<body>
<?php renderNav('orders'); ?>
<div class="page-content">
<?php if ($msg): ?>
<div class="alert alert-<?= $msgType === 'error' ? 'error' : 'success' ?>"><?= $msgType === 'error' ? '❌' : '✅' ?> <?= e($msg) ?></div>
<?php endif; ?>
<?php if ($viewOrder): ?>
<!-- ── Single Order View ── -->
<div class="page-header">
<div class="page-header-title">
<h1>Order <?= e($viewOrder['order_number']) ?></h1>
<p>Order details and workflow history</p>
</div>
<div style="display:flex;gap:8px;align-items:center;">
<button onclick="window.print()" class="btn btn-secondary" style="display:flex;align-items:center;gap:6px;">🖨️ Print</button>
<a href="orders.php" class="btn btn-ghost">← Back to Orders</a>
</div>
</div>
<div class="track-card">
<div class="track-info">
<div class="track-info-grid">
<div class="track-info-item">
<div class="label">Customer</div>
<div class="value"><?= e($viewOrder['customer_name']) ?></div>
<div style="font-size:12px;color:var(--text-muted)"><?= e($viewOrder['customer_email']) ?></div>
</div>
<div class="track-info-item">
<div class="label">Status</div>
<div><span class="status-badge badge-<?= $viewOrder['status'] ?>"><?= statusLabel($viewOrder['status']) ?></span></div>
</div>
<div class="track-info-item">
<div class="label">Total</div>
<div class="value">IDR <?= number_format($viewOrder['total_price'], 0, ',', '.') ?></div>
<div style="font-size:12px;color:var(--text-muted)"><?= $viewOrder['quantity'] ?> × IDR <?= number_format($viewOrder['unit_price'], 0, ',', '.') ?></div>
</div>
<div class="track-info-item">
<div class="label">Description</div>
<div class="value" style="font-size:13px"><?= e($viewOrder['description']) ?></div>
</div>
<div class="track-info-item">
<div class="label">Created</div>
<div class="value" style="font-size:13px"><?= date('M j, Y', strtotime($viewOrder['created_at'])) ?></div>
</div>
<div class="track-info-item">
<div class="label">Due Date</div>
<div class="value" style="font-size:13px"><?= $viewOrder['due_date'] ? date('M j, Y', strtotime($viewOrder['due_date'])) : '—' ?></div>
</div>
<div class="track-info-item">
<div class="label">Machine</div>
<div class="value" style="font-size:13px"><?= $viewOrder['machine'] ? e($viewOrder['machine']) : '—' ?></div>
</div>
</div>
<?php if ($viewOrder['notes']): ?>
<div style="background:var(--bg);border-radius:8px;padding:12px 16px;font-size:13px;color:var(--text-muted)">
<strong>Notes:</strong> <?= e($viewOrder['notes']) ?>
</div>
<?php endif; ?>
<!-- Update Status -->
<form method="POST" style="margin-top:20px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;">
<input type="hidden" name="order_id" value="<?= $viewOrder['id'] ?>">
<input type="hidden" name="update_status" value="1">
<label class="form-label" style="margin:0">Update Status:</label>
<select name="status" class="form-control" style="width:auto;">
<?php foreach ($statuses as $st): ?>
<option value="<?= $st ?>" <?= $viewOrder['status']===$st ? 'selected':'' ?>><?= statusLabel($st) ?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="btn btn-primary btn-sm">Update →</button>
</form>
</div>
<!-- Activity Timeline -->
<div class="timeline">
<h3>📍 Activity History</h3>
<ul class="timeline-list">
<?php foreach ($viewActivity as $a): ?>
<li class="timeline-item done">
<div class="timeline-label"><?= statusLabel($a['status']) ?></div>
<div class="timeline-time"><?= $a['note'] ?: date('M j, Y g:i A', strtotime($a['created_at'])) ?></div>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
<?php else: ?>
<!-- ── Orders List ── -->
<div class="page-header">
<div class="page-header-title">
<h1>📋 Orders</h1>
<p><?= $total ?> total orders</p>
</div>
<div style="display:flex;gap:8px;align-items:center;">
<a href="orders.php?export=csv&status=<?= urlencode($statusFilter) ?>&q=<?= urlencode($search) ?>" class="btn btn-secondary" style="display:flex;align-items:center;gap:6px;" title="Export to CSV">
📥 Export CSV
</a>
<button onclick="window.print()" class="btn btn-secondary" style="display:flex;align-items:center;gap:6px;">🖨️ Print</button>
<button class="btn btn-primary" onclick="document.getElementById('newOrderModal').classList.remove('hidden')">➕ New Order</button>
</div>
</div>
<!-- Filters -->
<form method="GET" style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:20px;">
<input type="text" name="q" class="form-control" placeholder="Search orders..." value="<?= e($search) ?>" style="max-width:280px;">
<select name="status" class="form-control" style="width:auto;">
<option value="">All Statuses</option>
<?php foreach ($statuses as $st): ?>
<option value="<?= $st ?>" <?= $statusFilter===$st?'selected':'' ?>><?= statusLabel($st) ?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="btn btn-primary btn-sm">Filter</button>
<?php if ($search || $statusFilter): ?>
<a href="orders.php" class="btn btn-ghost btn-sm">Clear</a>
<?php endif; ?>
</form>
<!-- Table -->
<div class="panel">
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Order #</th>
<th>Customer</th>
<th>Description</th>
<th>Qty</th>
<th>Total</th>
<th>Status</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php if (empty($orders)): ?>
<tr><td colspan="8" style="text-align:center;padding:40px;color:var(--text-muted)">No orders found</td></tr>
<?php else: ?>
<?php foreach ($orders as $o): ?>
<tr>
<td><a href="orders.php?view=<?= $o['id'] ?>" style="color:var(--primary);font-weight:700"><?= e($o['order_number']) ?></a></td>
<td>
<div style="font-weight:600"><?= e($o['customer_name']) ?></div>
<div style="font-size:12px;color:var(--text-muted)"><?= e($o['customer_email']) ?></div>
</td>
<td style="max-width:200px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis"><?= e($o['description']) ?></td>
<td><?= $o['quantity'] ?></td>
<td>IDR <?= number_format($o['total_price'], 0, ',', '.') ?></td>
<td><span class="status-badge badge-<?= $o['status'] ?>"><?= statusLabel($o['status']) ?></span></td>
<td style="color:var(--text-muted);font-size:12.5px"><?= date('M j, Y', strtotime($o['created_at'])) ?></td>
<td>
<div style="display:flex;gap:6px;">
<a href="orders.php?view=<?= $o['id'] ?>" class="action-btn">View</a>
<form method="POST" style="display:inline" onsubmit="return confirm('Delete this order?')">
<input type="hidden" name="order_id" value="<?= $o['id'] ?>">
<input type="hidden" name="delete_order" value="1">
<button type="submit" class="action-btn danger">Delete</button>
</form>
</div>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<!-- Pagination -->
<?php if ($totalPages > 1): ?>
<div class="pagination">
<?php for ($i=1;$i<=$totalPages;$i++): ?>
<a href="?p=<?= $i ?>&status=<?= urlencode($statusFilter) ?>&q=<?= urlencode($search) ?>" class="page-btn <?= $i===$page?'active':'' ?>"><?= $i ?></a>
<?php endfor; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
</div>
<!-- New Order Modal -->
<div class="modal-overlay hidden" id="newOrderModal">
<div class="modal">
<div class="modal-header">
<h2>➕ New Order</h2>
<button class="modal-close" onclick="document.getElementById('newOrderModal').classList.add('hidden')">✕</button>
</div>
<form method="POST">
<input type="hidden" name="create_order" value="1">
<div class="modal-body">
<div class="form-group">
<label class="form-label" style="font-size:13px;font-weight:600;">Order Number <span style="color:#888;font-weight:400;">(leave blank to auto-generate)</span></label>
<div style="display:flex;gap:8px;align-items:center;">
<input type="text" name="order_number" id="orderNumberInput" class="form-control" placeholder="e.g. ORD-2024-001" style="font-weight:600;letter-spacing:0.5px;">
<button type="button" class="btn btn-ghost btn-sm" onclick="generateOrderNum()" style="white-space:nowrap;flex-shrink:0;">🔄 Generate</button>
</div>
<p style="font-size:11px;color:#888;margin-top:4px;">Enter a custom number or click Generate for an auto-number.</p>
</div>
<div class="form-group">
<label class="form-label">Customer *</label>
<select name="customer_id" class="form-control" required>
<option value="">— Select Customer —</option>
<?php foreach ($customers as $c): ?>
<option value="<?= $c['id'] ?>"><?= e($c['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label class="form-label">Description *</label>
<textarea name="description" class="form-control" rows="2" required placeholder="e.g. Cetak Brosur A4 Full Color"></textarea>
</div>
<div class="form-grid">
<div class="form-group">
<label class="form-label">Quantity</label>
<input type="number" name="quantity" class="form-control" value="1" min="1" required>
</div>
<div class="form-group">
<label class="form-label">Unit Price (IDR)</label>
<input type="number" name="unit_price" class="form-control" value="0" step="1" min="0">
</div>
</div>
<div class="form-grid">
<div class="form-group">
<label class="form-label">Due Date</label>
<input type="date" name="due_date" class="form-control">
</div>
<div class="form-group">
<label class="form-label">Machine</label>
<select id="machineSelect" class="form-control" onchange="handleMachineSelect(this)">
<option value="">— Select Machine —</option>
<option value="Speed Master 52">Speed Master 52</option>
<option value="Komori 428">Komori 428</option>
<option value="__manual__">Other (manual input)</option>
</select>
<!-- Always submitted; hidden when a preset is chosen -->
<input type="text" name="machine" id="machineInput" class="form-control" placeholder="Enter machine name..." style="margin-top:6px;display:none;">
</div>
</div>
<div class="form-group">
<label class="form-label">Notes</label>
<textarea name="notes" class="form-control" rows="2" placeholder="Optional notes..."></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-ghost" onclick="document.getElementById('newOrderModal').classList.add('hidden')">Cancel</button>
<button type="submit" class="btn btn-primary">Create Order →</button>
</div>
</form>
</div>
</div>
<script>
document.querySelector('.page-header') && document.querySelector('.page-header').setAttribute('data-print-date', new Date().toLocaleString());
<?php if ($action === 'new'): ?>
document.getElementById('newOrderModal').classList.remove('hidden');
<?php endif; ?>
function handleMachineSelect(sel) {
const input = document.getElementById('machineInput');
if (sel.value === '__manual__') {
input.style.display = 'block';
input.required = true;
input.value = '';
input.focus();
} else {
input.style.display = 'none';
input.required = false;
input.value = sel.value; // preset value passed via hidden input
}
}
// Sync machine value before form submit
document.addEventListener('DOMContentLoaded', function () {
const form = document.querySelector('#newOrderModal form');
if (form) {
form.addEventListener('submit', function () {
const sel = document.getElementById('machineSelect');
const input = document.getElementById('machineInput');
if (sel.value !== '__manual__') {
input.value = sel.value;
}
});
}
});
function generateOrderNum() {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, '0');
const d = String(now.getDate()).padStart(2, '0');
const rand = String(Math.floor(Math.random() * 900) + 100);
const num = `ORD-${y}${m}${d}-${rand}`;
document.getElementById('orderNumberInput').value = num;
document.getElementById('orderNumberInput').focus();
}
</script>
</body>
</html>