-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRationUI.java
More file actions
1093 lines (944 loc) · 46 KB
/
Copy pathRationUI.java
File metadata and controls
1093 lines (944 loc) · 46 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 java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
public class RationUI
{
// Shared state
private static Map<String, Shop> regionalShops = new HashMap<>();
private static BeneficiaryList beneficiaries = new BeneficiaryList();
private static DistributionQueue dq = new DistributionQueue();
private static String currentState = "Haryana";
private static JFrame mainFrame;
// Store Aadhar last 4 digits for each beneficiary
private static Map<String, String> aadharMap = new HashMap<>();
// Image icons
private static ImageIcon goiLogo;
private static ImageIcon pmImage;
// Palette - Original Indian colors
private static final Color NAVY = new Color(0, 51, 102);
private static final Color SAFFRON = new Color(255, 153, 51);
private static final Color GOV_GREEN = new Color(19, 136, 8);
private static final Color WHITE = new Color(255, 255, 255);
private static final Color SURFACE = new Color(245, 247, 251);
private static final Color BORDER = new Color(208, 216, 228);
private static final Color MUTED = new Color(90, 106, 126);
private static final Color ERROR_RED = new Color(192, 57, 43);
private static final Color WARNING_BG = new Color(255, 243, 205);
private static final Color SUCCESS_BG = new Color(234, 246, 234);
public static void main(String[] args)
{
loadImages();
initializeData();
SwingUtilities.invokeLater(RationUI::createMainUI);
}
private static void loadImages() {
// Try to load images from files
// Place goi_logo.png and pm_image.png in your project folder
try {
File goiFile = new File("goi_logo.jpg");
File pmFile = new File("pm_image.jpg");
if (goiFile.exists()) {
Image img = ImageIO.read(goiFile);
Image scaledImg = img.getScaledInstance(50, 50, Image.SCALE_SMOOTH);
goiLogo = new ImageIcon(scaledImg);
} else {
// Create fallback text icon
goiLogo = createTextIcon("GOI", NAVY, WHITE);
}
if (pmFile.exists()) {
Image img = ImageIO.read(pmFile);
Image scaledImg = img.getScaledInstance(55, 55, Image.SCALE_SMOOTH);
pmImage = new ImageIcon(scaledImg);
} else {
// Create fallback text icon
pmImage = createTextIcon("PM", NAVY, WHITE);
}
} catch (Exception e) {
goiLogo = createTextIcon("GOI", NAVY, WHITE);
pmImage = createTextIcon("PM", NAVY, WHITE);
}
}
private static ImageIcon createTextIcon(String text, Color bg, Color fg) {
BufferedImage image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(bg);
g2d.fillOval(0, 0, 50, 50);
g2d.setColor(fg);
g2d.setFont(new Font("Arial", Font.BOLD, 16));
FontMetrics fm = g2d.getFontMetrics();
int textWidth = fm.stringWidth(text);
int textHeight = fm.getHeight();
g2d.drawString(text, (50 - textWidth) / 2, (50 + textHeight - fm.getDescent()) / 2);
g2d.dispose();
return new ImageIcon(image);
}
private static void initializeData()
{
String[] states = {"Punjab","Haryana","West Bengal","Kerala",
"Uttar Pradesh","Tamil Nadu","Maharashtra","Gujarat","Bihar"};
for (String state : states)
{
Shop shop = new Shop("S_" + state.replaceAll(" ","").toUpperCase(),
"Government Ration Shop", "Main Market", state, 5);
if (state.equals("Punjab") || state.equals("Haryana"))
{
shop.addItem(new Inventory("Rice", 800, 3.0, 200));
shop.addItem(new Inventory("Wheat",1500, 2.5, 300));
shop.addItem(new Inventory("Sugar", 400, 13.5, 100));
shop.addItem(new Inventory("Oil", 250, 80.0, 80));
}
else if (state.equals("West Bengal"))
{
shop.addItem(new Inventory("Rice", 1200, 3.0, 300));
shop.addItem(new Inventory("Wheat", 500, 2.5, 150));
shop.addItem(new Inventory("Sugar", 350, 13.5, 100));
shop.addItem(new Inventory("Oil", 200, 80.0, 60));
}
else if (state.equals("Kerala"))
{
shop.addItem(new Inventory("Rice", 1000, 3.0, 250));
shop.addItem(new Inventory("Wheat", 600, 2.5, 150));
shop.addItem(new Inventory("Sugar", 300, 13.5, 80));
shop.addItem(new Inventory("Oil", 180, 80.0, 50));
}
else
{
shop.addItem(new Inventory("Rice", 700, 3.0, 200));
shop.addItem(new Inventory("Wheat", 700, 2.5, 200));
shop.addItem(new Inventory("Sugar", 300, 13.5, 80));
shop.addItem(new Inventory("Oil", 150, 80.0, 50));
}
regionalShops.put(state, shop);
}
// Seed beneficiaries with Aadhar last 4 digits
beneficiaries.addBeneficiary(new Customer("Amarjeet Singh", 45,"9876543210","RC101","BPL","Sector-10","Punjab"));
aadharMap.put("RC101", "1234");
beneficiaries.addBeneficiary(new Customer("Baldev Singh", 38,"9876543211","RC102","APL","Sector-15","Punjab"));
aadharMap.put("RC102", "5678");
beneficiaries.addBeneficiary(new Customer("Mamata Devi", 52,"9876543212","RC103","Antyodaya","Sector-08","West Bengal"));
aadharMap.put("RC103", "9012");
beneficiaries.addBeneficiary(new Customer("Sourav Roy", 48,"9876543213","RC104","BPL","Sector-12","West Bengal"));
aadharMap.put("RC104", "3456");
beneficiaries.addBeneficiary(new Customer("Priya Nair", 55,"9876543214","RC105","APL","Sector-08","Kerala"));
aadharMap.put("RC105", "7890");
beneficiaries.addBeneficiary(new Customer("Rahul Verma", 42,"9876543215","RC106","BPL","Sector-05","Maharashtra"));
aadharMap.put("RC106", "2468");
}
private static void createMainUI()
{
mainFrame = new JFrame("Digital Ration Distribution System - PDS 2.0");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(900, 650);
mainFrame.setLocationRelativeTo(null);
mainFrame.setBackground(SURFACE);
JPanel root = new JPanel(new BorderLayout(0, 0));
root.setBackground(SURFACE);
root.add(buildHeader(), BorderLayout.NORTH);
root.add(buildHomePanel(), BorderLayout.CENTER);
mainFrame.setContentPane(root);
mainFrame.setVisible(true);
}
private static JPanel buildHeader() {
JPanel outer = new JPanel(new BorderLayout());
outer.setBackground(NAVY);
JPanel hdr = new JPanel(new BorderLayout());
hdr.setBackground(NAVY);
hdr.setBorder(new EmptyBorder(8, 16, 8, 16));
// Left: GOI Logo with image
JPanel leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 5));
leftPanel.setBackground(NAVY);
JLabel goiLabel = new JLabel(goiLogo);
goiLabel.setToolTipText("Government of India");
leftPanel.add(goiLabel);
JLabel goiText = new JLabel("Government of India");
goiText.setFont(new Font("Segoe UI", Font.BOLD, 12));
goiText.setForeground(WHITE);
leftPanel.add(goiText);
// Centre text
JPanel centre = new JPanel();
centre.setLayout(new BoxLayout(centre, BoxLayout.Y_AXIS));
centre.setBackground(NAVY);
JLabel title = new JLabel("DIGITAL RATION DISTRIBUTION SYSTEM", SwingConstants.CENTER);
title.setFont(new Font("Segoe UI", Font.BOLD, 16));
title.setForeground(SAFFRON);
title.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel sub = new JLabel("PDS 2.0 | One Nation, One Ration Card | NFSA 2013", SwingConstants.CENTER);
sub.setFont(new Font("Segoe UI", Font.PLAIN, 10));
sub.setForeground(WHITE);
sub.setAlignmentX(Component.CENTER_ALIGNMENT);
centre.add(title);
centre.add(Box.createVerticalStrut(4));
centre.add(sub);
// Right: PM Image
JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 5));
rightPanel.setBackground(NAVY);
JLabel pmTextLabel = new JLabel("Prime Minister");
pmTextLabel.setFont(new Font("Segoe UI", Font.PLAIN, 11));
pmTextLabel.setForeground(WHITE);
rightPanel.add(pmTextLabel);
JLabel pmLabel = new JLabel(pmImage);
pmLabel.setToolTipText("Prime Minister of India");
rightPanel.add(pmLabel);
hdr.add(leftPanel, BorderLayout.WEST);
hdr.add(centre, BorderLayout.CENTER);
hdr.add(rightPanel, BorderLayout.EAST);
// Saffron ribbon
JLabel ribbon = new JLabel("SATYAMEVA JAYATE | National Food Security Act, 2013 | PM Garib Kalyan Anna Yojana", SwingConstants.CENTER);
ribbon.setFont(new Font("Segoe UI", Font.BOLD, 11));
ribbon.setForeground(NAVY);
ribbon.setBackground(SAFFRON);
ribbon.setOpaque(true);
ribbon.setBorder(new EmptyBorder(6, 0, 6, 0));
outer.add(hdr, BorderLayout.CENTER);
outer.add(ribbon, BorderLayout.SOUTH);
return outer;
}
private static JPanel buildHomePanel() {
JPanel panel = new JPanel(new BorderLayout(0, 12));
panel.setBackground(SURFACE);
panel.setBorder(new EmptyBorder(20, 25, 20, 25));
// Region selector
JPanel regionRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 6));
regionRow.setBackground(WHITE);
regionRow.setBorder(new CompoundBorder(new LineBorder(BORDER, 1, true), new EmptyBorder(8, 12, 8, 12)));
JLabel regionLbl = new JLabel("Select State / Region:");
regionLbl.setFont(new Font("Segoe UI", Font.BOLD, 13));
regionLbl.setForeground(NAVY);
String[] states = {"Haryana","Punjab","Uttar Pradesh","West Bengal",
"Tamil Nadu","Kerala","Maharashtra","Gujarat","Bihar"};
JComboBox<String> stateCbo = new JComboBox<>(states);
stateCbo.setSelectedItem(currentState);
stateCbo.setFont(new Font("Segoe UI", Font.PLAIN, 13));
stateCbo.setPreferredSize(new Dimension(200, 30));
stateCbo.addActionListener(e -> currentState = (String) stateCbo.getSelectedItem());
regionRow.add(regionLbl);
regionRow.add(stateCbo);
panel.add(regionRow, BorderLayout.NORTH);
// Welcome banner
JPanel welcomeBanner = new JPanel();
welcomeBanner.setBackground(NAVY);
welcomeBanner.setBorder(new EmptyBorder(12, 0, 12, 0));
JLabel welcomeLbl = new JLabel("WELCOME TO THE DIGITAL PUBLIC DISTRIBUTION SYSTEM");
welcomeLbl.setFont(new Font("Segoe UI", Font.BOLD, 16));
welcomeLbl.setForeground(WHITE);
welcomeBanner.add(welcomeLbl);
JPanel centerPanel = new JPanel(new BorderLayout(0, 15));
centerPanel.setBackground(SURFACE);
centerPanel.add(welcomeBanner, BorderLayout.NORTH);
// 2x2 menu grid
JPanel grid = new JPanel(new GridLayout(2, 2, 20, 20));
grid.setBackground(SURFACE);
grid.setBorder(new EmptyBorder(10, 0, 10, 0));
grid.add(menuCard("DISTRIBUTE RATION",
"Step 1: Enter RCID\nStep 2: Verify Aadhar\nStep 3: Enter OTP\nAllocate monthly stock",
new Color(232, 238, 247), e -> showDistributionUI()));
grid.add(menuCard("CHECK STOCK",
"View inventory levels\nMonitor threshold alerts\nManage restocking",
new Color(234, 246, 234), e -> showStockUI()));
grid.add(menuCard("ADD BENEFICIARY",
"Register new family\nAdd RCID, Aadhar & personal details\nLinked List insertion",
new Color(255, 244, 230), e -> showAddBeneficiaryUI()));
grid.add(menuCard("DISTRIBUTION STATUS",
"Track pending queue (FIFO)\nView completed history (Stack)\nServe next customer",
new Color(253, 232, 232), e -> showDistributionStatusUI()));
centerPanel.add(grid, BorderLayout.CENTER);
panel.add(centerPanel, BorderLayout.CENTER);
// Footer
JPanel footer = new JPanel();
footer.setBackground(NAVY);
footer.setBorder(new EmptyBorder(10, 0, 10, 0));
JLabel footerLbl = new JLabel("Toll Free: 1800-11-4000 | Email: pds@gov.in | National Consumer Helpline: 1800-11-4000");
footerLbl.setFont(new Font("Segoe UI", Font.PLAIN, 10));
footerLbl.setForeground(WHITE);
footer.add(footerLbl);
panel.add(footer, BorderLayout.SOUTH);
return panel;
}
private static JPanel menuCard(String title, String desc, Color bg, ActionListener action) {
JPanel card = new JPanel(new BorderLayout(0, 8));
card.setBackground(WHITE);
card.setBorder(new CompoundBorder(
new LineBorder(BORDER, 1, true),
new EmptyBorder(20, 18, 20, 18)));
card.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
JLabel titleLbl = new JLabel("<html><center><b><font size='4'>" + title + "</font></b></center></html>");
titleLbl.setFont(new Font("Segoe UI", Font.BOLD, 14));
titleLbl.setForeground(NAVY);
titleLbl.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel descLbl = new JLabel("<html><center><font size='2' color='#666666'>" + desc + "</font></center></html>");
descLbl.setAlignmentX(Component.CENTER_ALIGNMENT);
card.add(titleLbl, BorderLayout.NORTH);
card.add(descLbl, BorderLayout.CENTER);
MouseAdapter ma = new MouseAdapter() {
public void mouseClicked(MouseEvent e) { action.actionPerformed(null); }
public void mouseEntered(MouseEvent e) {
card.setBorder(new CompoundBorder(new LineBorder(NAVY, 2, true), new EmptyBorder(20, 18, 20, 18)));
card.setBackground(new Color(240, 248, 255));
}
public void mouseExited (MouseEvent e) {
card.setBorder(new CompoundBorder(new LineBorder(BORDER, 1, true), new EmptyBorder(20, 18, 20, 18)));
card.setBackground(WHITE);
}
};
card.addMouseListener(ma);
for (Component c : card.getComponents()) c.addMouseListener(ma);
return card;
}
// ==================== STEP 1: RCID ENTRY ====================
private static void showDistributionUI() {
JDialog dlg = dialog("Distribute to Beneficiary", 480, 280);
final Customer[] foundCustomer = new Customer[1];
JPanel p = formPanel();
p.add(sectionTitle("Step 1 - Ration Card Lookup"));
p.add(Box.createVerticalStrut(8));
JTextField cardField = styledField("e.g. RC101");
p.add(fieldRow("Ration Card ID", cardField));
p.add(Box.createVerticalStrut(4));
JLabel info = smallLabel("Enter RCID to verify beneficiary eligibility.");
p.add(info);
p.add(Box.createVerticalStrut(12));
JButton nextBtn = navyButton("Verify RCID");
p.add(leftAlign(nextBtn));
nextBtn.addActionListener(e -> {
String cardId = cardField.getText().trim().toUpperCase();
Customer c = beneficiaries.searchByCard(cardId);
if (c == null) {
showError(dlg, "Card ID not found. Please check and retry.");
return;
}
foundCustomer[0] = c;
dlg.dispose();
// STEP 2: Go to Aadhar Verification
showAadharVerification(c);
});
dlg.add(p);
dlg.setVisible(true);
}
// ==================== STEP 2: AADHAR VERIFICATION ====================
private static void showAadharVerification(Customer customer) {
JDialog dlg = dialog("Aadhar Verification", 480, 320);
final int[] attempts = {0};
final int MAX_ATTEMPTS = 3;
JPanel p = formPanel();
p.add(sectionTitle("Step 2 - Aadhar Authentication"));
p.add(Box.createVerticalStrut(8));
JLabel infoLbl = new JLabel("Verify your identity using Aadhar number");
infoLbl.setFont(new Font("Segoe UI", Font.BOLD, 13));
infoLbl.setForeground(NAVY);
infoLbl.setAlignmentX(Component.LEFT_ALIGNMENT);
p.add(infoLbl);
p.add(Box.createVerticalStrut(4));
JLabel maskedLbl = new JLabel("Beneficiary: " + customer.getName());
maskedLbl.setFont(new Font("Segoe UI", Font.PLAIN, 12));
maskedLbl.setForeground(MUTED);
maskedLbl.setAlignmentX(Component.LEFT_ALIGNMENT);
p.add(maskedLbl);
p.add(Box.createVerticalStrut(12));
JTextField aadharField = styledField("Last 4 digits of Aadhar");
aadharField.setHorizontalAlignment(JTextField.CENTER);
aadharField.setFont(new Font("Segoe UI", Font.BOLD, 18));
p.add(fieldRow("Aadhar (last 4 digits)", aadharField));
p.add(Box.createVerticalStrut(4));
JLabel errLbl = new JLabel(" ");
errLbl.setFont(new Font("Segoe UI", Font.PLAIN, 11));
errLbl.setForeground(ERROR_RED);
p.add(errLbl);
p.add(Box.createVerticalStrut(8));
JPanel btnRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
btnRow.setBackground(WHITE);
JButton verifyBtn = navyButton("Verify Aadhar");
JButton cancelBtn = outlineButton("Cancel");
btnRow.add(verifyBtn);
btnRow.add(cancelBtn);
p.add(btnRow);
verifyBtn.addActionListener(e -> {
String enteredAadhar = aadharField.getText().trim();
String storedAadhar = aadharMap.get(customer.getRationCardId());
if (attempts[0] >= MAX_ATTEMPTS) {
errLbl.setText("Too many failed attempts. Please try again later.");
verifyBtn.setEnabled(false);
return;
}
if (storedAadhar != null && storedAadhar.equals(enteredAadhar)) {
// AADHAR VERIFIED - Generate OTP and show OTP dialog
String otp = OTPManager.generateOTP(customer.getRationCardId());
JOptionPane.showMessageDialog(dlg,
"Aadhar verification successful!\n\nOTP sent to: " + OTPManager.maskPhone(customer.getPhoneNumber()) +
"\nDemo OTP: " + otp + "\nValid for 2 minutes - 3 attempts allowed.",
"Success", JOptionPane.INFORMATION_MESSAGE);
dlg.dispose();
// STEP 3: Go to OTP Verification (AUTOMATICALLY after Aadhar success)
showOTPVerification(customer);
} else {
attempts[0]++;
int remaining = MAX_ATTEMPTS - attempts[0];
if (remaining > 0) {
errLbl.setText("Aadhar verification failed. " + remaining + " attempt(s) remaining.");
} else {
errLbl.setText("Aadhar verification failed. No attempts remaining.");
verifyBtn.setEnabled(false);
}
aadharField.setText("");
}
});
cancelBtn.addActionListener(e -> dlg.dispose());
dlg.add(p);
dlg.setVisible(true);
}
// ==================== STEP 3: OTP VERIFICATION ====================
private static void showOTPVerification(Customer customer) {
JDialog dlg = dialog("Two-Factor Authentication", 450, 280);
long[] expiry = { System.currentTimeMillis() + 120_000L };
int[] attempts = { 0 };
JPanel p = formPanel();
p.add(sectionTitle("Step 3 - OTP Verification"));
p.add(Box.createVerticalStrut(8));
JLabel phoneLbl = smallLabel("OTP sent to: " + OTPManager.maskPhone(customer.getPhoneNumber()));
p.add(phoneLbl);
JLabel timerLbl = new JLabel("2:00");
timerLbl.setFont(new Font("Segoe UI", Font.BOLD, 12));
timerLbl.setForeground(new Color(109, 59, 0));
timerLbl.setBackground(WARNING_BG);
timerLbl.setOpaque(true);
timerLbl.setBorder(new EmptyBorder(4, 12, 4, 12));
p.add(Box.createVerticalStrut(6));
p.add(timerLbl);
p.add(Box.createVerticalStrut(10));
JTextField otpField = styledField("Enter 4-digit OTP");
otpField.setHorizontalAlignment(JTextField.CENTER);
otpField.setFont(new Font("Segoe UI", Font.BOLD, 18));
p.add(fieldRow("OTP", otpField));
p.add(Box.createVerticalStrut(4));
JLabel errLbl = new JLabel(" ");
errLbl.setFont(new Font("Segoe UI", Font.PLAIN, 11));
errLbl.setForeground(ERROR_RED);
p.add(errLbl);
p.add(Box.createVerticalStrut(8));
JPanel btnRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
btnRow.setBackground(WHITE);
JButton verifyBtn = navyButton("Verify OTP");
JButton resendBtn = outlineButton("Resend OTP");
btnRow.add(verifyBtn);
btnRow.add(resendBtn);
p.add(btnRow);
// Countdown timer
javax.swing.Timer countdown = new javax.swing.Timer(500, null);
countdown.addActionListener(ev -> {
long rem = Math.max(0, expiry[0] - System.currentTimeMillis());
long m = rem / 60000, s = (rem % 60000) / 1000;
timerLbl.setText(String.format("%d:%02d", m, s));
if (rem == 0) { timerLbl.setText("Expired"); countdown.stop(); }
});
countdown.start();
dlg.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) { countdown.stop(); }
});
verifyBtn.addActionListener(e -> {
if (attempts[0] >= 3) { errLbl.setText("OTP invalidated - too many attempts."); return; }
if (System.currentTimeMillis() > expiry[0]) { errLbl.setText("OTP expired. Please resend."); return; }
boolean ok = OTPManager.verifyOTP(customer.getRationCardId(), otpField.getText().trim());
if (ok) {
countdown.stop();
JOptionPane.showMessageDialog(dlg, "OTP verification successful!", "Success", JOptionPane.INFORMATION_MESSAGE);
dlg.dispose();
showBeneficiaryDetails(customer);
} else {
attempts[0]++;
int left = 3 - attempts[0];
if (left <= 0) {
errLbl.setText("OTP invalidated after 3 wrong attempts.");
verifyBtn.setEnabled(false);
} else {
errLbl.setText("Incorrect OTP. " + left + " attempt(s) remaining.");
}
}
});
resendBtn.addActionListener(e -> {
String newOtp = OTPManager.generateOTP(customer.getRationCardId());
expiry[0] = System.currentTimeMillis() + 120_000L;
attempts[0] = 0;
errLbl.setText(" ");
otpField.setText("");
verifyBtn.setEnabled(true);
if (!countdown.isRunning()) countdown.start();
JOptionPane.showMessageDialog(dlg,
"OTP resent to " + OTPManager.maskPhone(customer.getPhoneNumber()) +
"\nDemo New OTP: " + newOtp,
"OTP Resent", JOptionPane.INFORMATION_MESSAGE);
});
dlg.add(p);
dlg.setVisible(true);
}
private static void showBeneficiaryDetails(Customer c) {
JDialog dlg = dialog("Beneficiary Details - " + c.getName(), 550, 520);
JPanel p = formPanel();
Shop shop = regionalShops.getOrDefault(c.getState(), regionalShops.get("Haryana"));
StringBuilder alloc = new StringBuilder();
Inventory[] inv = shop.getAllStock();
int cnt = shop.getStockCount();
for (int i = 0; i < cnt; i++) {
int kg = shop.getAllocation(inv[i].getItemName(), c.getCategory());
if (kg > 0) alloc.append(inv[i].getItemName()).append(": ").append(kg).append(" kg ");
}
p.add(sectionTitle("Beneficiary Information"));
p.add(Box.createVerticalStrut(8));
String maskedAadhar = "XXXX-XXXX-" + aadharMap.getOrDefault(c.getRationCardId(), "XXXX");
String[][] rows = {
{"Name", c.getName()},
{"Age", c.getAge() + " years"},
{"Phone", OTPManager.maskPhone(c.getPhoneNumber())},
{"Aadhar", maskedAadhar},
{"Ration Card", c.getRationCardId()},
{"Category", c.getCategory()},
{"Area", c.getArea()},
{"State", c.getState()},
{"Allocated Stock", alloc.toString().trim()}
};
for (String[] row : rows) p.add(detailRow(row[0], row[1]));
p.add(Box.createVerticalStrut(10));
p.add(sectionTitle("Distribution Queue"));
p.add(Box.createVerticalStrut(6));
JCheckBox queueChk = new JCheckBox("Add to Distribution Queue (FIFO - First Come First Serve)");
queueChk.setFont(new Font("Segoe UI", Font.PLAIN, 13));
queueChk.setBackground(WHITE);
p.add(queueChk);
p.add(Box.createVerticalStrut(10));
JPanel btnRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
btnRow.setBackground(WHITE);
JButton confirmBtn = navyButton("Confirm");
JButton invBtn = outlineButton("Check Inventory");
btnRow.add(confirmBtn);
btnRow.add(invBtn);
p.add(btnRow);
JLabel msg = new JLabel(" ");
msg.setFont(new Font("Segoe UI", Font.PLAIN, 12));
p.add(Box.createVerticalStrut(6));
p.add(msg);
confirmBtn.addActionListener(e -> {
if (queueChk.isSelected()) {
if (dq.isInQueue(c.getRationCardId())) {
msg.setForeground(new Color(200, 100, 0));
msg.setText(c.getName() + " is already in the queue.");
} else {
dq.enqueue(c);
msg.setForeground(GOV_GREEN);
msg.setText(c.getName() + " added to distribution queue.");
}
} else {
msg.setForeground(GOV_GREEN);
msg.setText("Distribution recorded.");
}
});
invBtn.addActionListener(e -> showStockUI());
dlg.add(p);
dlg.setVisible(true);
}
private static void showStockUI() {
JDialog dlg = dialog("Inventory - " + currentState, 680, 420);
JPanel p = formPanel();
p.add(sectionTitle("Inventory Status - " + currentState));
p.add(Box.createVerticalStrut(10));
Shop shop = regionalShops.getOrDefault(currentState, regionalShops.get("Haryana"));
Inventory[] inv = shop.getAllStock();
int cnt = shop.getStockCount();
String[] cols = {"Item", "Stock (kg)", "Threshold", "Price/kg", "Status", "Action"};
Object[][] data = new Object[cnt][6];
for (int i = 0; i < cnt; i++) {
Inventory it = inv[i];
data[i][0] = it.getItemName();
data[i][1] = it.getQuantity();
data[i][2] = it.getThreshold();
data[i][3] = "Rs." + it.getPricePerKg();
data[i][4] = it.isBelowThreshold() ? "CRITICAL" : "Adequate";
data[i][5] = it.isBelowThreshold() ? "Order Required" : "--";
}
JTable table = new JTable(data, cols) {
public boolean isCellEditable(int r, int c) { return false; }
};
table.setFont(new Font("Segoe UI", Font.PLAIN, 13));
table.setRowHeight(28);
table.getTableHeader().setFont(new Font("Segoe UI", Font.BOLD, 12));
table.getTableHeader().setBackground(SURFACE);
table.setShowHorizontalLines(true);
table.setGridColor(BORDER);
table.setDefaultRenderer(Object.class, (tbl, val, sel, foc, row, col) -> {
JLabel lbl = new JLabel(val != null ? val.toString() : "");
lbl.setOpaque(true);
lbl.setFont(new Font("Segoe UI", Font.PLAIN, 13));
lbl.setBorder(new EmptyBorder(0, 8, 0, 8));
boolean low = inv[row].isBelowThreshold();
lbl.setBackground(low ? new Color(253, 232, 232) : WHITE);
lbl.setForeground(col == 4 ? (low ? ERROR_RED : GOV_GREEN) : new Color(50, 50, 50));
return lbl;
});
JScrollPane scroll = new JScrollPane(table);
scroll.setBorder(new LineBorder(BORDER, 1));
p.add(scroll);
p.add(Box.createVerticalStrut(10));
for (int i = 0; i < cnt; i++) {
if (inv[i].isBelowThreshold()) {
final Inventory item = inv[i];
JPanel alertRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 4));
alertRow.setBackground(WARNING_BG);
alertRow.setBorder(new CompoundBorder(
new LineBorder(SAFFRON, 1),
new EmptyBorder(6, 10, 6, 10)));
alertRow.add(new JLabel("ALERT: " + item.getItemName() + " is below threshold!"));
alertRow.add(new JLabel("Enter received qty:"));
JTextField qtyField = new JTextField(6);
qtyField.setFont(new Font("Segoe UI", Font.PLAIN, 12));
JButton updateBtn = new JButton("Update Stock");
updateBtn.setFont(new Font("Segoe UI", Font.PLAIN, 12));
updateBtn.setBackground(NAVY);
updateBtn.setForeground(WHITE);
updateBtn.setOpaque(true);
updateBtn.setBorderPainted(false);
updateBtn.addActionListener(e -> {
try {
int add = Integer.parseInt(qtyField.getText().trim());
if (add > 0) {
item.addStock(add);
showInfo(dlg, add + " kg of " + item.getItemName() +
" added. New stock: " + item.getQuantity() + " kg.");
dlg.dispose();
showStockUI();
}
} catch (NumberFormatException ex) {
showError(dlg, "Enter a valid number.");
}
});
alertRow.add(qtyField);
alertRow.add(updateBtn);
p.add(alertRow);
p.add(Box.createVerticalStrut(6));
}
}
dlg.add(p);
dlg.setVisible(true);
}
private static void showAddBeneficiaryUI() {
JDialog dlg = dialog("Register New Beneficiary", 500, 560);
JPanel p = formPanel();
p.add(sectionTitle("New Beneficiary Registration"));
p.add(Box.createVerticalStrut(8));
JTextField nameField = styledField("As per Aadhar");
JTextField ageField = styledField("Enter age");
JTextField phoneField = styledField("10-digit mobile");
JTextField aadharField = styledField("12-digit Aadhar number");
JTextField rcField = styledField("e.g. RC110");
JTextField areaField = styledField("e.g. Sector-10");
String[] cats = {"Select Category","Antyodaya (AAY)","Below Poverty Line (BPL)","Above Poverty Line (APL)"};
String[] states = {"Select State","Punjab","Haryana","Uttar Pradesh","West Bengal",
"Tamil Nadu","Kerala","Maharashtra","Gujarat","Bihar"};
JComboBox<String> catCbo = styledCombo(cats);
JComboBox<String> stateCbo = styledCombo(states);
p.add(fieldRow("Full Name *", nameField));
p.add(fieldRow("Age *", ageField));
p.add(fieldRow("Phone Number *", phoneField));
p.add(fieldRow("Aadhar Number *", aadharField));
p.add(fieldRow("Ration Card No. *", rcField));
p.add(fieldRow("Category *", catCbo));
p.add(fieldRow("Area / Sector *", areaField));
p.add(fieldRow("State *", stateCbo));
p.add(Box.createVerticalStrut(10));
JPanel btnRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
btnRow.setBackground(WHITE);
JButton regBtn = navyButton("Register");
JButton clearBtn = outlineButton("Clear");
btnRow.add(regBtn);
btnRow.add(clearBtn);
p.add(btnRow);
JLabel msg = new JLabel(" ");
msg.setFont(new Font("Segoe UI", Font.PLAIN, 12));
p.add(Box.createVerticalStrut(6));
p.add(msg);
regBtn.addActionListener(e -> {
String name = nameField.getText().trim();
String phone = phoneField.getText().trim();
String aadhar = aadharField.getText().trim();
String rc = rcField.getText().trim().toUpperCase();
String area = areaField.getText().trim();
String cat = catCbo.getSelectedIndex() == 0 ? "" :
((String)catCbo.getSelectedItem()).replaceAll(" \\(.*\\)","");
String state = stateCbo.getSelectedIndex() == 0 ? "" :
(String)stateCbo.getSelectedItem();
int age = 0;
try { age = Integer.parseInt(ageField.getText().trim()); } catch (NumberFormatException ex) {}
if (name.isEmpty() || phone.isEmpty() || aadhar.isEmpty() || rc.isEmpty() || area.isEmpty()
|| cat.isEmpty() || state.isEmpty() || age <= 0) {
msg.setForeground(ERROR_RED);
msg.setText("Please fill all required fields correctly.");
return;
}
if (phone.length() != 10 || !phone.matches("\\d+")) {
msg.setForeground(ERROR_RED);
msg.setText("Enter a valid 10-digit mobile number.");
return;
}
if (aadhar.length() != 12 || !aadhar.matches("\\d+")) {
msg.setForeground(ERROR_RED);
msg.setText("Enter a valid 12-digit Aadhar number.");
return;
}
if (beneficiaries.searchByCard(rc) != null) {
msg.setForeground(ERROR_RED);
msg.setText("Ration Card ID already registered.");
return;
}
String aadharLast4 = aadhar.substring(aadhar.length() - 4);
beneficiaries.addBeneficiary(new Customer(name, age, phone, rc, cat, area, state));
aadharMap.put(rc, aadharLast4);
msg.setForeground(GOV_GREEN);
msg.setText(name + " registered with card " + rc + ".");
nameField.setText(""); ageField.setText(""); phoneField.setText("");
aadharField.setText(""); rcField.setText(""); areaField.setText("");
catCbo.setSelectedIndex(0); stateCbo.setSelectedIndex(0);
});
clearBtn.addActionListener(e -> {
nameField.setText(""); ageField.setText(""); phoneField.setText("");
aadharField.setText(""); rcField.setText(""); areaField.setText("");
catCbo.setSelectedIndex(0); stateCbo.setSelectedIndex(0);
msg.setText(" ");
});
dlg.add(p);
dlg.setVisible(true);
}
private static void showDistributionStatusUI() {
JDialog dlg = dialog("Distribution Status", 600, 500);
JPanel p = formPanel();
p.add(sectionTitle("Distribution Status"));
p.add(Box.createVerticalStrut(8));
p.add(boldLabel("Pending Queue (FIFO)"));
p.add(Box.createVerticalStrut(4));
JPanel queuePanel = new JPanel();
queuePanel.setLayout(new BoxLayout(queuePanel, BoxLayout.Y_AXIS));
queuePanel.setBackground(WHITE);
queuePanel.setBorder(new LineBorder(BORDER, 1));
refreshQueuePanel(queuePanel);
JScrollPane qScroll = new JScrollPane(queuePanel);
qScroll.setPreferredSize(new Dimension(540, 120));
qScroll.setBorder(null);
p.add(qScroll);
p.add(Box.createVerticalStrut(12));
p.add(boldLabel("Completed (Stack - most recent first)"));
p.add(Box.createVerticalStrut(4));
JPanel stackPanel = new JPanel();
stackPanel.setLayout(new BoxLayout(stackPanel, BoxLayout.Y_AXIS));
stackPanel.setBackground(WHITE);
stackPanel.setBorder(new LineBorder(BORDER, 1));
refreshStackPanel(stackPanel);
JScrollPane sScroll = new JScrollPane(stackPanel);
sScroll.setPreferredSize(new Dimension(540, 120));
sScroll.setBorder(null);
p.add(sScroll);
p.add(Box.createVerticalStrut(10));
JPanel btnRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
btnRow.setBackground(WHITE);
JButton serveBtn = navyButton("Serve Next Customer");
JButton refreshBtn = outlineButton("Refresh");
btnRow.add(serveBtn);
btnRow.add(refreshBtn);
p.add(btnRow);
JLabel msg = new JLabel(" ");
msg.setFont(new Font("Segoe UI", Font.PLAIN, 12));
p.add(Box.createVerticalStrut(6));
p.add(msg);
serveBtn.addActionListener(e -> {
if (dq.isEmpty()) {
msg.setForeground(new Color(200, 100, 0));
msg.setText("Queue is empty - no one to serve.");
} else {
Customer served = dq.dequeue();
msg.setForeground(GOV_GREEN);
msg.setText("Served: " + served.getName() + " (" + served.getRationCardId() + ")");
refreshQueuePanel(queuePanel);
refreshStackPanel(stackPanel);
queuePanel.revalidate();
queuePanel.repaint();
stackPanel.revalidate();
stackPanel.repaint();
}
});
refreshBtn.addActionListener(e -> {
refreshQueuePanel(queuePanel);
refreshStackPanel(stackPanel);
queuePanel.revalidate(); queuePanel.repaint();
stackPanel.revalidate(); stackPanel.repaint();
});
dlg.add(p);
dlg.setVisible(true);
}
private static void refreshQueuePanel(JPanel panel) {
panel.removeAll();
java.util.LinkedList<Customer> q = dq.getQueue();
if (q.isEmpty()) {
panel.add(emptyRow("No beneficiaries in queue."));
} else {
int pos = 1;
for (Customer c : q)
panel.add(statusRow(pos++, c, "PENDING", WARNING_BG, new Color(200, 100, 0)));
}
}
private static void refreshStackPanel(JPanel panel) {
panel.removeAll();
Stack<Customer> stack = dq.getCompletedStack();
if (stack.isEmpty()) {
panel.add(emptyRow("No completed distributions yet."));
} else {
java.util.List<Customer> list = new ArrayList<>(stack);
Collections.reverse(list);
int pos = 1;
for (Customer c : list)
panel.add(statusRow(pos++, c, "COMPLETED", SUCCESS_BG, GOV_GREEN));
}
}
private static JPanel statusRow(int pos, Customer c, String status, Color bg, Color fgStatus) {
JPanel row = new JPanel(new BorderLayout());
row.setBackground(bg);
row.setBorder(new CompoundBorder(
new MatteBorder(0, 0, 1, 0, BORDER),
new EmptyBorder(7, 10, 7, 10)));
row.setMaximumSize(new Dimension(Integer.MAX_VALUE, 38));
JLabel left = new JLabel(pos + ". " + c.getName() +
" | " + c.getRationCardId() +
" | " + c.getCategory() +
" | " + c.getArea());
left.setFont(new Font("Segoe UI", Font.PLAIN, 12));
JLabel right = new JLabel(status);
right.setFont(new Font("Segoe UI", Font.BOLD, 11));
right.setForeground(fgStatus);
row.add(left, BorderLayout.CENTER);
row.add(right, BorderLayout.EAST);
return row;
}
private static JPanel emptyRow(String text) {
JPanel row = new JPanel(new FlowLayout(FlowLayout.LEFT));
row.setBackground(WHITE);
JLabel lbl = new JLabel(text);
lbl.setFont(new Font("Segoe UI", Font.ITALIC, 12));
lbl.setForeground(MUTED);
row.add(lbl);
return row;
}
// ==================== UI HELPERS ====================
private static JDialog dialog(String title, int w, int h) {
JDialog d = new JDialog(mainFrame, title, true);
d.setSize(w, h);
d.setLocationRelativeTo(mainFrame);
d.setLayout(new BorderLayout());
return d;
}
private static JPanel formPanel() {
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p.setBackground(WHITE);
p.setBorder(new EmptyBorder(18, 22, 18, 22));
return p;
}
private static JLabel sectionTitle(String text) {
JLabel lbl = new JLabel(text);
lbl.setFont(new Font("Segoe UI", Font.BOLD, 14));
lbl.setForeground(NAVY);
lbl.setBorder(new MatteBorder(0, 0, 2, 0, NAVY));
lbl.setAlignmentX(Component.LEFT_ALIGNMENT);
return lbl;
}
private static JLabel boldLabel(String text) {
JLabel lbl = new JLabel(text);
lbl.setFont(new Font("Segoe UI", Font.BOLD, 13));
lbl.setForeground(new Color(50, 50, 50));
lbl.setAlignmentX(Component.LEFT_ALIGNMENT);
return lbl;
}
private static JLabel smallLabel(String text) {
JLabel lbl = new JLabel(text);
lbl.setFont(new Font("Segoe UI", Font.PLAIN, 11));