-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathucSellMedicine.cs
More file actions
468 lines (418 loc) · 19.2 KB
/
ucSellMedicine.cs
File metadata and controls
468 lines (418 loc) · 19.2 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
467
468
using DGVPrinterHelper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Pharmacy_Management_Sysytem.BusinessLogic;
using Pharmacy_Management_Sysytem.Models;
using Pharmacy_Management_Sysytem.Services;
namespace Pharmacy_Management_Sysytem
{
public partial class ucSellMedicine : UserControl
{
private readonly IMedicineService _medicineService;
private List<CartItem> _cartItems;
public ucSellMedicine()
{
InitializeComponent();
_medicineService = Program.Services.MedicineService;
_cartItems = new List<CartItem>();
InitializeCart();
// Add input validation for numeric fields
txtBoxNumsOfUnits.KeyPress += TxtBoxNumsOfUnits_KeyPress;
}
private void TxtBoxNumsOfUnits_KeyPress(object sender, KeyPressEventArgs e)
{
// Allow only digits, backspace, and delete
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
private void InitializeCart()
{
// Initialize the cart DataGridView
dataGridView1.Columns.Clear();
dataGridView1.Columns.Add("MedicineID", "Medicine ID");
dataGridView1.Columns.Add("MedicineName", "Medicine Name");
dataGridView1.Columns.Add("Quantity", "Quantity");
dataGridView1.Columns.Add("PricePerUnit", "Price Per Unit");
dataGridView1.Columns.Add("TotalPrice", "Total Price");
// Set column widths
dataGridView1.Columns[0].Width = 100;
dataGridView1.Columns[1].Width = 200;
dataGridView1.Columns[2].Width = 80;
dataGridView1.Columns[3].Width = 100;
dataGridView1.Columns[4].Width = 100;
}
private void RefreshCart()
{
dataGridView1.Rows.Clear();
foreach (var item in _cartItems)
{
dataGridView1.Rows.Add(
item.MedicineId,
item.MedicineName,
item.Quantity,
item.PricePerUnit.ToString("C"),
item.TotalPrice.ToString("C")
);
}
}
public class CartItem
{
public string MedicineId { get; set; }
public string MedicineName { get; set; }
public int Quantity { get; set; }
public decimal PricePerUnit { get; set; }
public decimal TotalPrice => Quantity * PricePerUnit;
}
private void ClearForm()
{
txtBoxMedicineID.Text = "";
txtBoxMedicineName.Text = "";
txtBoxMedicineNumber.Text = "";
txtBoxQuantity.Text = "";
txtBoxPricePerUnit.Text = "";
txtBoxNumsOfUnits.Text = "";
txtBoxTotalPrice.Text = "";
}
void deleteMedicine(int PurchaseID)
{
try
{
// TODO: Implement purchase deletion using PurchaseService
// For now, show a confirmation message
var result = MessageBox.Show($"Are you sure you want to delete purchase ID {PurchaseID}?",
"Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// TODO: Call PurchaseService.DeletePurchase(PurchaseID)
MessageBox.Show($"Purchase ID {PurchaseID} would be deleted (PurchaseService not implemented yet)",
"Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error deleting purchase: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ucSellMedicine_Load(object sender, EventArgs e)
{
listBox.Items.Clear();
try
{
var result = _medicineService.GetValidMedicines();
if (result.IsSuccess)
{
foreach (var medicine in result.Data)
{
listBox.Items.Add(medicine.MedicineName);
}
if (listBox.Items.Count > 0)
{
listBox.SelectedIndex = 0;
}
}
else
{
MessageBox.Show($"Error loading medicines: {result.ErrorMessage}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error loading medicines: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtBoxSearch_TextChanged(object sender, EventArgs e)
{
listBox.Items.Clear();
try
{
var result = _medicineService.GetMedicinesByName(txtBoxSearch.Text);
if (result.IsSuccess)
{
foreach (var medicine in result.Data)
{
listBox.Items.Add(medicine.MedicineName);
}
if (listBox.Items.Count > 0)
{
listBox.SelectedIndex = 0;
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Error searching medicines: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string selectedMedicineName = listBox.GetItemText(listBox.SelectedItem);
txtBoxMedicineName.Text = selectedMedicineName;
// Get medicine details by name
var medicinesResult = _medicineService.GetMedicinesByName(selectedMedicineName);
if (medicinesResult.IsSuccess && medicinesResult.Data.Count > 0)
{
var medicine = medicinesResult.Data.First();
// Populate all medicine details
txtBoxMedicineID.Text = medicine.MedicineId;
txtBoxMedicineNumber.Text = medicine.MedicineNumber;
txtBoxQuantity.Text = medicine.Quantity.ToString();
txtBoxPricePerUnit.Text = medicine.PricePerUnit.ToString();
// Clear and reset other fields
txtBoxNumsOfUnits.Text = "";
txtBoxTotalPrice.Text = "";
}
else
{
MessageBox.Show("Medicine details not found", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error loading medicine details: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtBoxNumsOfUnits_TextChanged(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtBoxNumsOfUnits.Text))
{
txtBoxTotalPrice.Text = "";
return;
}
// Validate that the input is a valid number
if (!int.TryParse(txtBoxNumsOfUnits.Text, out int units))
{
txtBoxTotalPrice.Text = "";
return;
}
// Validate that price per unit is available and valid
if (string.IsNullOrWhiteSpace(txtBoxPricePerUnit.Text) ||
!decimal.TryParse(txtBoxPricePerUnit.Text, out decimal pricePerUnit))
{
txtBoxTotalPrice.Text = "";
return;
}
// Calculate total price
decimal totalPrice = pricePerUnit * units;
txtBoxTotalPrice.Text = totalPrice.ToString("F2");
}
catch (Exception ex)
{
// If any error occurs, clear the total price
txtBoxTotalPrice.Text = "";
}
}
private void btnAddToCart_Click(object sender, EventArgs e)
{
try
{
// Validate required fields
if (string.IsNullOrWhiteSpace(txtBoxMedicineName.Text))
{
MessageBox.Show("Please select a medicine first", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (string.IsNullOrWhiteSpace(txtBoxNumsOfUnits.Text) || !int.TryParse(txtBoxNumsOfUnits.Text, out int units))
{
MessageBox.Show("Please enter a valid number of units", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (string.IsNullOrWhiteSpace(txtBoxQuantity.Text) || !int.TryParse(txtBoxQuantity.Text, out int availableQuantity))
{
MessageBox.Show("Unable to determine available quantity", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (units > availableQuantity)
{
MessageBox.Show($"Not enough stock! Available: {availableQuantity}, Requested: {units}",
"Insufficient Stock", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Parse price per unit safely
if (!decimal.TryParse(txtBoxPricePerUnit.Text, out decimal pricePerUnit))
{
MessageBox.Show("Invalid price per unit", "Validation Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Add item to cart
var cartItem = new CartItem
{
MedicineId = txtBoxMedicineID.Text,
MedicineName = txtBoxMedicineName.Text,
Quantity = units,
PricePerUnit = pricePerUnit
};
// Check if item already exists in cart
var existingItem = _cartItems.FirstOrDefault(x => x.MedicineId == cartItem.MedicineId);
if (existingItem != null)
{
// Update quantity if item already exists
existingItem.Quantity += cartItem.Quantity;
}
else
{
// Add new item to cart
_cartItems.Add(cartItem);
}
// Refresh the cart display
RefreshCart();
// Clear the form for next item
ClearForm();
MessageBox.Show($"Added {units} units of {txtBoxMedicineName.Text} to cart\nTotal: ${txtBoxTotalPrice.Text}",
"Added to Cart", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Error adding to cart: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnBuy_Click(object sender, EventArgs e)
{
try
{
// Check if cart is empty
if (_cartItems.Count == 0)
{
MessageBox.Show("Your cart is empty. Please add some medicines first.", "Empty Cart",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Calculate total cart value
decimal totalCartValue = _cartItems.Sum(item => item.TotalPrice);
int totalItems = _cartItems.Sum(item => item.Quantity);
// Show purchase summary
string purchaseSummary = $"Purchase Summary:\n\n";
foreach (var item in _cartItems)
{
purchaseSummary += $"• {item.MedicineName} - {item.Quantity} units - ${item.TotalPrice:F2}\n";
}
purchaseSummary += $"\nTotal Items: {totalItems}\nTotal Amount: ${totalCartValue:F2}";
var result = MessageBox.Show($"{purchaseSummary}\n\nDo you want to complete this purchase?",
"Confirm Purchase", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// TODO: Implement actual purchase completion with PurchaseService
// For now, just clear the cart and show success message
// Print the bill before clearing the cart
PrintBill();
_cartItems.Clear();
RefreshCart();
ClearForm();
MessageBox.Show("Purchase completed successfully!\n\nThank you for your business!",
"Purchase Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error completing purchase: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void PrintBill()
{
try
{
// Use the existing cart DataGridView for printing
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("No items in cart to print.", "Print Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Configure the printer with simpler settings
DGVPrinter print = new DGVPrinter();
print.Title = "PHARMACY MANAGEMENT SYSTEM";
print.SubTitle = $"Bill Date: {DateTime.Now:dd/MM/yyyy HH:mm}";
print.PageNumbers = true;
print.PorportionalColumns = true;
print.Footer = $"Total Amount: {_cartItems.Sum(item => item.TotalPrice):C}";
// Print the cart DataGridView
print.PrintDataGridView(dataGridView1);
}
catch (Exception ex)
{
// If DGVPrinter fails, show a simple text-based bill
ShowTextBill();
}
}
private void ShowTextBill()
{
try
{
string billText = "PHARMACY MANAGEMENT SYSTEM\n";
billText += "================================\n";
billText += $"Bill Date: {DateTime.Now:dd/MM/yyyy HH:mm}\n\n";
billText += "Medicine ID\tMedicine Name\t\tQty\tPrice\tTotal\n";
billText += "--------------------------------------------------------\n";
foreach (var item in _cartItems)
{
billText += $"{item.MedicineId}\t{item.MedicineName}\t\t{item.Quantity}\t{item.PricePerUnit:C}\t{item.TotalPrice:C}\n";
}
billText += "--------------------------------------------------------\n";
billText += $"TOTAL AMOUNT: {_cartItems.Sum(item => item.TotalPrice):C}\n";
billText += "================================\n";
billText += "Thank you for your business!";
MessageBox.Show(billText, "Bill Receipt", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Error displaying bill: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
if (dataGridView1.SelectedRows.Count == 0)
{
MessageBox.Show("Please select a medicine to remove from cart.", "No Selection",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
var selectedRow = dataGridView1.SelectedRows[0];
string medicineId = selectedRow.Cells["MedicineID"].Value.ToString();
string medicineName = selectedRow.Cells["MedicineName"].Value.ToString();
var result = MessageBox.Show($"Are you sure you want to remove '{medicineName}' from the cart?",
"Confirm Removal", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
// Remove item from cart
_cartItems.RemoveAll(item => item.MedicineId == medicineId);
RefreshCart();
MessageBox.Show($"'{medicineName}' has been removed from the cart.", "Item Removed",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error removing item from cart: {ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}