-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
355 lines (326 loc) · 19.6 KB
/
Copy pathMainForm.cs
File metadata and controls
355 lines (326 loc) · 19.6 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
using System.Diagnostics;
using System.Drawing.Printing;
namespace FMPReceiptPrinter;
public sealed class MainForm : Form
{
private readonly AppState _state;
private readonly List<ReceiptTemplate> _templates;
private readonly ReceiptPreviewControl _preview = new() { Dock = DockStyle.Fill };
private readonly NumericUpDown _receiptNo = new() { Minimum = 1, Maximum = 99999, Width = 90 };
private readonly DateTimePicker _date = new() { Format = DateTimePickerFormat.Short, Width = 120 };
private readonly TextBox _customer = new() { Width = 260 };
private readonly TextBox _address = new() { Width = 260 };
private readonly ComboBox _terms = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 120 };
private readonly DateTimePicker _due = new() { Format = DateTimePickerFormat.Short, Width = 120 };
private readonly NumericUpDown _deliveryFee = new() { DecimalPlaces = 2, Maximum = 1000000, ThousandsSeparator = true, Width = 110 };
private readonly TextBox _preparedBy = new() { Width = 160 };
private readonly Label _subtotal = new() { AutoSize = true, Font = new Font("Segoe UI", 10, FontStyle.Bold) };
private readonly Label _total = new() { AutoSize = true, Font = new Font("Segoe UI", 12, FontStyle.Bold), ForeColor = Color.FromArgb(8,126,175) };
private readonly DataGridView _items = new() { AllowUserToAddRows = false, AllowUserToDeleteRows = false, RowHeadersVisible = false, AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, Width = 420, Height = 245 };
private readonly ComboBox _templateCombo = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 220 };
private readonly ComboBox _printerCombo = new() { DropDownStyle = ComboBoxStyle.DropDownList, Width = 245 };
private readonly Label _printerStatus = new() { AutoSize = true, Padding = new Padding(0,6,0,0) };
private readonly TextBox _signaturePath = new() { Width = 250, ReadOnly = true };
private readonly CheckBox _useSignature = new() { Text = "Place uploaded signature on receipt", AutoSize = true };
private readonly Dictionary<ReceiptSlot, CheckBox> _slotChecks = new();
private Button _printPreviewButton = null!;
private Button _printButton = null!;
private ReceiptTemplate CurrentTemplate => (ReceiptTemplate?)_templateCombo.SelectedItem ?? _templates[0];
public MainForm()
{
Storage.Initialize();
_state = Storage.LoadState();
_templates = Storage.LoadTemplates();
if (_templates.Count == 0) _templates.Add(new());
Text = "ARCWorks Simple Receipt Printer";
MinimumSize = new Size(1120, 720);
Size = new Size(1280, 820);
StartPosition = FormStartPosition.CenterScreen;
Font = new Font("Segoe UI", 9f);
Icon = System.Drawing.Icon.ExtractAssociatedIcon(Application.ExecutablePath);
BuildUi();
NewReceipt();
}
private void BuildUi()
{
var toolbar = new FlowLayoutPanel { Dock = DockStyle.Top, Height = 48, Padding = new Padding(10,8,10,6), BackColor = Color.FromArgb(245,247,249), WrapContents = false };
if (Icon is not null)
{
toolbar.Controls.Add(new PictureBox
{
Image = Icon.ToBitmap(),
Size = new Size(32, 32),
SizeMode = PictureBoxSizeMode.Zoom,
Margin = new Padding(0, 0, 8, 0)
});
}
toolbar.Controls.Add(MakeButton("New Receipt", (_,_) => NewReceipt()));
toolbar.Controls.Add(MakeButton("Save JSON", (_,_) => SaveReceipt(true)));
_printPreviewButton = MakeButton("Print Preview", (_,_) => ShowPrintPreview());
_printButton = MakeButton("Print", (_,_) => PrintReceipt());
toolbar.Controls.Add(_printPreviewButton);
toolbar.Controls.Add(_printButton);
toolbar.Controls.Add(MakeButton("Open Receipts", (_,_) => OpenFolder(Storage.ReceiptFolder)));
toolbar.Controls.Add(MakeButton("Import Template", (_,_) => ImportTemplate()));
toolbar.Controls.Add(MakeButton("Open Templates", (_,_) => OpenFolder(Storage.TemplateFolder)));
Controls.Add(toolbar);
var split = new SplitContainer { Dock = DockStyle.Fill, SplitterDistance = 500, FixedPanel = FixedPanel.Panel1, Panel1MinSize = 470 };
Controls.Add(split);
split.BringToFront();
var editor = new Panel { Dock = DockStyle.Fill, AutoScroll = true, Padding = new Padding(14) };
split.Panel1.Controls.Add(editor);
split.Panel2.Controls.Add(_preview);
var flow = new FlowLayoutPanel { Dock = DockStyle.Top, AutoSize = true, FlowDirection = FlowDirection.TopDown, WrapContents = false };
editor.Controls.Add(flow);
flow.Controls.Add(Section("Receipt template", FieldRow(("Template", _templateCombo))));
_templateCombo.DataSource = _templates;
_templateCombo.DisplayMember = nameof(ReceiptTemplate.Name);
var lastTemplate = _templates.FindIndex(x => string.Equals(x.Name, _state.LastTemplate, StringComparison.OrdinalIgnoreCase));
if (lastTemplate >= 0) _templateCombo.SelectedIndex = lastTemplate;
_templateCombo.SelectedIndexChanged += (_,_) =>
{
_state.LastTemplate = CurrentTemplate.Name;
Storage.SaveState(_state);
ConfigureRows();
RefreshPreview();
};
var printerRow = new FlowLayoutPanel { AutoSize=true, Width=430, WrapContents=false };
printerRow.Controls.Add(_printerCombo); printerRow.Controls.Add(MakeSmallButton("Refresh", (_,_) => RefreshPrinters())); printerRow.Controls.Add(_printerStatus);
flow.Controls.Add(Section("Printer connection", printerRow));
_printerCombo.SelectedIndexChanged += (_,_) => UpdatePrinterStatus();
RefreshPrinters();
flow.Controls.Add(Section("Receipt details",
FieldRow(("Receipt no.", _receiptNo), ("Date", _date)),
FieldRow(("Customer", _customer)),
FieldRow(("Address", _address)),
FieldRow(("Terms", _terms), ("Due date", _due))));
_terms.Items.AddRange(["Cash", "7 Days", "14 Days", "Custom"]);
_terms.SelectedIndexChanged += (_,_) => UpdateDueDate();
ConfigureGrid();
var itemSection = Section("Items", _items);
itemSection.Width = 455;
flow.Controls.Add(itemSection);
var signatureButtons = new FlowLayoutPanel { AutoSize=true, Width=430, WrapContents=false };
signatureButtons.Controls.Add(_signaturePath);
signatureButtons.Controls.Add(MakeSmallButton("Upload signature", (_,_) => UploadSignature()));
flow.Controls.Add(Section("Totals and e-signature",
FieldRow(("Delivery fee", _deliveryFee), ("Prepared by", _preparedBy)),
signatureButtons, _useSignature,
FieldRow(("Subtotal", _subtotal), ("Total", _total))));
_useSignature.CheckedChanged += (_,_) => RefreshPreview();
var slots = new FlowLayoutPanel { AutoSize = true, WrapContents = true, Width = 430 };
foreach (var slot in Enum.GetValues<ReceiptSlot>())
{
var cb = new CheckBox { Text = SlotName(slot), AutoSize = true, Margin = new Padding(4,4,14,4), Checked = slot == ReceiptSlot.TopLeft };
cb.CheckedChanged += (_,_) => RefreshPreview();
_slotChecks[slot] = cb; slots.Controls.Add(cb);
}
slots.Controls.Add(MakeSmallButton("All", (_,_) => SetAllSlots(true)));
slots.Controls.Add(MakeSmallButton("Clear", (_,_) => SetAllSlots(false)));
flow.Controls.Add(Section("Print positions", slots));
foreach (var control in new Control[] { _receiptNo, _date, _customer, _address, _due, _deliveryFee, _preparedBy })
{
if (control is TextBox tb) tb.TextChanged += (_,_) => RefreshPreview();
else if (control is NumericUpDown nud) nud.ValueChanged += (_,_) => { Recalculate(); RefreshPreview(); };
else if (control is DateTimePicker dt) dt.ValueChanged += (_,_) => RefreshPreview();
}
Shown += (_,_) =>
{
split.SplitterDistance = Math.Min(500, Math.Max(split.Panel1MinSize, ClientSize.Width - 620));
flow.Width = 455;
flow.Height = flow.PreferredSize.Height + 12;
editor.AutoScrollMinSize = new Size(0, flow.Height + 28);
flow.PerformLayout(); editor.PerformLayout();
};
}
private void ConfigureGrid()
{
_items.Columns.Add(new DataGridViewTextBoxColumn { Name="Quantity", HeaderText="Qty", FillWeight=18 });
_items.Columns.Add(new DataGridViewTextBoxColumn { Name="Description", HeaderText="Description", FillWeight=47 });
_items.Columns.Add(new DataGridViewTextBoxColumn { Name="UnitPrice", HeaderText="Unit Price", FillWeight=22, DefaultCellStyle = new DataGridViewCellStyle { Format="N2" } });
_items.Columns.Add(new DataGridViewTextBoxColumn { Name="Amount", HeaderText="Amount", FillWeight=23, ReadOnly=true, DefaultCellStyle = new DataGridViewCellStyle { Format="N2", BackColor=Color.FromArgb(245,247,249) } });
_items.CellEndEdit += (_,e) => { UpdateAmount(e.RowIndex); Recalculate(); RefreshPreview(); };
_items.RowsAdded += (_,_) => Recalculate();
}
private void ConfigureRows()
{
if (_items.Columns.Count == 0) return;
var existing = ReadItems().ToList();
_items.Rows.Clear();
var count = Math.Max(4, CurrentTemplate.ItemRows);
_items.Rows.Add(count);
for (var i=0; i<Math.Min(count, existing.Count); i++)
{
_items.Rows[i].Cells[0].Value = existing[i].Quantity == 0 ? null : existing[i].Quantity;
_items.Rows[i].Cells[1].Value = existing[i].Description;
_items.Rows[i].Cells[2].Value = existing[i].UnitPrice == 0 ? null : existing[i].UnitPrice;
UpdateAmount(i);
}
}
private void NewReceipt()
{
_receiptNo.Value = Math.Max(1, _state.LastReceiptNumber + 1);
_date.Value = DateTime.Today;
_customer.Clear(); _address.Clear(); _preparedBy.Clear(); _deliveryFee.Value = 0;
_terms.SelectedItem = "7 Days"; _due.Value = DateTime.Today.AddDays(7);
ConfigureRows(); Recalculate(); RefreshPreview();
}
private ReceiptData ReadReceipt() => new()
{
ReceiptNumber = (int)_receiptNo.Value, Date = _date.Value.Date, Customer = _customer.Text.Trim(), Address = _address.Text.Trim(),
Terms = _terms.Text, DueDate = _due.Value.Date, DeliveryFee = _deliveryFee.Value, PreparedBy = _preparedBy.Text.Trim(),
UseESignature = _useSignature.Checked, SignatureFile = _signaturePath.Text, Items = ReadItems().ToList()
};
private IEnumerable<ReceiptItem> ReadItems()
{
foreach (DataGridViewRow row in _items.Rows)
{
var qty = DecimalValue(row.Cells[0].Value); var description = Convert.ToString(row.Cells[1].Value)?.Trim() ?? ""; var price = DecimalValue(row.Cells[2].Value);
if (qty != 0 || price != 0 || description.Length > 0) yield return new ReceiptItem { Quantity=qty, Description=description, UnitPrice=price };
}
}
private void UpdateAmount(int rowIndex)
{
if (rowIndex < 0 || rowIndex >= _items.Rows.Count) return;
var row = _items.Rows[rowIndex]; row.Cells[3].Value = DecimalValue(row.Cells[0].Value) * DecimalValue(row.Cells[2].Value);
}
private void Recalculate()
{
var receipt = ReadReceipt(); _subtotal.Text = receipt.Subtotal.ToString("N2"); _total.Text = receipt.Total.ToString("N2");
}
private void RefreshPreview()
{
if (_templates.Count == 0 || _items.Columns.Count == 0) return;
Recalculate(); _preview.Receipt = ReadReceipt(); _preview.Template = CurrentTemplate; _preview.Slots = SelectedSlots(); _preview.Invalidate();
}
private HashSet<ReceiptSlot> SelectedSlots() => _slotChecks.Where(x => x.Value.Checked).Select(x => x.Key).ToHashSet();
private bool ValidatePrint()
{
if (SelectedSlots().Count == 0) { MessageBox.Show("Select at least one print position.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information); return false; }
if (string.IsNullOrWhiteSpace(_customer.Text) && MessageBox.Show("Customer is blank. Continue?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return false;
if (_printerCombo.SelectedItem is null) { MessageBox.Show("No installed printer is available. Connect or install a printer, then click Refresh.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; }
return true;
}
private string SaveReceipt(bool notify)
{
var receipt = ReadReceipt(); var path = Storage.SaveReceipt(receipt);
_state.LastReceiptNumber = Math.Max(_state.LastReceiptNumber, receipt.ReceiptNumber); _state.LastTemplate = CurrentTemplate.Name; Storage.SaveState(_state);
if (notify) MessageBox.Show($"Saved to:\n{path}", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
return path;
}
private PrintDocument CreatePrintDocument()
{
var receipt = ReadReceipt(); var template = CurrentTemplate; var slots = SelectedSlots();
var doc = new PrintDocument { DocumentName = $"Delivery Receipt {receipt.ReceiptNumber:00000}", OriginAtMargins = false };
doc.PrinterSettings.PrinterName = Convert.ToString(_printerCombo.SelectedItem) ?? "";
doc.DefaultPageSettings.Landscape = false;
doc.DefaultPageSettings.PaperSize = new PaperSize("216 x 279 mm", (int)Math.Round(ReceiptRenderer.PageWidth), (int)Math.Round(ReceiptRenderer.PageHeight));
doc.DefaultPageSettings.Margins = new Margins(0,0,0,0);
doc.PrintPage += (_,e) =>
{
if (e.Graphics is not null)
{
// GDI starts at the printer's printable origin. Move back to the
// physical page origin so left/right hardware margins stay balanced.
var state = e.Graphics.Save();
e.Graphics.TranslateTransform(-e.PageSettings.HardMarginX, -e.PageSettings.HardMarginY);
ReceiptRenderer.DrawPage(
e.Graphics,
new RectangleF(0, 0, ReceiptRenderer.PageWidth, ReceiptRenderer.PageHeight),
receipt,
template,
slots,
showCutGuides: false);
e.Graphics.Restore(state);
}
e.HasMorePages=false;
};
return doc;
}
private void ShowPrintPreview()
{
if (!ValidatePrint()) return;
using var doc = CreatePrintDocument(); using var dialog = new PrintPreviewDialog { Document=doc, Width=1100, Height=800, StartPosition=FormStartPosition.CenterParent };
dialog.ShowDialog(this);
}
private void PrintReceipt()
{
if (!ValidatePrint()) return;
using var doc = CreatePrintDocument(); using var dialog = new PrintDialog { Document=doc, UseEXDialog=true };
if (dialog.ShowDialog(this) == DialogResult.OK) { SaveReceipt(false); doc.Print(); MessageBox.Show("Receipt sent to the printer and saved as JSON.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information); }
}
private void UpdateDueDate()
{
if (_terms.Text == "Cash") _due.Value = _date.Value.Date;
else if (_terms.Text == "7 Days") _due.Value = _date.Value.Date.AddDays(7);
else if (_terms.Text == "14 Days") _due.Value = _date.Value.Date.AddDays(14);
RefreshPreview();
}
private void SetAllSlots(bool value) { foreach (var cb in _slotChecks.Values) cb.Checked=value; RefreshPreview(); }
private void RefreshPrinters()
{
var selected = Convert.ToString(_printerCombo.SelectedItem);
_printerCombo.Items.Clear();
foreach (string printer in PrinterSettings.InstalledPrinters) _printerCombo.Items.Add(printer);
if (!string.IsNullOrWhiteSpace(selected) && _printerCombo.Items.Contains(selected)) _printerCombo.SelectedItem = selected;
else if (_printerCombo.Items.Count > 0) _printerCombo.SelectedIndex = 0;
UpdatePrinterStatus();
}
private void UpdatePrinterStatus()
{
var isReady = false;
if (_printerCombo.SelectedItem is not null)
{
var settings = new PrinterSettings { PrinterName = Convert.ToString(_printerCombo.SelectedItem) ?? "" };
isReady = settings.IsValid;
}
_printerStatus.Text = isReady ? "Ready" : "Not available";
_printerStatus.ForeColor = isReady ? Color.ForestGreen : Color.Firebrick;
_printPreviewButton.Enabled = isReady;
_printButton.Enabled = isReady;
}
private void UploadSignature()
{
using var dialog = new OpenFileDialog { Title="Upload signature image", Filter="Image files|*.png;*.jpg;*.jpeg;*.bmp" };
if (dialog.ShowDialog(this) != DialogResult.OK) return;
try { _signaturePath.Text = Storage.ImportSignature(dialog.FileName); _useSignature.Checked=true; RefreshPreview(); }
catch (Exception ex) { MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
private void ImportTemplate()
{
using var dialog = new OpenFileDialog { Title="Import receipt template", Filter="Receipt template JSON|*.json" };
if (dialog.ShowDialog(this) != DialogResult.OK) return;
try
{
Storage.ImportTemplate(dialog.FileName);
var updated = Storage.LoadTemplates();
_templates.Clear();
_templates.AddRange(updated);
if (_templates.Count == 0) _templates.Add(new());
_templateCombo.DataSource = null; _templateCombo.DataSource = _templates; _templateCombo.DisplayMember = nameof(ReceiptTemplate.Name);
MessageBox.Show("Template imported.", Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex) { MessageBox.Show($"Could not import template:\n{ex.Message}", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
private static decimal DecimalValue(object? value) => decimal.TryParse(Convert.ToString(value), out var result) ? result : 0;
private static string SlotName(ReceiptSlot slot) => slot switch { ReceiptSlot.TopLeft=>"Top left", ReceiptSlot.TopRight=>"Top right", ReceiptSlot.BottomLeft=>"Bottom left", _=>"Bottom right" };
private static Button MakeButton(string text, EventHandler click) { var b=new Button{Text=text,AutoSize=true,Height=30,Margin=new Padding(3)}; b.Click+=click; return b; }
private static Button MakeSmallButton(string text, EventHandler click) { var b=new Button{Text=text,AutoSize=true,Height=26,Margin=new Padding(3,1,3,1)}; b.Click+=click; return b; }
private static void OpenFolder(string path) { Directory.CreateDirectory(path); Process.Start(new ProcessStartInfo("explorer.exe", path) { UseShellExecute=true }); }
private static FlowLayoutPanel FieldRow(params (string Label, Control Control)[] fields)
{
var row = new FlowLayoutPanel { AutoSize=true, Width=430, WrapContents=false, Margin=new Padding(0,2,0,2) };
foreach (var field in fields) { row.Controls.Add(new Label { Text=field.Label, AutoSize=true, Width=78, TextAlign=ContentAlignment.MiddleLeft, Padding=new Padding(0,6,0,0) }); row.Controls.Add(field.Control); }
return row;
}
private static GroupBox Section(string title, params Control[] controls)
{
var box = new GroupBox { Text=title, AutoSize=false, Width=455, Padding=new Padding(10), Margin=new Padding(0,0,0,8) };
var flow = new FlowLayoutPanel { AutoSize=true, Width=430, FlowDirection=FlowDirection.TopDown, WrapContents=false, Location=new Point(10,22) };
flow.Controls.AddRange(controls);
flow.Height = flow.PreferredSize.Height;
box.Height = flow.Height + 34;
box.Controls.Add(flow);
return box;
}
}