Repository navigation
Expand file tree
/
Copy pathDashboardPanel.java
More file actions
2126 lines (1990 loc) · 109 KB
/
Copy pathDashboardPanel.java
File metadata and controls
2126 lines (1990 loc) · 109 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.plaf.basic.BasicScrollBarUI;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
public class DashboardPanel extends JPanel {
private static final Color PINK=new Color(0xC9,0x63,0x7A),WHITE=Color.WHITE;
private static final Color DARK=new Color(0x21,0x21,0x21),GRAY=new Color(0x75,0x75,0x75);
private static final Color ALT=new Color(0xFF,0xF9,0xFA),BRD=new Color(0xF0,0xE0,0xE6);
private static final Color SEARCH_BRD=new Color(0xED,0xD5,0xDC),TBL_BRD=new Color(0xF5,0xE8,0xEC);
private static final Color TBL_HDR_BG=new Color(0xFF,0xF5,0xF7),TBL_HDR_FG=new Color(0x8B,0x45,0x58);
private static final Color TBL_HDR_BR=new Color(0xF0,0xD8,0xDF);
private static final Color CARD1_BG=new Color(0xFF,0xF0,0xF5),CARD2_BG=new Color(0xFF,0xFB,0xF0);
private static final Color CARD3_BG=new Color(0xF5,0xF0,0xFF),CARD4_BG=new Color(0xF0,0xFF,0xF5);
private static final Color BADGE_GREEN_BG=new Color(0xE8,0xF5,0xE9),BADGE_ORANGE_BG=new Color(0xFF,0xF3,0xE0);
private static final Color BADGE_ORANGE_FG=new Color(0xE6,0x51,0x00);
private static final Color GREEN=new Color(0x2E,0x7D,0x32),ORANGE=new Color(0xFF,0x8F,0x00);
private static final Color RED=new Color(0xD3,0x2F,0x2F);
private static final Font F12=new Font("Segoe UI",Font.PLAIN,12);
private static final Font FB12=new Font("Segoe UI",Font.BOLD,12);
private static final Font F13=new Font("Segoe UI",Font.PLAIN,13);
private static final Font FB13=new Font("Segoe UI",Font.BOLD,13);
private static final Font FB16=new Font("Segoe UI",Font.BOLD,16);
private static final Font FB28=new Font("Segoe UI",Font.BOLD,28);
private static DefaultTableModel sharedTableModel;
private static JTable sharedTable;
private static int currentPage = 1;
private JTable medicinesTable;
private JLabel showingLabel;
private JLabel totalLbl,expLbl,lowLbl,revLbl;
private JPanel pagPanel;
private StockOverviewPanel stockChartPanel;
private java.util.function.IntConsumer navigator;
private Timer expirySweepTimer;
static final int RPP=5;
private String[] cols={"ID","Medicine Name","Category","Stock","Price (\u20b9)","Expiry Date","Status","Action"};
private static void initializeSharedTable() {
if(sharedTableModel != null && sharedTable != null) return;
String[] columns = {"ID","Medicine Name","Category","Stock","Price (\u20b9)","Expiry Date","Status","Action"};
sharedTableModel = new DefaultTableModel(columns, 0){
public boolean isCellEditable(int r, int c){ return c == 7; }
};
loadMedicinesFromDatabase();
sharedTable = new JTable(sharedTableModel);
}
private static void loadMedicinesFromDatabase() {
archiveExpiredMedicines();
Vector<Vector> data = sharedTableModel.getDataVector();
data.clear();
for(Object[] row:DatabaseManager.getAllMedicines()){
Vector<Object> values=new Vector<>();
for(Object value:row) values.add(value);
data.add(values);
}
sharedTableModel.fireTableDataChanged();
}
private static void archiveExpiredMedicines() {
for(Object[] row:DatabaseManager.getAllMedicines()){
LocalDate expiry=parseExpiryDate(String.valueOf(row[5]));
if(expiry!=null&&expiry.isBefore(LocalDate.now())){
DatabaseManager.archiveExpiredMedicine(Integer.parseInt(String.valueOf(row[0])));
}
}
}
public DashboardPanel() {
setLayout(new BorderLayout()); setOpaque(false);
initializeSharedTable();
initModel();
startExpirySweepTimer();
JPanel top=new JPanel(new BorderLayout()); top.setOpaque(false);
top.add(buildDashboardSummary(),BorderLayout.NORTH);
JPanel mid=new JPanel(new BorderLayout(16,0)); mid.setOpaque(false);
mid.setBorder(BorderFactory.createEmptyBorder(20,0,0,0));
mid.add(buildTableSection(),BorderLayout.CENTER);
mid.add(buildRightPanel(),BorderLayout.EAST);
top.add(mid,BorderLayout.CENTER);
add(top,BorderLayout.CENTER);
}
private void startExpirySweepTimer() {
expirySweepTimer=new Timer(60*60*1000,e->{
loadMedicinesFromDatabase();
refreshTable();
updateStats();
});
expirySweepTimer.start();
}
void setNavigator(java.util.function.IntConsumer navigator) {
this.navigator = navigator;
}
private void navigateTo(int index) {
if(navigator != null) navigator.accept(index);
}
private void initModel() {
styleTable(sharedTable);
TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(sharedTableModel);
sharedTable.setRowSorter(sorter);
refreshTable();
}
void refreshTable(){
int totalRows = sharedTableModel.getRowCount();
int start = (currentPage - 1) * RPP;
int end = Math.min(start + RPP, totalRows);
TableRowSorter<DefaultTableModel> sorter = (TableRowSorter<DefaultTableModel>) sharedTable.getRowSorter();
sorter.setRowFilter(new RowFilter<DefaultTableModel, Object>() {
public boolean include(Entry e) {
int row = (int) e.getIdentifier();
return row >= start && row < end;
}
});
if(showingLabel != null) {
showingLabel.setText("Showing " + (start + 1) + " to " + end + " of " + totalRows + " entries");
}
if(pagPanel != null) refreshPagination();
}
static String status(int s){return s>20?"In Stock":s>=10?"Low Stock":"Critical";}
private JPanel buildStatCards() {
JPanel row=new JPanel(new GridLayout(1,4,12,0)); row.setOpaque(false);
row.setPreferredSize(new Dimension(0,130));
row.setMinimumSize(new Dimension(0,120));
totalLbl=new JLabel(String.valueOf(sharedTableModel.getRowCount()));
expLbl=new JLabel(String.valueOf(getExpiringSoonRows().size()));
lowLbl=new JLabel(String.valueOf(getLowStockRows().size()));
revLbl=new JLabel("\u20b9"+String.format("%.2f",DatabaseManager.getTotalRevenue()));
JPanel totalCard=statCard(statIcon(0,new Color(0xFF,0x98,0x00)),"Total Medicines",totalLbl,new Color(0xFF,0x98,0x00),"All medicines in stock",new Color(0x4C,0xAF,0x50),CARD1_BG);
makeClickable(totalCard,()->navigateTo(1));
row.add(totalCard);
JPanel expCard=statCard(statIcon(1,new Color(0xFF,0xB3,0x00)),"Expiring Soon",expLbl,new Color(0xFF,0xB3,0x00),"Red: 1 month, Yellow: 2 months",new Color(0xFF,0x98,0x00),CARD2_BG);
makeClickable(expCard,this::showExpiryTabs);
row.add(expCard);
JPanel lowCard=statCard(statIcon(2,new Color(0x7B,0x1F,0xA2)),"Low Stock",lowLbl,new Color(0x7B,0x1F,0xA2),"Stock below minimum",new Color(0x9E,0x9E,0x9E),CARD3_BG);
makeClickable(lowCard,()->showMedicineList("Low Stock Medicines",getLowStockRows()));
row.add(lowCard);
JPanel revenueCard=statCard(statIcon(3,GREEN),"Total Revenue",revLbl,GREEN,"This Month",new Color(0x4C,0xAF,0x50),CARD4_BG);
makeClickable(revenueCard,this::showRevenueHistory);
row.add(revenueCard);
return row;
}
private JPanel buildDashboardSummary() {
JPanel wrap=new JPanel();
wrap.setLayout(new BoxLayout(wrap,BoxLayout.Y_AXIS));
wrap.setOpaque(false);
JPanel actions=new JPanel(new FlowLayout(FlowLayout.RIGHT,0,0));
actions.setOpaque(false);
actions.setBorder(BorderFactory.createEmptyBorder(12,0,0,0));
JButton reportStatus=pinkBtn("Report Status");
reportStatus.addActionListener(e->{
stockChartPanel.setVisible(true);
stockChartPanel.restartAnimation();
wrap.revalidate();
wrap.repaint();
});
actions.add(reportStatus);
stockChartPanel=new StockOverviewPanel();
stockChartPanel.setVisible(false);
stockChartPanel.setAlignmentX(0f);
stockChartPanel.setCloseAction(()->{
stockChartPanel.setVisible(false);
wrap.revalidate();
wrap.repaint();
});
sharedTableModel.addTableModelListener(e->stockChartPanel.refreshData());
wrap.add(buildStatCards());
wrap.add(actions);
wrap.add(Box.createVerticalStrut(12));
wrap.add(stockChartPanel);
return wrap;
}
private JPanel statCard(Icon icon,String label,JLabel valLbl,Color ic,String sub,Color sc,Color bg) {
JPanel c=new JPanel(){
protected void paintComponent(Graphics g){
Graphics2D g2=(Graphics2D)g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(new Color(0xC9,0x63,0x7A,20));
g2.fill(new RoundRectangle2D.Float(2,4,getWidth()-4,getHeight()-4,16,16));
g2.setColor(bg);
g2.fill(new RoundRectangle2D.Float(0,0,getWidth(),getHeight()-2,16,16));
g2.setColor(BRD);
g2.draw(new RoundRectangle2D.Float(0,0,getWidth()-1,getHeight()-3,16,16));
g2.dispose();
}
};
c.setLayout(new BoxLayout(c,BoxLayout.Y_AXIS)); c.setOpaque(false);
c.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
JLabel il=new JLabel(icon); il.setFont(new Font("Segoe UI Emoji",Font.PLAIN,24));
il.setForeground(ic); il.setAlignmentX(0f);
valLbl.setFont(FB28); valLbl.setForeground(DARK); valLbl.setAlignmentX(0f);
JLabel ll=new JLabel(label); ll.setFont(F13); ll.setForeground(GRAY); ll.setAlignmentX(0f);
JLabel sl=new JLabel(sub); sl.setFont(FB12); sl.setForeground(sc); sl.setAlignmentX(0f);
c.add(il);c.add(Box.createVerticalStrut(4));c.add(valLbl);
c.add(Box.createVerticalStrut(2));c.add(ll);c.add(Box.createVerticalStrut(2));c.add(sl);
return c;
}
private JPanel buildTableSection() {
JPanel sec=new JPanel(new BorderLayout(0,10)); sec.setOpaque(false);
JPanel hdr=new JPanel(new BorderLayout()); hdr.setOpaque(false);
JLabel title=new JLabel(" Medicine Inventory"); title.setFont(FB16); title.setForeground(DARK);
title.setIcon(sectionIcon(0)); title.setIconTextGap(6);
JButton addBtn=pinkBtn("+ Add Medicine");
addBtn.addActionListener(e->showAddDialog());
hdr.add(title,BorderLayout.WEST); hdr.add(exportButtons(addBtn),BorderLayout.EAST);
sec.add(hdr,BorderLayout.NORTH);
JPanel body=new JPanel(new BorderLayout(0,8)); body.setOpaque(false);
JTextField search=new JTextField(" Search medicine by name, category or company...");
search.setFont(F13); search.setForeground(new Color(0xAA,0xAA,0xAA));
search.setPreferredSize(new Dimension(0,42));
search.setBorder(BorderFactory.createCompoundBorder(
new AbstractBorder(){public void paintBorder(Component c,Graphics g,int x,int y,int w,int h){
Graphics2D g2=(Graphics2D)g.create();g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(SEARCH_BRD);g2.draw(new RoundRectangle2D.Float(x,y,w-1,h-1,50,50));g2.dispose();}
public Insets getBorderInsets(Component c){return new Insets(1,1,1,1);}},
BorderFactory.createEmptyBorder(10,20,10,20)));
search.addFocusListener(new FocusAdapter(){
public void focusGained(FocusEvent e){if(search.getText().contains("Search")){search.setText("");search.setForeground(DARK);}}
public void focusLost(FocusEvent e){if(search.getText().isEmpty()){search.setText(" Search medicine by name, category or company...");search.setForeground(new Color(0xAA,0xAA,0xAA));refreshTable();}}
});
search.addKeyListener(new KeyAdapter(){
public void keyReleased(KeyEvent e){
String t=search.getText().trim();
TableRowSorter<DefaultTableModel> sorter = (TableRowSorter<DefaultTableModel>) sharedTable.getRowSorter();
if(t.isEmpty()||t.contains("Search")){
refreshTable();
}
else{
sorter.setRowFilter(RowFilter.orFilter(java.util.Arrays.asList(
RowFilter.regexFilter("(?i)"+java.util.regex.Pattern.quote(t),1),
RowFilter.regexFilter("(?i)"+java.util.regex.Pattern.quote(t),2))));
}
}
});
body.add(search,BorderLayout.NORTH);
JScrollPane sp=new JScrollPane(sharedTable); sp.setBorder(BorderFactory.createLineBorder(TBL_BRD));
sp.getViewport().setBackground(WHITE);
body.add(sp,BorderLayout.CENTER);
pagPanel=new JPanel(new BorderLayout()); pagPanel.setOpaque(false);
pagPanel.setBorder(BorderFactory.createEmptyBorder(8,0,0,0));
showingLabel = new JLabel();
showingLabel.setFont(F12); showingLabel.setForeground(GRAY);
pagPanel.add(showingLabel, BorderLayout.WEST);
refreshTable();
body.add(pagPanel,BorderLayout.SOUTH);
sec.add(body,BorderLayout.CENTER);
return sec;
}
private void styleTable(JTable table) {
table.setFont(F13); table.setRowHeight(40);
table.setShowGrid(false); table.setIntercellSpacing(new Dimension(0,0));
table.setSelectionBackground(new Color(252,228,236));
table.setSelectionForeground(new Color(180,60,90));
table.setRowSelectionAllowed(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setDefaultEditor(Object.class,null);
table.setFocusable(true);
table.getColumn("Action").setCellRenderer(new TableCellRenderer(){
public Component getTableCellRendererComponent(JTable t,Object v,boolean sel,boolean foc,int r,int c){
JPanel ap=new JPanel(new FlowLayout(FlowLayout.CENTER,4,8));
ap.setOpaque(true);ap.setBackground(sel?new Color(252,228,236):(r%2==0?WHITE:ALT));
ap.add(iconLabel(0));ap.add(iconLabel(1));return ap;}});
table.getColumn("Action").setCellEditor(new ActionEditor(this, table));
table.setDefaultEditor(Object.class,null);
table.setDefaultRenderer(Object.class,new DefaultTableCellRenderer(){
public Component getTableCellRendererComponent(JTable t,Object v,boolean sel,boolean foc,int r,int c){
JLabel l=(JLabel)super.getTableCellRendererComponent(t,v,sel,foc,r,c);
if(!sel)l.setBackground(r%2==0?WHITE:ALT);
l.setForeground(DARK);l.setOpaque(true);
l.setBorder(BorderFactory.createEmptyBorder(0,8,0,8));
if(c==6){
String s=String.valueOf(v);
if("In Stock".equals(s)){l.setForeground(GREEN);l.setBackground(BADGE_GREEN_BG);}
else if("Low Stock".equals(s)){l.setForeground(BADGE_ORANGE_FG);l.setBackground(BADGE_ORANGE_BG);}
else{l.setForeground(RED);l.setBackground(new Color(0xFF,0xEB,0xEE));}
l.setHorizontalAlignment(SwingConstants.CENTER);
}
return l;
}
});
JTableHeader th=table.getTableHeader();
th.setFont(FB13);th.setBackground(TBL_HDR_BG);th.setForeground(TBL_HDR_FG);
th.setPreferredSize(new Dimension(0,40));
th.setBorder(BorderFactory.createMatteBorder(0,0,1,0,TBL_HDR_BR));th.setReorderingAllowed(false);
table.getColumnModel().getColumn(0).setPreferredWidth(50);
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(2).setPreferredWidth(80);
table.getColumnModel().getColumn(3).setPreferredWidth(50);
table.getColumnModel().getColumn(4).setPreferredWidth(70);
table.getColumnModel().getColumn(5).setPreferredWidth(90);
table.getColumnModel().getColumn(6).setPreferredWidth(80);
table.getColumnModel().getColumn(7).setPreferredWidth(70);
}
private void showAddDialog() {
JDialog dlg=new JDialog((Frame)SwingUtilities.getWindowAncestor(this),"Add New Medicine",true);
dlg.setSize(500,450); dlg.setLocationRelativeTo(this); dlg.setResizable(false);
JPanel p=new JPanel(); p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
p.setBorder(BorderFactory.createEmptyBorder(24,28,24,28)); p.setBackground(WHITE);
JLabel t=new JLabel("Add New Medicine"); t.setFont(new Font("Segoe UI",Font.BOLD,20));
t.setForeground(DARK); t.setAlignmentX(0f);
p.add(t); p.add(Box.createVerticalStrut(20));
JTextField nameF=addField(p,"Medicine Name");
JComboBox<String> catF=new JComboBox<>(new String[]{"Tablet","Capsule","Syrup","Injection"});
catF.setFont(F13); catF.setMaximumSize(new Dimension(Integer.MAX_VALUE,36));
JPanel cp=new JPanel(new BorderLayout()); cp.setOpaque(false); cp.setMaximumSize(new Dimension(Integer.MAX_VALUE,60));
cp.setAlignmentX(0f);
JLabel cl=new JLabel("Category"); cl.setFont(FB13); cl.setForeground(DARK);
cp.add(cl,BorderLayout.NORTH); cp.add(catF,BorderLayout.CENTER);
p.add(cp); p.add(Box.createVerticalStrut(10));
JTextField stockF=addField(p,"Stock (number)");
JTextField priceF=addField(p,"Price ₹");
JTextField expF=addField(p,"Expiry Date (MM/YYYY)");
JTextField compF=addField(p,"Company Name");
p.add(Box.createVerticalStrut(16));
JPanel btns=new JPanel(new FlowLayout(FlowLayout.RIGHT,10,0)); btns.setOpaque(false);
btns.setAlignmentX(0f); btns.setMaximumSize(new Dimension(Integer.MAX_VALUE,40));
JButton cancel=new JButton("Cancel");
cancel.setFont(FB13);cancel.setForeground(GRAY);cancel.setBackground(WHITE);
cancel.setBorder(BorderFactory.createLineBorder(BRD,1,true));
cancel.setPreferredSize(new Dimension(100,36));
cancel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
cancel.addActionListener(e->dlg.dispose());
JButton addB=pinkBtn("Add Medicine");
addB.setPreferredSize(new Dimension(140,36));
addB.addActionListener(e->{
String nm=nameF.getText().trim(), stk=stockF.getText().trim();
String pr=priceF.getText().trim(), exp=expF.getText().trim(), co=compF.getText().trim();
if(nm.isEmpty()||stk.isEmpty()||pr.isEmpty()||exp.isEmpty()||co.isEmpty()){
JOptionPane.showMessageDialog(dlg,"Please fill all fields!","Error",JOptionPane.ERROR_MESSAGE);return;
}
int stkVal;
double priceVal;
try{stkVal=validStock(stk);}catch(Exception ex){
JOptionPane.showMessageDialog(dlg,"Stock must be zero or more.","Error",JOptionPane.ERROR_MESSAGE);return;}
try{priceVal=validPrice(pr);}catch(Exception ex){
JOptionPane.showMessageDialog(dlg,"Price must be greater than zero.","Error",JOptionPane.ERROR_MESSAGE);return;}
LocalDate expiryDate=parseExpiryDate(exp);
if(expiryDate==null){
JOptionPane.showMessageDialog(dlg,"Expiry date must be like MM/YYYY, Jan 2027, or YYYY-MM-DD.","Error",JOptionPane.ERROR_MESSAGE);return;
}
if(expiryDate.isBefore(LocalDate.now())){
JOptionPane.showMessageDialog(dlg,"Expiry date has passed. Cannot add this medicine.","Error",JOptionPane.ERROR_MESSAGE);return;
}
int nextId=1006;
for(int i=0;i<sharedTableModel.getRowCount();i++){
int id=Integer.parseInt(String.valueOf(sharedTableModel.getValueAt(i,0)));
if(id>=nextId)nextId=id+1;
}
Object[] newRow=new Object[]{String.valueOf(nextId),nm,(String)catF.getSelectedItem(),stkVal,String.format("%.2f",priceVal),exp,status(stkVal),co};
DatabaseManager.addMedicine(newRow);
loadMedicinesFromDatabase();
currentPage=(int)Math.ceil(sharedTableModel.getRowCount()/(double)RPP);
refreshTable();
updateStats(); dlg.dispose();
JOptionPane.showMessageDialog(this,"Medicine added successfully!","Success",JOptionPane.INFORMATION_MESSAGE);
});
btns.add(cancel); btns.add(addB);
p.add(btns);
JScrollPane scroll=new JScrollPane(p);
scroll.setBorder(null);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scroll.getViewport().setBackground(WHITE);
scroll.getVerticalScrollBar().setUnitIncrement(12);
applyTransparentScrollBar(scroll);
dlg.setContentPane(scroll); dlg.setVisible(true);
}
private JTextField addField(JPanel p,String label) {
JPanel fp=new JPanel(new BorderLayout()); fp.setOpaque(false);
fp.setMaximumSize(new Dimension(Integer.MAX_VALUE,52)); fp.setAlignmentX(0f);
JLabel l=new JLabel(label); l.setFont(FB13); l.setForeground(DARK);
JTextField tf=new JTextField(); tf.setFont(F13);
tf.setPreferredSize(new Dimension(0,32));
tf.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(BRD,1,true),BorderFactory.createEmptyBorder(4,10,4,10)));
fp.add(l,BorderLayout.NORTH); fp.add(tf,BorderLayout.CENTER);
p.add(fp); p.add(Box.createVerticalStrut(8));
return tf;
}
void updateStats(){
totalLbl.setText(String.valueOf(sharedTableModel.getRowCount()));
if(expLbl!=null)expLbl.setText(String.valueOf(getExpiringSoonRows().size()));
if(lowLbl!=null)lowLbl.setText(String.valueOf(getLowStockRows().size()));
if(revLbl!=null)revLbl.setText("\u20b9"+String.format("%.2f",DatabaseManager.getTotalRevenue()));
if(stockChartPanel!=null)stockChartPanel.refreshData();
}
private void makeClickable(JComponent component,Runnable action) {
component.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
component.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){action.run();}
});
}
private List<Object[]> getLowStockRows() {
List<Object[]> rows=new ArrayList<>();
for(int i=0;i<sharedTableModel.getRowCount();i++){
String st=String.valueOf(sharedTableModel.getValueAt(i,6));
if("Low Stock".equals(st)||"Critical".equals(st)) rows.add(medicineDialogRow(i));
}
return rows;
}
private List<Object[]> getExpiringSoonRows() {
List<Object[]> rows=new ArrayList<>();
LocalDate today=LocalDate.now();
LocalDate limit=today.plusMonths(2);
for(int i=0;i<sharedTableModel.getRowCount();i++){
LocalDate expiry=parseExpiryDate(String.valueOf(sharedTableModel.getValueAt(i,5)));
if(expiry!=null&&!expiry.isBefore(today)&&!expiry.isAfter(limit)) rows.add(medicineDialogRow(i));
}
return rows;
}
private Object[] medicineDialogRow(int row) {
return new Object[]{
sharedTableModel.getValueAt(row,0),
sharedTableModel.getValueAt(row,1),
sharedTableModel.getValueAt(row,2),
sharedTableModel.getValueAt(row,3),
sharedTableModel.getValueAt(row,4),
sharedTableModel.getValueAt(row,5),
sharedTableModel.getValueAt(row,6)
};
}
private static LocalDate parseExpiryDate(String text) {
String value=text.trim();
DateTimeFormatter monthName=DateTimeFormatter.ofPattern("MMM yyyy",Locale.ENGLISH);
DateTimeFormatter monthNumber=DateTimeFormatter.ofPattern("MM/yyyy",Locale.ENGLISH);
try{return YearMonth.parse(value,monthName).atEndOfMonth();}catch(DateTimeParseException ignored){}
try{return YearMonth.parse(value,monthNumber).atEndOfMonth();}catch(DateTimeParseException ignored){}
try{return LocalDate.parse(value);}catch(DateTimeParseException ignored){}
return null;
}
private int validStock(String text) {
int stock=Integer.parseInt(text.trim());
if(stock<0)throw new NumberFormatException();
return stock;
}
private double validPrice(String text) {
double price=Double.parseDouble(text.trim());
if(price<=0)throw new NumberFormatException();
return price;
}
private void showMedicineList(String title,List<Object[]> rows) {
String[] columns={"ID","Medicine","Category","Stock","Price","Expiry","Status"};
Object[][] data=rows.toArray(new Object[0][]);
JTable table=simpleTable(columns,data);
if("Expiring Soon".equals(title)) applyExpiryUrgencyRenderer(table);
JScrollPane sp=new JScrollPane(table);
sp.setPreferredSize(new Dimension(760,320));
sp.setBorder(BorderFactory.createLineBorder(BRD));
sp.getViewport().setBackground(WHITE);
applyTransparentScrollBar(sp);
if(rows.isEmpty()){
JOptionPane.showMessageDialog(this,"No medicines found for this list.",title,JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(this,sp,title,JOptionPane.PLAIN_MESSAGE);
}
}
private void showRevenueHistory() {
List<DatabaseManager.BillSummary> bills=DatabaseManager.getBillHistory();
String[] columns={"Bill No","Customer","Payment","Subtotal","Tax","Total","Date & Time"};
Object[][] data=new Object[bills.size()][columns.length];
for(int i=0;i<bills.size();i++){
DatabaseManager.BillSummary bill=bills.get(i);
data[i]=new Object[]{
"#"+bill.id,
bill.customer,
bill.payment,
"\u20b9"+String.format("%.2f",bill.subtotal),
"\u20b9"+String.format("%.2f",bill.tax),
"\u20b9"+String.format("%.2f",bill.total),
bill.billDate
};
}
JTable table=simpleTable(columns,data);
JScrollPane sp=new JScrollPane(table);
sp.setPreferredSize(new Dimension(820,340));
sp.setBorder(BorderFactory.createLineBorder(BRD));
sp.getViewport().setBackground(WHITE);
applyTransparentScrollBar(sp);
if(bills.isEmpty()){
JOptionPane.showMessageDialog(this,"No revenue history yet. Generate a bill to create the first entry.","Revenue History",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(this,sp,"Revenue History",JOptionPane.PLAIN_MESSAGE);
}
}
private JPanel buildRightPanel() {
JPanel r=new JPanel(); r.setLayout(new BoxLayout(r,BoxLayout.Y_AXIS));
r.setOpaque(false); r.setPreferredSize(new Dimension(260,0));
JPanel alerts=rndPanel(); alerts.setLayout(new BoxLayout(alerts,BoxLayout.Y_AXIS));
alerts.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
alerts.setMaximumSize(new Dimension(260,250));
JPanel ah=new JPanel(new BorderLayout()); ah.setOpaque(false);
ah.setMaximumSize(new Dimension(260,24)); ah.setAlignmentX(0f);
JLabel at=new JLabel(" Stock Alerts"); at.setFont(FB16); at.setForeground(DARK);
at.setIcon(sectionIcon(1)); at.setIconTextGap(6);
JLabel va=new JLabel("View All"); va.setFont(F12); va.setForeground(PINK);
va.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
va.addMouseListener(new MouseAdapter(){public void mouseClicked(MouseEvent e){navigateTo(4);}});
ah.add(at,BorderLayout.WEST); ah.add(va,BorderLayout.EAST);
alerts.add(ah); alerts.add(Box.createVerticalStrut(12));
alerts.add(alertItem("Dolo 650",28));alerts.add(Box.createVerticalStrut(8));
alerts.add(alertItem("Amoxicillin 500mg",15));alerts.add(Box.createVerticalStrut(8));
alerts.add(alertItem("Cetrizine 10mg",2));
r.add(alerts); r.add(Box.createVerticalStrut(14));
JPanel qa=rndPanel(); qa.setLayout(new BoxLayout(qa,BoxLayout.Y_AXIS));
qa.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
qa.setMaximumSize(new Dimension(260,250));
JLabel qt=new JLabel(" Quick Actions"); qt.setFont(FB16); qt.setForeground(DARK); qt.setAlignmentX(0f);
qt.setIcon(sectionIcon(2)); qt.setIconTextGap(6);
qa.add(qt); qa.add(Box.createVerticalStrut(12));
JPanel grid=new JPanel(new GridLayout(2,2,8,8)); grid.setOpaque(false);
grid.setAlignmentX(0f); grid.setMaximumSize(new Dimension(240,160));
JButton addMedicine=actionBtn(0,"Add Medicine");
addMedicine.addActionListener(e->showAddDialog());
JButton newBill=actionBtn(1,"New Bill");
newBill.addActionListener(e->navigateTo(2));
JButton purchase=actionBtn(2,"Purchase");
purchase.addActionListener(e->navigateTo(3));
JButton reports=actionBtn(3,"View Reports");
reports.addActionListener(e->navigateTo(5));
grid.add(addMedicine); grid.add(newBill);
grid.add(purchase); grid.add(reports);
qa.add(grid); r.add(qa); r.add(Box.createVerticalGlue());
return r;
}
private JPanel alertItem(String name,int qty) {
JPanel i=new JPanel(new BorderLayout(8,0)); i.setOpaque(false);
i.setMaximumSize(new Dimension(240,48)); i.setAlignmentX(0f);
i.setBorder(BorderFactory.createEmptyBorder(6,0,6,0));
// Pill capsule icon drawn with Graphics2D
JLabel ic=new JLabel(new Icon(){
public int getIconWidth(){return 40;} public int getIconHeight(){return 20;}
public void paintIcon(Component c,Graphics g,int x,int y){
Graphics2D g2=(Graphics2D)g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(new Color(0xFC,0xE4,0xEC));
g2.fillRoundRect(x,y,40,20,20,20);
g2.setColor(PINK); g2.setStroke(new BasicStroke(1.5f));
g2.drawRoundRect(x,y,39,19,20,20);
g2.drawLine(x+20,y,x+20,y+19);
g2.dispose();
}
});
JPanel tx=new JPanel(); tx.setLayout(new BoxLayout(tx,BoxLayout.Y_AXIS)); tx.setOpaque(false);
JLabel n=new JLabel(name); n.setFont(FB13); n.setForeground(DARK);
JLabel s=new JLabel("Only "+qty+" left in stock"); s.setFont(F12); s.setForeground(GRAY);
tx.add(n); tx.add(s);
i.add(ic,BorderLayout.WEST); i.add(tx,BorderLayout.CENTER);
return i;
}
JPanel createMedicinesPage() {
currentPage=1; refreshTable();
JPanel p=new JPanel(new BorderLayout(0,10)); p.setOpaque(false);
JPanel hdr=new JPanel(new BorderLayout()); hdr.setOpaque(false);
JLabel t=new JLabel(" All Medicines"); t.setFont(FB16); t.setForeground(DARK);
t.setIcon(sectionIcon(0)); t.setIconTextGap(6);
JButton ab=pinkBtn("+ Add Medicine"); ab.addActionListener(e->showAddDialog());
hdr.add(t,BorderLayout.WEST); hdr.add(exportButtons(ab),BorderLayout.EAST);
p.add(hdr,BorderLayout.NORTH);
medicinesTable = new JTable(sharedTableModel);
styleTable(medicinesTable);
medicinesTable.setRowSorter(null);
JScrollPane sp=new JScrollPane(medicinesTable); sp.setBorder(BorderFactory.createLineBorder(BRD));
sp.getViewport().setBackground(WHITE);
applyTransparentScrollBar(sp);
p.add(sp,BorderLayout.CENTER);
return p;
}
private void applyTransparentScrollBar(JScrollPane sp) {
JScrollBar bar = sp.getVerticalScrollBar();
bar.setOpaque(false);
bar.setUnitIncrement(12);
bar.setUI(new BasicScrollBarUI() {
protected void configureScrollBarColors() {
thumbColor = new Color(0xC9,0x63,0x7A,90);
trackColor = new Color(0,0,0,0);
}
protected JButton createDecreaseButton(int orientation) { return zeroButton(); }
protected JButton createIncreaseButton(int orientation) { return zeroButton(); }
protected void paintTrack(Graphics g, JComponent c, Rectangle r) {}
protected void paintThumb(Graphics g, JComponent c, Rectangle r) {
if(!c.isEnabled() || r.width <= 0 || r.height <= 0) return;
Graphics2D g2=(Graphics2D)g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(thumbColor);
g2.fillRoundRect(r.x+3,r.y+3,r.width-6,r.height-6,8,8);
g2.dispose();
}
});
}
private JButton zeroButton() {
JButton b = new JButton();
b.setPreferredSize(new Dimension(0,0));
b.setMinimumSize(new Dimension(0,0));
b.setMaximumSize(new Dimension(0,0));
return b;
}
JPanel createStockAlertsPage() {
JPanel p=new JPanel(); p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS)); p.setOpaque(false);
JLabel t=new JLabel(" Stock Alerts \u2014 Low & Critical Items"); t.setFont(FB16);
t.setIcon(sectionIcon(1)); t.setIconTextGap(6);
t.setForeground(DARK); t.setAlignmentX(0f);
p.add(t); p.add(Box.createVerticalStrut(16));
for(int i=0;i<sharedTableModel.getRowCount();i++){
String st=String.valueOf(sharedTableModel.getValueAt(i, 6));
if(!"In Stock".equals(st)){
String nm=(String)sharedTableModel.getValueAt(i, 1);
int qty=Integer.parseInt(String.valueOf(sharedTableModel.getValueAt(i, 3)));
JPanel card=rndPanel(); card.setLayout(new BorderLayout(12,0));
card.setBorder(BorderFactory.createEmptyBorder(14,16,14,16));
card.setMaximumSize(new Dimension(Integer.MAX_VALUE,60)); card.setAlignmentX(0f);
JLabel ic=new JLabel(sectionIcon(0));
JPanel info=new JPanel(); info.setLayout(new BoxLayout(info,BoxLayout.Y_AXIS)); info.setOpaque(false);
JLabel nl=new JLabel(nm+" \u2014 "+st); nl.setFont(FB13);
nl.setForeground("Critical".equals(st)?RED:ORANGE);
JLabel sl=new JLabel("Only "+qty+" left in stock"); sl.setFont(F12); sl.setForeground(GRAY);
info.add(nl); info.add(sl);
card.add(ic,BorderLayout.WEST); card.add(info,BorderLayout.CENTER);
p.add(card); p.add(Box.createVerticalStrut(8));
}
}
if(p.getComponentCount()==2){
JLabel none=new JLabel("All medicines are well stocked!");
none.setFont(F13);none.setForeground(GREEN);none.setAlignmentX(0f);
p.add(none);
}
p.add(Box.createVerticalGlue());
return p;
}
JPanel createBillingPage() {
JPanel p=new JPanel(new BorderLayout(14,14)); p.setOpaque(false);
JPanel main=new JPanel(new BorderLayout(0,12)); main.setOpaque(false);
JLabel t=new JLabel(" Billing"); t.setFont(FB16); t.setForeground(DARK);
t.setIcon(qaIcon(1)); t.setIconTextGap(8);
main.add(t,BorderLayout.NORTH);
JPanel form=rndPanel(); form.setLayout(new GridLayout(2,5,10,10));
form.setBorder(BorderFactory.createEmptyBorder(16,16,16,16));
JComboBox<String> medBox=new JComboBox<>(medicineNames()); medBox.setFont(F13);
JComboBox<String> paymentField=new JComboBox<>(new String[]{"Cash","UPI","Card"}); paymentField.setFont(F13);
JTextField qtyField=input("1"), discountField=input("0");
JTextField customerField=input("Walk-in"), mobileField=input("");
form.add(labeled("Medicine",medBox));
form.add(labeled("Qty",qtyField));
form.add(labeled("Discount %",discountField));
JButton add=pinkBtn("+ Add Item"); form.add(add);
JButton remove=pinkBtn("Remove Item"); form.add(remove);
form.add(labeled("Customer",customerField));
form.add(labeled("Mobile",mobileField));
form.add(labeled("Payment",paymentField));
JButton print=pinkBtn("Generate Bill"); form.add(print);
JButton history=pinkBtn("Bill History"); history.addActionListener(e->showRevenueHistory()); form.add(history);
main.add(form,BorderLayout.CENTER);
String[] cols={"Item","Qty","Price","Amount"};
JTable billTable=simpleTable(cols,new Object[][]{});
DefaultTableModel billModel=(DefaultTableModel)billTable.getModel();
JScrollPane sp=new JScrollPane(billTable); sp.setBorder(BorderFactory.createLineBorder(BRD));
sp.getViewport().setBackground(WHITE); applyTransparentScrollBar(sp);
main.add(sp,BorderLayout.SOUTH);
JPanel side=new JPanel(); side.setOpaque(false); side.setLayout(new BoxLayout(side,BoxLayout.Y_AXIS));
side.setPreferredSize(new Dimension(260,0));
JLabel subtotalValue=new JLabel("\u20b90.00"), taxValue=new JLabel("\u20b90.00"), totalValue=new JLabel("\u20b90.00");
side.add(totalCard("Subtotal",subtotalValue,sectionIcon(0),new Color(0xFF,0xF7,0xE8),new Color(0xE6,0x51,0x00)));
side.add(Box.createVerticalStrut(12));
side.add(totalCard("Tax",taxValue,sectionIcon(2),new Color(0xF5,0xF0,0xFF),new Color(0x7B,0x1F,0xA2)));
side.add(Box.createVerticalStrut(12));
side.add(totalCard("Total",totalValue,statIcon(3,GREEN),new Color(0xE8,0xF5,0xE9),GREEN));
p.add(main,BorderLayout.CENTER); p.add(side,BorderLayout.EAST);
Runnable updateTotals=()->{
double subtotal=0;
for(int i=0;i<billModel.getRowCount();i++) subtotal+=Double.parseDouble(String.valueOf(billModel.getValueAt(i,3)));
double discount;
try{discount=validDiscount(discountField.getText().trim());}catch(IllegalArgumentException ex){discount=0;}
subtotal=subtotal-(subtotal*discount/100.0);
double tax=subtotal*0.05,total=subtotal+tax;
subtotalValue.setText("\u20b9"+String.format("%.2f",subtotal));
taxValue.setText("\u20b9"+String.format("%.2f",tax));
totalValue.setText("\u20b9"+String.format("%.2f",total));
};
add.addActionListener(e->{
if(medBox.getItemCount()==0){JOptionPane.showMessageDialog(this,"No medicines available for billing.","Billing",JOptionPane.WARNING_MESSAGE);return;}
int qty;
try{qty=Integer.parseInt(qtyField.getText().trim()); if(qty<=0)throw new NumberFormatException();}catch(Exception ex){
JOptionPane.showMessageDialog(this,"Enter a valid quantity.","Billing",JOptionPane.ERROR_MESSAGE);return;}
int idx=medBox.getSelectedIndex();
String name=String.valueOf(sharedTableModel.getValueAt(idx,1));
int available=Integer.parseInt(String.valueOf(sharedTableModel.getValueAt(idx,3)));
int alreadyInBill=billedQuantity(billModel,name);
if(qty+alreadyInBill>available){
JOptionPane.showMessageDialog(this,"Only "+available+" units available for "+name+".","Billing",JOptionPane.WARNING_MESSAGE);return;
}
double price=Double.parseDouble(String.valueOf(sharedTableModel.getValueAt(idx,4)));
billModel.addRow(new Object[]{name,qty,String.format("%.2f",price),String.format("%.2f",qty*price)});
updateTotals.run();
});
remove.addActionListener(e->{
int row=billTable.getSelectedRow();
if(row<0){JOptionPane.showMessageDialog(this,"Select an item to remove.","Billing",JOptionPane.INFORMATION_MESSAGE);return;}
billModel.removeRow(billTable.convertRowIndexToModel(row));
updateTotals.run();
});
print.addActionListener(e->{
if(billModel.getRowCount()==0){JOptionPane.showMessageDialog(this,"Add at least one item before generating a bill.","Billing",JOptionPane.WARNING_MESSAGE);return;}
if(!isValidMobile(mobileField.getText().trim())){JOptionPane.showMessageDialog(this,"Enter a valid 10 digit mobile number or leave it blank.","Billing",JOptionPane.ERROR_MESSAGE);return;}
try{validDiscount(discountField.getText().trim());}catch(IllegalArgumentException ex){JOptionPane.showMessageDialog(this,ex.getMessage(),"Billing",JOptionPane.ERROR_MESSAGE);return;}
if(!hasAvailableStockForBill(billModel))return;
BillTotals totals=calculateBillTotals(billModel,discountField);
String preview="Customer: "+customerField.getText().trim()+
"\nMobile: "+mobileField.getText().trim()+
"\nPayment: "+paymentField.getSelectedItem()+
"\nItems: "+billModel.getRowCount()+
"\nTotal: \u20b9"+String.format("%.2f",totals.total)+
"\n\nGenerate this bill?";
if(JOptionPane.showConfirmDialog(this,preview,"Confirm Bill",JOptionPane.YES_NO_OPTION)!=JOptionPane.YES_OPTION)return;
int billId=BillingService.saveBillAndUpdateStock(
customerField.getText().trim(),
mobileField.getText().trim(),
String.valueOf(paymentField.getSelectedItem()),
totals.subtotal,
totals.tax,
totals.total,
buildBillLines(billModel)
);
loadMedicinesFromDatabase();
refreshTable();
updateStats();
JOptionPane.showMessageDialog(this,
"Bill #"+billId+" generated for "+customerField.getText().trim()+"\nMobile: "+mobileField.getText().trim()+
"\nPayment: "+paymentField.getSelectedItem()+"\nTotal: "+totalValue.getText(),
"Bill Generated",JOptionPane.INFORMATION_MESSAGE);
billModel.setRowCount(0);
updateTotals.run();
});
updateTotals.run();
return p;
}
private boolean hasAvailableStockForBill(DefaultTableModel billModel) {
for(int i=0;i<billModel.getRowCount();i++){
String name=String.valueOf(billModel.getValueAt(i,0));
int row=findMedicineRowByName(name);
if(row<0){
JOptionPane.showMessageDialog(this,name+" is no longer available in inventory.","Billing",JOptionPane.ERROR_MESSAGE);
return false;
}
int requested=billedQuantity(billModel,name);
int available=Integer.parseInt(String.valueOf(sharedTableModel.getValueAt(row,3)));
if(requested>available){
JOptionPane.showMessageDialog(this,"Only "+available+" units available for "+name+".","Billing",JOptionPane.WARNING_MESSAGE);
return false;
}
}
return true;
}
private List<BillingService.BillLine> buildBillLines(DefaultTableModel billModel) {
List<BillingService.BillLine> lines=new ArrayList<>();
for(int i=0;i<billModel.getRowCount();i++){
String name=String.valueOf(billModel.getValueAt(i,0));
int row=findMedicineRowByName(name);
int qty=Integer.parseInt(String.valueOf(billModel.getValueAt(i,1)));
double price=Double.parseDouble(String.valueOf(billModel.getValueAt(i,2)));
double amount=Double.parseDouble(String.valueOf(billModel.getValueAt(i,3)));
int stock=Integer.parseInt(String.valueOf(sharedTableModel.getValueAt(row,3)));
int updatedStock=stock-qty;
Object[] medicineRow=new Object[]{
sharedTableModel.getValueAt(row,0),
sharedTableModel.getValueAt(row,1),
sharedTableModel.getValueAt(row,2),
stock,
sharedTableModel.getValueAt(row,4),
sharedTableModel.getValueAt(row,5),
sharedTableModel.getValueAt(row,6)
};
lines.add(new BillingService.BillLine(medicineRow,qty,price,amount,updatedStock,status(updatedStock)));
}
return lines;
}
private BillTotals calculateBillTotals(DefaultTableModel billModel,JTextField discountField) {
double subtotal=0;
for(int i=0;i<billModel.getRowCount();i++) subtotal+=Double.parseDouble(String.valueOf(billModel.getValueAt(i,3)));
double discount=validDiscount(discountField.getText().trim());
subtotal=subtotal-(subtotal*discount/100.0);
double tax=subtotal*0.05,total=subtotal+tax;
return new BillTotals(subtotal,tax,total);
}
private double validDiscount(String text) {
try{
double discount=Double.parseDouble(text.isEmpty()?"0":text);
if(discount<0||discount>100)throw new NumberFormatException();
return discount;
}catch(Exception ex){
throw new IllegalArgumentException("Discount must be between 0 and 100.");
}
}
private void showExpiryTabs() {
loadMedicinesFromDatabase();
refreshTable();
updateStats();
JTabbedPane tabs=new JTabbedPane();
tabs.setFont(FB13);
tabs.addTab("Expiring Soon", expiryTablePanel(getExpiringSoonRows(),true));
tabs.addTab("Expired", expiryTablePanel(DatabaseManager.getExpiredMedicines(),false));
tabs.setPreferredSize(new Dimension(780,360));
JOptionPane.showMessageDialog(this,tabs,"Expiry Medicines",JOptionPane.PLAIN_MESSAGE);
}
private JPanel expiryTablePanel(List<Object[]> rows,boolean colorByUrgency) {
JPanel panel=new JPanel(new BorderLayout());
panel.setBackground(WHITE);
if(rows.isEmpty()){
JLabel empty=new JLabel(colorByUrgency?"No medicines expiring in the next 2 months.":"No expired medicines found.");
empty.setFont(F13);
empty.setForeground(GRAY);
empty.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(empty,BorderLayout.CENTER);
return panel;
}
String[] columns={"ID","Medicine","Category","Stock","Price","Expiry","Status"};
JTable table=simpleTable(columns,rows.toArray(new Object[0][]));
if(colorByUrgency) applyExpiryUrgencyRenderer(table);
else applyExpiredRenderer(table);
JScrollPane sp=new JScrollPane(table);
sp.setBorder(BorderFactory.createLineBorder(BRD));
sp.getViewport().setBackground(WHITE);
applyTransparentScrollBar(sp);
panel.add(sp,BorderLayout.CENTER);
return panel;
}
private void applyExpiredRenderer(JTable table) {
table.setDefaultRenderer(Object.class,new DefaultTableCellRenderer(){
public Component getTableCellRendererComponent(JTable t,Object v,boolean sel,boolean foc,int r,int c){
JLabel l=(JLabel)super.getTableCellRendererComponent(t,v,sel,foc,r,c);
if(!sel)l.setBackground(new Color(0xFF,0xEB,0xEE));
l.setForeground(sel?new Color(180,60,90):RED);
l.setOpaque(true);
l.setBorder(BorderFactory.createEmptyBorder(0,8,0,8));
return l;
}
});
}
private boolean isValidMobile(String mobile) {
return mobile.isEmpty()||mobile.matches("\\d{10}");
}
private static class BillTotals {
final double subtotal,tax,total;
BillTotals(double subtotal,double tax,double total){
this.subtotal=subtotal;
this.tax=tax;
this.total=total;
}
}
private int billedQuantity(DefaultTableModel billModel,String medicineName) {
int total=0;
for(int i=0;i<billModel.getRowCount();i++){
if(medicineName.equals(String.valueOf(billModel.getValueAt(i,0)))){
total+=Integer.parseInt(String.valueOf(billModel.getValueAt(i,1)));
}
}
return total;
}
private int findMedicineRowByName(String medicineName) {
for(int i=0;i<sharedTableModel.getRowCount();i++){
if(medicineName.equals(String.valueOf(sharedTableModel.getValueAt(i,1)))) return i;
}
return -1;
}
JPanel createPurchasesPage() {
JPanel p=new JPanel(new BorderLayout(0,12)); p.setOpaque(false);
JPanel hdr=new JPanel(new BorderLayout()); hdr.setOpaque(false);
JLabel t=new JLabel(" Purchases"); t.setFont(FB16); t.setForeground(DARK);
t.setIcon(qaIcon(2)); t.setIconTextGap(8);
JButton order=pinkBtn("+ New Purchase"); hdr.add(t,BorderLayout.WEST); hdr.add(order,BorderLayout.EAST);
p.add(hdr,BorderLayout.NORTH);
String[] cols={"PO No","Supplier","Items","Amount","Status","Date & Time"};
Object[][] rows=purchaseRows();
JTable tbl=simpleTable(cols,rows);
DefaultTableModel purchaseModel=(DefaultTableModel)tbl.getModel();
JLabel pendingValue=new JLabel();
JLabel monthValue=new JLabel();
JLabel supplierValue=new JLabel();
Runnable updatePurchaseStats=()->{
pendingValue.setText(String.valueOf(DatabaseManager.getPendingPurchaseCount()));
monthValue.setText("\u20b9"+String.format("%,.0f",DatabaseManager.getPurchaseTotalThisMonth()));
supplierValue.setText(String.valueOf(DatabaseManager.getSupplierCount()));
};
JPanel cards=new JPanel(new GridLayout(1,3,12,0)); cards.setOpaque(false);
cards.add(totalCard("Pending Orders",pendingValue,sectionIcon(2),new Color(0xF5,0xF0,0xFF),new Color(0x7B,0x1F,0xA2)));
cards.add(totalCard("This Month",monthValue,statIcon(3,GREEN),new Color(0xE8,0xF5,0xE9),GREEN));
cards.add(totalCard("Suppliers",supplierValue,qaIcon(0),new Color(0xFF,0xF0,0xF5),PINK));
updatePurchaseStats.run();
p.add(cards,BorderLayout.CENTER);
order.addActionListener(e->{
if(!showPurchaseDialog())return;
reloadPurchaseModel(purchaseModel);
updatePurchaseStats.run();
});
JScrollPane sp=new JScrollPane(tbl); sp.setBorder(BorderFactory.createLineBorder(BRD));
sp.getViewport().setBackground(WHITE); applyTransparentScrollBar(sp);
p.add(sp,BorderLayout.SOUTH);
return p;
}
private Object[][] purchaseRows() {
List<Object[]> purchases=DatabaseManager.getAllPurchases();
Object[][] rows=new Object[purchases.size()][];
for(int i=0;i<purchases.size();i++) rows[i]=purchases.get(i);
return rows;
}
private void reloadPurchaseModel(DefaultTableModel model) {
model.setRowCount(0);
for(Object[] row:DatabaseManager.getAllPurchases()) model.addRow(row);
}
private boolean showPurchaseDialog() {
JPanel form=new JPanel(new GridLayout(4,1,8,8));
JTextField supplier=input("");
JTextField items=input("");
JTextField amount=input("");
JComboBox<String> status=new JComboBox<>(new String[]{"Pending","Received"});
status.setFont(F13);
form.add(labeled("Supplier",supplier));
form.add(labeled("Items",items));
form.add(labeled("Amount",amount));
form.add(labeled("Status",status));
int result=JOptionPane.showConfirmDialog(this,form,"New Purchase",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(result!=JOptionPane.OK_OPTION)return false;
String supplierText=supplier.getText().trim();
String itemsText=items.getText().trim();
if(supplierText.isEmpty()||itemsText.isEmpty()){
JOptionPane.showMessageDialog(this,"Supplier and items are required.","Purchase",JOptionPane.ERROR_MESSAGE);
return false;
}
double amountValue;
try{
amountValue=Double.parseDouble(amount.getText().replaceAll("[^0-9.]",""));