diff --git a/.svn/entries b/.svn/entries new file mode 100644 index 0000000..48082f7 --- /dev/null +++ b/.svn/entries @@ -0,0 +1 @@ +12 diff --git a/.svn/format b/.svn/format new file mode 100644 index 0000000..48082f7 --- /dev/null +++ b/.svn/format @@ -0,0 +1 @@ +12 diff --git a/.svn/pristine/00/00ca05828582eb28a3f5e26fd02c533c49e9b831.svn-base b/.svn/pristine/00/00ca05828582eb28a3f5e26fd02c533c49e9b831.svn-base new file mode 100644 index 0000000..4ed0a9c --- /dev/null +++ b/.svn/pristine/00/00ca05828582eb28a3f5e26fd02c533c49e9b831.svn-base @@ -0,0 +1,20 @@ + + + + + + + + + + + + diff --git a/.svn/pristine/01/012d27f712c523f4a8304159764ebcdfdbe5680f.svn-base b/.svn/pristine/01/012d27f712c523f4a8304159764ebcdfdbe5680f.svn-base new file mode 100644 index 0000000..3db7982 --- /dev/null +++ b/.svn/pristine/01/012d27f712c523f4a8304159764ebcdfdbe5680f.svn-base @@ -0,0 +1,1357 @@ +using System; +using System.Collections.Generic; +using System.IO.Ports; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Xml.Serialization; +using System.Windows.Threading; +using System.Diagnostics; +using System.Collections.ObjectModel; +using SafeBagDE70.Model; +using HandyControl.Tools; +using System.Drawing.Printing; +using System.Drawing; +using static HandyControl.Tools.Interop.InteropValues; +using SafeBagDE70.API; +using Newtonsoft.Json; +using System.IO; +using System.Reflection; +using DE70_CMDv2; +using System.Configuration; +using Serilog; +using System.ComponentModel; +using SafeBagDE70.StateMachine; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window; +using System.Runtime.Intrinsics.Arm; +using SafeBagDE70.Services; +using System.Windows.Forms; +using Button = System.Windows.Controls.Button; +using UserControl = System.Windows.Controls.UserControl; +using Application = System.Windows.Application; +using Control = System.Windows.Controls.Control; + + +namespace SafeBagDE70 +{ //Summary + + + public partial class DepositSMUCv2 : UserControl + { + SerialPort serialPortDE70 = new SerialPort(); + SerialPort serialPortSensor= new SerialPort(); + + List sessions = new List(); + public ObservableCollection lvCountItems = new ObservableCollection(); + private DispatcherTimer sensorTimer; + DispatcherTimer? warningTimer = null; + DispatcherTimer? endsessionTimer = null; + DispatcherTimer? backToWelcomeTimer = null; + public long maxQuantitySheet = 10000; + public int quantityStored = 0; + public int totalAllDenominations = 0; + public int posDenomi; + public bool printerFlag = false; + public static string? recvDataString; + public int countSensorTimer = 0; + private PrinterManager printerManager = new PrinterManager(); + + private NotesInSession notesInSession= new NotesInSession(); + //DispatcherTimer? + private volatile bool bIsCounted = false; + + int countTimer = 0; + CCmdRsp cCmdRsp = null; + bool bInitialized = false; + bool bOpenPort = true; + bool bIsMaintain = false; + MainWindow mainWindow = null; + Thread thread = null; + Task taskCounting = null; + public DepositSMUCv2() + { + InitializeComponent(); + } + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + mainWindow=((MainWindow)Application.Current.MainWindow); + InitTransaction(); + StopTimers(); + } + public void InitTransaction() + { + try + { + lblName.Content= "Vietinbank " + Environment.MachineName; + if (AppData.IsAuthenticated) + { + lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})"; + lblTransactionCode.Content = $"Mã GD: {AppData.CurrentCustomerAccount.TransactionCode}"; + } + cCmdRsp = new CCmdRsp(serialPortDE70); + AppData.cCmdRsp = cCmdRsp; + // LoginUsingQRCode(); + InitSerialPorts(); + //Subscrible to the DataReveied event\ + bInitialized = InitSession(); + InitTimers(); + + notesInSession = new NotesInSession(); + spNotesInSession.DataContext = notesInSession; + + AppData.IsInTransaction = true; + ResetButtons(); + btnStart.IsEnabled = true; + ResetTimers(); + var state=GetCDMState(); + if(state.GetSR2()==0x1C) + { + StopTimers(); + ShowError(state.CDMStatus); + } + GetCassetteData(); + } + catch (Exception ex) + { + ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI"); + } + + } + + private void InitSerialPorts() + { + InitSerialPortDE70(); + InitSerialPortSensor(); + } + + private void InitSerialPortSensor() + { + if (serialPortSensor.IsOpen) serialPortSensor.Close(); + + serialPortSensor.PortName = AppData.SensorPort; + serialPortSensor.BaudRate = 9600; + serialPortSensor.Parity = Parity.None; + serialPortSensor.DataBits = 8; + serialPortSensor.StopBits = StopBits.One; + serialPortSensor.ReadTimeout = 1000; + serialPortSensor.WriteTimeout = 1000; + + if(bOpenPort) + { + if (!serialPortSensor.IsOpen) + serialPortSensor.Open(); + } + + } + + private void InitSerialPortDE70() + { + if (serialPortDE70.IsOpen) serialPortDE70.Close(); + + + serialPortDE70.ReadBufferSize = 4096; + serialPortDE70.WriteBufferSize = 4096; + + + serialPortDE70.PortName = AppData.CDMPort; + serialPortDE70.BaudRate = 9600; + serialPortDE70.Parity = Parity.Even; + serialPortDE70.DataBits = 8; + serialPortDE70.StopBits = StopBits.One; + serialPortDE70.ReadTimeout = 10000; + serialPortDE70.WriteTimeout = 10000; + if(bOpenPort) + { + if (!serialPortDE70.IsOpen) + serialPortDE70.Open(); + } + + } + + private void InitTimers() + { + warningTimer = new DispatcherTimer(); // 30 seconds + warningTimer.Interval = new TimeSpan(0, 0, 30); + warningTimer.Tick += WarningTimer_Tick; ; + warningTimer.Stop(); + + endsessionTimer = new DispatcherTimer(); // 60 seconds + endsessionTimer.Interval = new TimeSpan(0, 0, 60); + endsessionTimer.Tick += EndSessionTimer_Tick; + endsessionTimer.Stop(); + + backToWelcomeTimer = new DispatcherTimer(); + backToWelcomeTimer.Interval = new TimeSpan(0, 0, 15); + backToWelcomeTimer.Tick += BackToWelcomeTimer_Tick; + backToWelcomeTimer.Stop(); + + sensorTimer = new DispatcherTimer(); + sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds + sensorTimer.Tick += SensorTimer_Tick; + sensorTimer.Start(); + } + + public void StopWelcomeTimer() + { + if(backToWelcomeTimer != null) + backToWelcomeTimer.Stop(); + } + public void StartWelcomeTimer() + { + if (backToWelcomeTimer != null) + backToWelcomeTimer.Start(); + } + private void BackToWelcomeTimer_Tick(object? sender, EventArgs e) + { + mainWindow.ShowWelcomeScreen(); + } + + private void EndSessionTimer_Tick(object? sender, EventArgs e) + { + Log.Information("7. Timout starting"); + mainWindow.ShowEndSessionScreen(); + StopTimers(); + DoStoreStart(); + bIsCounted = false; + DoCountStart(); + Task.Run(() => + { + taskCounting.Wait(); + DoStoreStart(); + Dispatcher.Invoke(() => + { + EndSession(1); + }); + Log.Information("7. Timout completed"); + }); + + + } + + private void BackToWelcomeScreen() + { + StopTimers(); + + var cdmState = GetCDMState(); + var state = GetCDMState(); + if (state.IsNotesInEscrow > 0) + { + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", false, true); + } + else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0) + { + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", false, true); + } + else if (state.IsNotesInHopper > 0) + { + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", false, true); + } + else if (state.IsCassetteFull != 0) + { + mainWindow.ShowCollectionScreen(); + } + else + { + mainWindow.ShowWelcomeScreen(); + } + } + + private void WarningTimer_Tick(object? sender, EventArgs e) + { + + mainWindow.ShowTimeoutScreen(); + } + + public void EndTransaction() + { + try + { + AppData.IsInTransaction = false; + + if (sensorTimer != null) + { + sensorTimer.Tick -= SensorTimer_Tick; + sensorTimer.Stop(); + } + if (warningTimer != null) + { + warningTimer.Tick -=WarningTimer_Tick; + warningTimer.Stop(); + } + if (endsessionTimer != null) + { + endsessionTimer.Tick -=EndSessionTimer_Tick; + endsessionTimer.Stop(); + } + } + catch (Exception ex) + { + } + } + + + public void InitLvCountItems() + { + if (lvCount.Items.Count == 11) { + foreach(var item in lvCountItems) + { + item.Quantity = "0"; + } + } + else + { + lvCountItems = new ObservableCollection() + { + new LvCountItem{Name = "500",Quantity = "0"}, + new LvCountItem{Name = "1000",Quantity = "0"}, + new LvCountItem{Name = "2000",Quantity = "0"}, + new LvCountItem{Name = "5000",Quantity = "0"}, + new LvCountItem{Name = "10000",Quantity = "0"}, + new LvCountItem{Name = "20000",Quantity = "0"}, + new LvCountItem{Name = "50000",Quantity = "0"}, + new LvCountItem{Name = "100000",Quantity = "0"}, + new LvCountItem{Name = "200000",Quantity = "0"}, + new LvCountItem{Name = "500000",Quantity = "0"}, + new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"}, + }; + } + + + lvCount.ItemsSource = lvCountItems; + + //lvCountItems[0].Quantity = "10"; + } + + private void SensorTimer_Tick(object? sender, EventArgs e) + { + sensorTimer.IsEnabled = false; + try + { + countSensorTimer++; + + if (countSensorTimer % 10 == 0) + { + + var status = printerManager.GetStatus(); + + if(status.StsNOPAPER) + { + AppData.DeviceStatus.PrinterStatus = (int)PrinterStatusCode.PAPEROUT; + StopTimers(); + ShowError("MÁY IN HẾT GIẤY! ĐỀ NGHỊ THAY GIẤY"); + } + else if(status.StsNEARENDPAP) + { + AppData.DeviceStatus.PrinterStatus = (int)PrinterStatusCode.NEARPAPEROUT; + } + + AppData.DeviceStatus.Description = AppData.CDMSTATE.CDMStatus; + AppData.DeviceStatus.DeviceTime = DateTime.Now; + + + APIModels.SendHealthCheck(AppData.DeviceStatus); + } + + sensorTimer.IsEnabled = false; + GetSensorValue(); + sensorTimer.IsEnabled = true; + } + catch (Exception ex) + { + Log.Fatal(ex, "Sensor_Timer"); + } + sensorTimer.IsEnabled = true; + } + Stopwatch watch = new Stopwatch(); + private void GetSensorValue() + { + try + { + + int state = 0; + if (serialPortSensor.IsOpen == true) + { + //serialPortSensor.DiscardInBuffer(); + //serialPortSensor.DiscardOutBuffer(); + + serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3); + var buffer = new byte[16]; + + int n = serialPortSensor.Read(buffer, 0, buffer.Length); + + + for (int i = 1; i < n - 1; i++) + { + if ((buffer[i] == 13) && (buffer[i + 1] == 10)) + { + state = buffer[i - 1] - 48; + if (bInitialized) + { + if (state != 0) + gridMain.IsEnabled = false; + else + gridMain.IsEnabled = true; + } + switch (state) + { + case 0: + lblStatus.Content = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: ĐÓNG"; + break; + case 1: + lblStatus.Content = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: MỞ"; + break; + case 2: + lblStatus.Content = "NGĂN KÉT: MỞ, NGĂN TÚI: ĐÓNG"; + break; + case 3: + lblStatus.Content = "NGĂN KÉT: MỞ, NGĂN TÚI: MỞ"; + break; + } + if (state > 0) + { + if (!bIsMaintain) + { + bIsMaintain = true; + DoMaintaince(); + } + + // TransitionToState("Maintainance"); + } + else + { + if(bIsMaintain) + { + bIsMaintain = false; + mainWindow.ShowWelcomeScreen(); + } + + } + + break; + } + } + + // the code that you want to measure comes here + watch.Stop(); + + var elapsedMs = watch.ElapsedMilliseconds; + Debug.WriteLine(elapsedMs); + watch.Start(); + } + } + catch (Exception ex) + { + Log.Fatal(ex,"GetSensorValue"); + if(serialPortSensor.IsOpen) + serialPortSensor.Close(); + serialPortSensor.Open(); + serialPortSensor.DiscardInBuffer(); + serialPortSensor.DiscardOutBuffer(); + } + } + private void DoMaintaince() + { + StopTimers(); + mainWindow.ShowMaintainanceScreen(); + } + + public int UpdateTotalQuantity() + { + int total = 0; + foreach (var item in lvCountItems) + { + if (item.Name != "Tổng") + { + int quantity = 0; + if (int.TryParse(item.Quantity, out quantity)) + { + total += quantity; + } + } + } + return total; + } + + public int AutoSerialGet() + { + try + { + int ret; + ushort seri_num = 0; + ushort get_num = 0; + bool endflg = false; + + var countSession = new CountSession(); + countSession.IsStored = false; + sessions.Add(countSession); + while (true) + { + AppData.WDTCount = 0; + ret = cCmdRsp.SendSerialSense(); + if (ret == Constants.E_OK) + { + ret = cCmdRsp.GetSerialNum(out seri_num); + if (ret == Constants.E_OK) + { + // Serial number acquisition + + if (cCmdRsp.ChkCntEnd()) + { + endflg = true; + //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]); + } + //Debug.WriteLine("START"); + //Debug.WriteLine($"Num Serial: {seri_num}"); + //Log.Information($"Num Serial: {seri_num}"); + + while (get_num < seri_num) + { + + AppData.WDTCount = 0; + get_num++; + + Log.Information($"Serial Idx: {get_num}/{seri_num}"); + ret = cCmdRsp.SendGetSerial(get_num); + Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}"); + + switch (cCmdRsp.recv_dat.dat[18]) + { + case 0x00: countSession.TempNotes[0]++;break; + case 0x02: + //TempNote[1] ++; + Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}"); + switch (cCmdRsp.recv_dat.dat[17]) + { + case 0x00: countSession.QuantityDenomi[0]++; break; + case 0x01: countSession.QuantityDenomi[1]++; break; + case 0x02: countSession.QuantityDenomi[2]++; break; + case 0x03: countSession.QuantityDenomi[3]++; break; + case 0x04: countSession.QuantityDenomi[4]++; break; + case 0x05: countSession.QuantityDenomi[5]++; break; + case 0x06: countSession.QuantityDenomi[6]++; break; + case 0x07: countSession.QuantityDenomi[7]++; break; + case 0x08: countSession.QuantityDenomi[8]++; break; + case 0x09: countSession.QuantityDenomi[9]++; break; + + } + break; + case 0x03: countSession.TempNotes[2]++; break; + case 0x0b: countSession.TempNotes[3]++; break; + case 0x0c: countSession.TempNotes[4]++; break; + } + UpdateListViewCountItems(); + } + //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds); + if (endflg) + { + break; + } + } + else + { + break; + } + } + else + { + break; + } + } + if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0) + { + sessions.Remove(countSession); + } + }catch(Exception ex) + { + Log.Fatal(ex, "AutoSerialGet"); + } + + //Log.Information(JsonConvert.SerializeObject(sessions)); + return 0; + } + + + + private string GetShortInforFromCountItems() + { + return JsonConvert.SerializeObject(lvCountItems); + } + + private bool DoCountStart() + { + bool bSuccess = true; + printerFlag = false; + + string currentMethod = MethodBase.GetCurrentMethod().Name; + try + { + if(bOpenPort) + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART); + if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { } + do + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE); + } + while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status + } + + + taskCounting = Task.Run(() => + { + Log.Information("Before AutoCount: " + GetShortInforFromCountItems()); + bIsCounted = false; + AutoSerialGet(); + bIsCounted = true; + Log.Information("After AutoCount: " + GetShortInforFromCountItems()); + }); + + + } + catch (Exception ex) + { + bSuccess = false; + Log.Fatal(ex,currentMethod); + } + return bSuccess; + } + private byte[] GetCassetteData() + { + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_READ_CASSETTE); + var data=cCmdRsp.recv_dat.dat; + + StringBuilder str=new StringBuilder(); + var recv_dat = cCmdRsp.recv_dat; + + AppData.DeviceStatus.Notes = GetNotes(recv_dat.dat); + str.Append("DATA:"); + for (int i = 0; i < recv_dat.leng - 1; i++) + { + var dat = string.Format("{0:X2} ", recv_dat.dat[i]); + str.Append(dat); + } + Log.Information("[CASSETTE]" + str.ToString()); + return (byte[])data.Clone(); + } + private int GetNotes(byte[] cassetData) + { + int notes = 0; + int offset = 14; + for (int i = 0; i < 10; i++) + { + notes += cassetData[2 * i + offset] * 256 + cassetData[2 * i + 1 + offset]; + } + return notes; + } + private bool CheckStoreValid(byte[] previousCassetData, byte[] newCassetData,List countSessions) + { + var quantFromSession = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//500.000->500 + foreach (var session in countSessions) { + if ((session.IsStored==false)) + { + for (int i = 0; i < 10; i++) + quantFromSession[i] += session.QuantityDenomi[i]; + } + } + var nPreviousCassetData = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + var nNewCassetData = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + int offset = 14; + bool bValid = true; + for(int i=0;i<10;i++) + { + nPreviousCassetData[i] = previousCassetData[2*i + offset] * 256 + previousCassetData[2*i + 1 + offset]; + nNewCassetData[i]=newCassetData[2*i + offset] * 256 + newCassetData[2*i+1+ offset]; + if (nNewCassetData[i] - nPreviousCassetData[i]!=quantFromSession[i]) + { + bValid = false; + break; + } + } + return bValid; + } + + private void UpdateListViewCountItems() + { + Dispatcher.Invoke(DispatcherPriority.Normal, () => + { + double sum = 0; + if (sessions != null && sessions.Count > 0) + { + for (int i = 0; i < 10; i++) + { + int quantity = 0; + for (int j = 0; j < sessions.Count; j++) + { + + quantity += sessions[j].QuantityDenomi[9 - i]; + + } + lvCountItems[i].Quantity = quantity.ToString(); + sum += lvCountItems[i].getValue(); + + } + //Update amount of money + lvCountItems[10].Quantity = UpdateTotalQuantity().ToString(); + lvCountItems[10].Value = sum.ToString(); + + //Update Notes In Sesion + notesInSession.GenuineNotes = 0; + notesInSession.RejectNotes = 0; + + for (int j = 0; j < sessions.Count; j++) + { + if (sessions[j].IsStored == false) + { + for (int i = 0; i < 10; i++) + { + notesInSession.GenuineNotes += sessions[j].QuantityDenomi[9 - i]; + } + notesInSession.RejectNotes += sessions[j].TempNotes.Sum(); + } + } + } + else + { + for (int i = 0; i < 11; i++) + { + lvCountItems[i].Quantity = "0"; + lvCountItems[i].Value = "0"; + } + } + }); + + } + + public bool DoCheck() + { + bool bSuccess = true; + string currentMethod = MethodBase.GetCurrentMethod().Name; + try + { + Log.Information("Before Check: "+GetShortInforFromCountItems()); + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + + + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL); + + Log.Information(JsonConvert.SerializeObject(sessions)); + sessions.RemoveAll(item=>!item.IsStored); + Log.Information(JsonConvert.SerializeObject(sessions)); + UpdateListViewCountItems(); + + + Log.Information("After Check: "+GetShortInforFromCountItems()); + } + catch (Exception ex) + { + bSuccess = false; + Log.Fatal(ex, currentMethod); + } + return bSuccess; + } + private bool WaitUntilCountReady(int nSecondTimeout) + { + CDMSTATE state = null; + int nTimes = 0; + bool bSuccess = false; + while (true) + { + state = GetCDMState(); + if (state.GetSR2() == 0x07) + { + bSuccess = true; + break; + } + nTimes++; + Thread.Sleep(1000); + if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout) + break; + } + return bSuccess; + } + private bool WaitUntilEnscrowEmpty(int nSecondTimeout) + { + CDMSTATE state = null; + int nTimes = 0; + bool bSuccess = false; + while(true) + { + state = GetCDMState(); + if (state.IsNotesInEscrow == 0) + { + bSuccess = true; + break; + } + nTimes++; + Thread.Sleep(1000); + if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout) + break; + } + return bSuccess; + } + private bool DoStoreStart() + { + + bool bSuccess = true; + printerFlag = true; + + string currentMethod = MethodBase.GetCurrentMethod().Name; + + try + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + //sessions.Add(new CountSession()); + + // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone(); + + //Debug.WriteLine(quantityStored); + + var previousCassetData = GetCassetteData(); + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART); + bSuccess=WaitUntilCountReady(10); + var newCasstData = GetCassetteData(); + bool bValid= CheckStoreValid(previousCassetData,newCasstData,sessions); + if(bValid) + { + if (bSuccess) + { + foreach (var item in sessions) + { + item.IsStored = true; + } + quantityStored = UpdateTotalQuantity(); + Log.Information("Stored " + GetShortInforFromCountItems()); + } + else + { + Log.Error("Store FAIL " + GetShortInforFromCountItems()); + } + } + else + { + string str = "PHIÊN GIAO DỊCH KHÔNG HỢP LỆ (SỐ TIỀN GIAO DỊCH KHÔNG KHỚP), VUI LÒNG BÁO CÁO LẠI CHI NHÁNH"; + Log.Information(str); + ShowError(str); + } + + Thread.Sleep(2000); + } + catch (Exception ex) + { + bSuccess = false; + Log.Fatal(ex, currentMethod); + } + return bSuccess; + } + + + private bool DoStart() + { + bool bSuccess = true; + InitSession(); + string currentMethod = MethodBase.GetCurrentMethod().Name; + AppData.IsInTransaction = true; + try + { + + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE); + + var recvData = cCmdRsp.recv_dat; + + if (recvData.dat[14] == recvData.dat[16]) + { + cCmdRsp.SendLock(); + } + else + { + cCmdRsp.SendEventFix(recvData.dat[16]); + cCmdRsp.SendLock(); + } + if (cCmdRsp.recv_dat.dat[0]!=0x40) + { + bSuccess = false; + } + } + catch (Exception ex) + { + bSuccess = false; + Log.Fatal(ex, currentMethod); + } + return bSuccess; + } + + + private bool DoEnd() + { + bool bSuccess = false; + var state = GetCDMState(); + StopTimers(); + Log.Information("CDM State: " + JsonConvert.SerializeObject(state)); + var lstEnabledControls = new List { btnEnd, btnCountStart }; + if (state.IsNotesInEscrow > 0) + { + btnEnd.IsEnabled = true; + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true,true); + } + else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0) + { + btnEnd.IsEnabled = true; + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true, true); + } + else if(state.IsNotesInHopper>0) + { + btnEnd.IsEnabled = true; + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", true, true); + } + else + { + bSuccess = true; + AppData.WDTCount = 0; + EndSession(); + + btnStart.IsEnabled = true; + btnLogout.IsEnabled = true; + + ResetTimers(); + } + return bSuccess; + } + private bool DoLogout() + { + bool bSuccess = false; + var state = GetCDMState(); + Log.Information("CDM State: " + JsonConvert.SerializeObject(state)); + InitLvCountItems(); + if (state.IsNotesInEscrow > 0) + { + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true); + } + else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0) + { + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true); + } + else //if (double.Parse(lvCountItems[10].Value)== 0) + { + bSuccess = true; + ResetSessions(); + BackToWelcomeScreen(); + } + return bSuccess; + } + + private void EndSession(int _CountingState=0) + { + string currentMethod = MethodBase.GetCurrentMethod().Name; + + //Remove sessions with store flag is false + + sessions.RemoveAll(item => !item.IsStored); + UpdateListViewCountItems(); + + var totalQuantity = lvCountItems[10].Quantity; + var totalValue = lvCountItems[10].Value; + + try + { + Log.Information(currentMethod); + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + if (double.Parse(totalValue) > 0) + { + var data2Send = new CountingData2Send + { + TransactionCode = AppData.CurrentCustomerAccount.TransactionCode, + Sessions = sessions, + MachineId = Environment.MachineName, + UserId = AppData.CurrentCustomerAccount.CustomerId, + MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"), + GenuineNotes = quantityStored, + CountingState= _CountingState + }; + + SyncData(data2Send); + //Reset all and ready to next session + + if (printerFlag == true) + { + if (double.Parse(totalValue) > 0) + PrintReceipt(); + printerFlag = false; + + } + + String strNotify = $"BẠN VỪA THỰC HIỆN NỘP TIỀN VÀO MÁY CDM:\r\n" + + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n" + + $"SỐ TIỀN: {totalValue} VND\r\n"; + mainWindow.ShowInformationScreen(strNotify, false, false); + ResetSessions(); + StartWelcomeTimer(); + + } + else + { + mainWindow.ShowWelcomeScreen(); + } + //SendData2Server + } + catch (Exception ex) + { + Log.Fatal(ex, currentMethod); + } + } + + private async Task SyncData(CountingData2Send data2Send) + { + Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send)); + var history = Save2DB(data2Send); + Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send)); + bool bSuccess = await APIModels.SendCountingData(data2Send); + if (bSuccess) + { + history.IsSent = true; + Update2DB(history); + Log.Information("Sending data to server successfully"); + } + else + { + Log.Information("Sending data to server failed"); + } + } + + public History Save2DB(CountingData2Send data2Send) + { + var data = JsonConvert.SerializeObject(data2Send); + var history = new History + { + Data = data, + DepositTime = DateTime.Now, + IsSent = false, + UserCode = AppData.CurrentCustomerAccount.CustomerId + }; + try + { + using (var db = new CDMDbContext()) + { + db.Histories.Add(history); + db.SaveChanges(); + } + } + catch (Exception ex) + { + Log.Fatal(ex,"Save2DB Exception"); + } + return history; + } + public History Update2DB(History history) + { + + try + { + using (var db = new CDMDbContext()) + { + db.Histories.Update(history); + db.SaveChanges(); + } + } + catch (Exception ex) + { + Log.Fatal(ex,"Update2DB Exception"); + } + return history; + } + + private void ShowError(string strError) + { + //gridMain.IsEnabled = false; + //btnCollect2.Visibility=Visibility.Collapsed; + //panelError.Visibility = Visibility.Visible; + //lblError.Text = strError; + //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen(); + mainWindow.ShowErrorScreen(strError); + } + + public CDMSTATE GetCDMState() + { + return AppData.GetCDMState(); + } + private bool InitSession() + { + try + { + //Check status + var cdmState = GetCDMState(); + + if (cdmState.IsCassetteFull != 0) + { + mainWindow.ShowCollectionScreen(); + return false; + } + else if (cdmState.IsNotesInEscrow != 0) + { + mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC"); + } + else + { + ResetSessions(); + return true; + } + + } + catch(Exception ex) + { + Log.Fatal(ex,"InitSession"); + } + return false; + } + + private void ResetSessions() + { + InitLvCountItems(); + sessions.Clear(); + quantityStored = 0; + maxQuantitySheet = 0; + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK); + } + + private void PrintReceipt() + { + Log.Information("PrintReceipt"); + var shopName = AppData.CurrentCustomerAccount.Name; + var shopCode = AppData.CurrentCustomerAccount.CustomerId; + var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM"; + var storeAccountNumber = 686868686688; + var currentTime = DateTime.Now; + var printDocument = new PrintDocument(); + + System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png"); + System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png"); + + printDocument.PrinterSettings.PrinterName = "CUSTOM K80"; + printDocument.PrintPage += (sender, e) => + { + int fontSize = 8; + int lineSpace = 20; + float marginLeft = 25; + float marginTop = 5; + float width = 275; + float height = 280; + + float LogoAeonWidth = 90; // Chiều rộng của LogoAeon + float LogoAeonHeight = 30; // Chiều cao của LogoAeon + float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang + float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon + + float LogoVietinWidth = 90; // Chiều rộng của LogoVietin + float LogoVietinHeight = 30; // Chiều cao của LogoVietin + float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang + float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin + + e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight); + e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight); + + + e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight); + e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight); + + e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height); + + + e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50)); + e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65)); + e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65)); + e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65)); + e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65)); + e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65)); + e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65)); + e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65)); + e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65)); + e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65)); + e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65)); + // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string, + // or for more complex scenarios, directly manipulate the byte stream sent to the printer. + }; + printDocument.Print(); + + + } + + private void UserControl_Unloaded(object sender, RoutedEventArgs e) + { + EndTransaction(); + } + public void ResetTimers() + { + StopTimers(); + StartTimers(); + } + + public void StartTimers() + { + if(warningTimer!=null && endsessionTimer != null) + { + warningTimer.Start(); + endsessionTimer.Start(); + } + + } + + public void StopTimers() + { + if(warningTimer!=null && endsessionTimer !=null) + { + warningTimer.Stop(); + endsessionTimer.Stop(); + } + + } + + private void ResetButtons() + { + btnStart.IsEnabled = false; + btnCountStart.IsEnabled = false; + btnCheck.IsEnabled = false; + btnStoreStart.IsEnabled = false; + btnEnd.IsEnabled = false; + btnLogout.IsEnabled = false; + } + + + + private Button _previousClickedButton = null; + private void btnCommon_Click(object sender, RoutedEventArgs e) + { + + var btn = sender as Button; + if (_previousClickedButton != null) + { + _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent; + _previousClickedButton.BorderThickness = new Thickness(1); + } + + // Set the border of the currently clicked button + btn.BorderBrush = System.Windows.Media.Brushes.DarkRed; + btn.BorderThickness = new Thickness(3); + + // Update the previously clicked button reference + _previousClickedButton = btn; + SoundManager.StartButtonPressSound(); + // Console.Beep(800, 200); + StopTimers(); + bool bResult = false; + if (btn==btnStart) + { + Log.Information("Deposit starting"); + Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId); + Log.Information("1. Start starting"); + ResetButtons(); + bResult = DoStart(); + if (bResult) + { + btnCountStart.IsEnabled = true; + ResetTimers(); + } + else + { + btnStart.IsEnabled = true; + btnLogout.IsEnabled = true; + } + if (bResult) + Log.Information("1. Start completed"); + else + Log.Information("1. Start failed"); + + } + else if(btn==btnCountStart) + { + + Log.Information("2. Count starting"); + ResetButtons(); + bResult = DoCountStart(); + Task.Run(() => + { + taskCounting.Wait(); + Dispatcher.Invoke(() => + { + btnCountStart.IsEnabled = true; + btnCheck.IsEnabled = true; + btnStoreStart.IsEnabled = true; + ResetTimers(); + Log.Information("2. Count completed"); + }); + }); + + + } + else if(btn==btnCheck) + { + Log.Information($"3. Check starting"); + ResetButtons(); + bResult = DoCheck(); + btnCountStart.IsEnabled= true; + ResetTimers(); + if (bResult) + Log.Information($"3. Check completed"); + else + Log.Information($"3. Check failed"); + } + else if (btn == btnStoreStart) + { + //TransitionToState("Store"); + Log.Information("4. Store starting"); + ResetButtons(); + bResult = DoStoreStart(); + btnEnd.IsEnabled= true; + btnCountStart.IsEnabled = true; + ResetTimers(); + if(bResult) + Log.Information("4. Store completed"); + else + Log.Information("4. Store failed"); + } + else if (btn == btnEnd) + { + // TransitionToState("End"); + Log.Information("5. End starting"); + ResetButtons(); + bResult = DoEnd(); + //btnStart.IsEnabled = true; + //btnLogout.IsEnabled = true; + //ResetTimers(); + if (bResult) + Log.Information("5. End Completed"); + else + Log.Information("5. End failed"); + } + else if (btn == btnLogout) + { + Log.Information("6. Exit starting"); + bResult = DoLogout(); + if (bResult) + Log.Information("6. Exit Completed"); + else + Log.Information("6. Exit failed"); + } + } + } +} + diff --git a/.svn/pristine/01/016232993cd3b1cbb037185c868e15aa9996813b.svn-base b/.svn/pristine/01/016232993cd3b1cbb037185c868e15aa9996813b.svn-base new file mode 100644 index 0000000..5303b8d --- /dev/null +++ b/.svn/pristine/01/016232993cd3b1cbb037185c868e15aa9996813b.svn-base @@ -0,0 +1,20 @@ +using Microsoft.Extensions.Configuration; +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Data; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows; + +namespace SafeBagDE70 +{ + /// + /// Interaction logic for App.xaml + /// + public partial class App : Application + { + + } +} diff --git a/.svn/pristine/05/051bf169707f7befae027e153dadad082679dd03.svn-base b/.svn/pristine/05/051bf169707f7befae027e153dadad082679dd03.svn-base new file mode 100644 index 0000000..60da5ed --- /dev/null +++ b/.svn/pristine/05/051bf169707f7befae027e153dadad082679dd03.svn-base @@ -0,0 +1,189 @@ +using System; +using System.Collections.Generic; +using System.IO.Ports; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Xml.Serialization; +using System.Windows.Threading; +using System.Diagnostics; +using SafeBagDE70.Services; + +namespace SafeBagDE70 +{ + /// + /// Interaction logic for MainWindow.xaml + /// + /// + public partial class MainWindow : HandyControl.Controls.Window + { + private WelcomeUC _welcomeUC; + private DepositSMUCv2 _depositUC; + private CollectionUC _collectionUC; + private InformationUC _informationUC; + private ErrorUC _errorUC; + private UserControl _currentUC; + private UserControl _prevUC; + private TimeoutUC _timeoutUC; + private MaintainanceUC _maintainanceUC; + private EndSessionUC _endSessionUC; + private object objLock = new object(); + public MainWindow() + { + InitializeComponent(); + Loaded += MainWindow_Loaded; + } + + private void MainWindow_Loaded(object sender, RoutedEventArgs e) + { + AppData.Init(); + if (_welcomeUC == null) _welcomeUC = new WelcomeUC(); + if (_collectionUC == null) _collectionUC = new CollectionUC(); + if (_informationUC == null) _informationUC = new InformationUC(); + if (_errorUC == null) _errorUC = new ErrorUC(); + if (_depositUC == null) _depositUC = new DepositSMUCv2(); + if (_timeoutUC == null) _timeoutUC = new TimeoutUC(); + if (_maintainanceUC == null) _maintainanceUC = new MaintainanceUC(); + if (_endSessionUC == null) _endSessionUC = new EndSessionUC(); + + + gridMain.Children.Add(_welcomeUC); + gridMain.Children.Add(_depositUC); + gridMain.Children.Add(_collectionUC); + gridMain.Children.Add(_informationUC); + gridMain.Children.Add(_errorUC); + gridMain.Children.Add(_timeoutUC); + gridMain.Children.Add(_maintainanceUC); + gridMain.Children.Add(_endSessionUC); + + ShowWelcomeScreen(); + //ShowDepositScreen(); + } + + public void HideAll() + { + lock(objLock) + { + foreach (var item in gridMain.Children) + { + if (item != null) + (item as UserControl).Visibility = Visibility.Hidden; + } + //_collectionUC.Visibility = Visibility.Hidden; + //_informationUC.Visibility = Visibility.Hidden; + //_errorUC.Visibility = Visibility.Hidden; + //_depositUC.Visibility = Visibility.Hidden; + //_welcomeUC.Visibility = Visibility.Hidden; + //_maintainanceUC.Visibility=Visibility.Hidden; + //_endSessionUC.Visibility = Visibility.Hidden; + SoundManager.StopWarningSound(); + } + + } + public void ShowEndSessionScreen() + { + _prevUC = _currentUC; + HideAll(); + _endSessionUC.Visibility= Visibility.Visible; + } + public void ShowInformationScreen(string strInfor,bool bContinue=false,bool bPlaySound=true,List lstControls=null) + { + _prevUC = _currentUC; + _currentUC = _informationUC; + HideAll(); + _informationUC.Visibility = Visibility.Visible; + _informationUC.ShowInfor(strInfor, bContinue, bPlaySound,lstControls); + } + public void ShowErrorScreen(string strError) + { + _prevUC = _currentUC; + _currentUC = _errorUC; + HideAll(); + _errorUC.Visibility = Visibility.Visible; + _errorUC.ShowInfor(strError); + } + public void ShowWelcomeScreen() + { + _depositUC.StopTimers(); + _depositUC.StopWelcomeTimer(); + _prevUC = _currentUC; + _currentUC = _welcomeUC; + HideAll(); + _welcomeUC.Init(); + + _welcomeUC.Visibility = Visibility.Visible; + } + public void ShowDepositScreen(bool bInit=true) + { + _depositUC.ResetTimers(); + _prevUC = _currentUC; + _currentUC = _depositUC; + HideAll(); + _depositUC.Visibility = Visibility.Visible; + if(bInit) + { + _depositUC.EndTransaction(); + _depositUC.InitTransaction(); + } + } + + public void ShowCollectionScreen() + { + _prevUC = _currentUC; + _currentUC = _collectionUC; + HideAll(); + _collectionUC.Init(); + _collectionUC.Visibility = Visibility.Visible; + } + public bool IsMaintainanceScreen() + { + return _currentUC == _maintainanceUC; + } + public DepositSMUCv2 GetDepositScreen() + { + return _depositUC; + } + public void ShowMaintainanceScreen() + { + _prevUC = _currentUC; + HideAll(); + _maintainanceUC.Visibility = Visibility.Visible; + } + public void ShowTimeoutScreen() + { + _prevUC = _currentUC; + HideAll(); + _timeoutUC.Visibility = Visibility.Visible; + } + public void StopTimers() + { + _depositUC.StopTimers(); + } + + public bool DoCheck() + { + return _depositUC.DoCheck(); + } + public void ResetTimers() + { + _depositUC.ResetTimers(); + } + public void BackScreen() + { + HideAll(); + _prevUC.Visibility = Visibility.Visible; + _currentUC = _prevUC; + } + } +} diff --git a/.svn/pristine/05/0544c1c531cfeb0e85da5d25c02fd7df8910b301.svn-base b/.svn/pristine/05/0544c1c531cfeb0e85da5d25c02fd7df8910b301.svn-base new file mode 100644 index 0000000..1f8400f Binary files /dev/null and b/.svn/pristine/05/0544c1c531cfeb0e85da5d25c02fd7df8910b301.svn-base differ diff --git a/.svn/pristine/05/05ed1e63594d8f555955e90a3b4c1661f7f03e44.svn-base b/.svn/pristine/05/05ed1e63594d8f555955e90a3b4c1661f7f03e44.svn-base new file mode 100644 index 0000000..b4ced11 --- /dev/null +++ b/.svn/pristine/05/05ed1e63594d8f555955e90a3b4c1661f7f03e44.svn-base @@ -0,0 +1,211 @@ +using CoreScanner; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Xml; + +namespace SafeBagDE70 +{ + /// + /// Interaction logic for WelcomeWindow.xaml + /// + public partial class WelcomeUC : UserControl + { + public string? QRCodeContent = null; + public string? PinCode = null; + public bool IsAuthenticated = false; + public CCoreScannerClass? cCoreScannerClass=null; + public WelcomeUC() + { + InitializeComponent(); + InitQRCodeScanner(); + } + private void LoginButton_Click(object sender, RoutedEventArgs e) + { + string pin = PinCodeBox.Password; + + if (ValidatePin(pin)) + { + PinCode=PinCodeBox.Password.ToString(); + if (AppData.customerAccounts != null) + { + CustomerAccount? cca = null; + if (PinCode != null) + { + var strPincode = PinCode.ToUpper(); + cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault(); + } + + if (cca != null) + { + ((MainWindow)Application.Current.MainWindow).ShowDepositScreen(); + //DialogResult = true; + //this.Close(); + } + else + { + lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại"; + } + } + } + else + { + MessageBox.Show("Invalid PIN. Please try again."); + } + } + + private void ForgotPin_Click(object sender, RoutedEventArgs e) + { + MessageBox.Show("Forgot PIN clicked."); + } + + private void Help_Click(object sender, RoutedEventArgs e) + { + MessageBox.Show("Help clicked."); + } + + private bool ValidatePin(string pin) + { + return true; + + } + private async void PinCodeButton_Click(object sender, RoutedEventArgs e) + { + var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe") + { + UseShellExecute = true + }; + Process.Start(onScreenKeyboardProcess); + try + { + //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink"; + //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe"); + //Process.Start(keyboardPath); + // AutomationElement.FromHandle(-1); + + // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe"; + // Process.Start(keyboardPath); + //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://")); + + //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe") + //{ + // UseShellExecute = true + //}; + //Process.Start(onScreenKeyboardProcess); + + QrCodePanel.Visibility = Visibility.Collapsed; + PinCodePanel.Visibility = Visibility.Visible; + + + cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent); + } + catch { + + } + + } + private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e) + { + PinCodePanel.Visibility = Visibility.Collapsed; + QrCodePanel.Visibility=Visibility.Visible; + cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent); + + + } + public void InitQRCodeScanner() + { + try + { + // Instantiate CoreScanner Class + cCoreScannerClass = new CCoreScannerClass(); + + // Call Open API + short[] scannerTypes = new short[1]; // Scanner Types you are interested in + scannerTypes[0] = 1; // 1 for all scanner types + short numberOfScannerTypes = 1; // Size of the scannerTypes array + int status; // Extended API return code + + cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status); + + // Subscribe for barcode events in cCoreScannerClass + + + // Let's subscribe for events + int opcode = 1001; // Method for Subscribe events + string outXML; // XML Output + string inXML = "" + + "" + + "1" + // Number of events you want to subscribe + "1" + // Comma separated event IDs + "" + + ""; + + cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status); + } + catch (Exception exp) + { + Console.WriteLine("Something wrong please check... " + exp.Message); + } + } + private void OnBarcodeEvent(short eventType, ref string pscanData) + { + string xmlString = pscanData; + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(xmlString); + + XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel"); + string rawDataHex = rawDataNode.InnerText.Trim(); + + QRCodeContent = HexStringToString(rawDataHex); + this.Dispatcher.Invoke(() => + { + + + if (AppData.customerAccounts != null) + { + CustomerAccount? cca = null; + if (QRCodeContent != null) + { + cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault(); + } + + if (cca != null) + { + cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent); + //DialogResult = true; + //this.Close(); + } + else + { + lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại"; + } + } + + }); + } + + static string HexStringToString(string hexString) + { + string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); + byte[] bytes = new byte[hexValues.Length]; + + for (int i = 0; i < hexValues.Length; i++) + { + bytes[i] = Convert.ToByte(hexValues[i], 16); + } + return Encoding.ASCII.GetString(bytes); + } + } +} diff --git a/.svn/pristine/06/0647e0e9088716b5fe424ece48a99f9eeb32b877.svn-base b/.svn/pristine/06/0647e0e9088716b5fe424ece48a99f9eeb32b877.svn-base new file mode 100644 index 0000000..576d5f4 --- /dev/null +++ b/.svn/pristine/06/0647e0e9088716b5fe424ece48a99f9eeb32b877.svn-base @@ -0,0 +1,826 @@ +using System; +using System.Collections.Generic; +using System.IO.Ports; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Channels; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Xml.Serialization; +using System.Windows.Threading; +using System.Diagnostics; +using System.Collections.ObjectModel; +using SafeBagDE70.Model; +using HandyControl.Tools; +using System.Drawing.Printing; +using System.Drawing; +using static HandyControl.Tools.Interop.InteropValues; +using SafeBagDE70.API; +using Newtonsoft.Json; +using System.IO; +using System.Reflection; +using DE70_CMDv2; +using System.Configuration; + + +namespace SafeBagDE70 +{ //Summary + + + public partial class DepositUC : UserControl + { + SerialPort serialPortDE70 = new SerialPort(); + SerialPort serialPortSensor= new SerialPort(); + + List sessions = new List(); + ObservableCollection lvCountItems = new ObservableCollection(); + private DispatcherTimer timer; + private DispatcherTimer sensorTimer; + + int countTimer = 0; + CCmdRsp cCmdRsp = null; + bool bInitialized = false; + + + public DepositUC() + { + InitializeComponent(); + + } + + private void UserControl_Loaded(object sender, RoutedEventArgs e) + { + InitTransaction(); + + } + public void InitTransaction() + { + try + { + if (AppData.IsAuthenticated) + { + lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})"; + } + + // LoginUsingQRCode(); + if (serialPortDE70.IsOpen) serialPortDE70.Close(); + if (serialPortSensor.IsOpen) serialPortSensor.Close(); + + serialPortDE70.ReadBufferSize = 4096; + serialPortDE70.WriteBufferSize = 4096; + cCmdRsp = new CCmdRsp(serialPortDE70); + AppData.cCmdRsp = cCmdRsp; + + serialPortDE70.PortName = "COM4"; + serialPortDE70.BaudRate = 9600; + serialPortDE70.Parity = Parity.Even; + serialPortDE70.DataBits = 8; + serialPortDE70.StopBits = StopBits.One; + serialPortDE70.ReadTimeout = 10000; + serialPortDE70.WriteTimeout = 10000; + + serialPortSensor.PortName = "COM3"; + serialPortSensor.BaudRate = 9600; + serialPortSensor.Parity = Parity.None; + serialPortSensor.DataBits = 8; + serialPortSensor.StopBits = StopBits.One; + serialPortSensor.ReadTimeout = 1000; + serialPortSensor.WriteTimeout = 1000; + + + //Subscrible to the DataReveied event + if (!serialPortDE70.IsOpen) + serialPortDE70.Open(); + + if (!serialPortSensor.IsOpen) + serialPortSensor.Open(); + + bInitialized = InitSession(); + + timer = new DispatcherTimer(); + timer.Interval = new TimeSpan(0, 0, 10); //10 seconds + timer.Tick += Timer_Tick; + timer.Start(); + + sensorTimer = new DispatcherTimer(); + sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds + sensorTimer.Tick += SensorTimer_Tick; + sensorTimer.Start(); + + } + catch (Exception ex) + { + ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI"); + } + + } + + public void EndTransaction() + { + try + { + AppData.IsInTransaction = false; + if (timer != null) + { + timer.Tick -= Timer_Tick; + timer.Stop(); + } + if (sensorTimer != null) + { + sensorTimer.Tick -= SensorTimer_Tick; + sensorTimer.Stop(); + } + } + catch (Exception ex) + { + } + } + public void SetStep(int step) + { + switch(step) + { + case 0: + btnStart.IsEnabled = true; + btnCheck.IsEnabled = false; + btnCountStart.IsEnabled = false; + btnStoreStart.IsEnabled = false; + btnEnd.IsEnabled = false; + break; + case 1: + btnStart.IsEnabled = false; + btnCheck.IsEnabled = false; + btnCountStart.IsEnabled = true; + btnStoreStart.IsEnabled = false; + btnEnd.IsEnabled =false; + break; + case 2: + btnStart.IsEnabled = false; + btnCheck.IsEnabled = true; + btnCountStart.IsEnabled = true; + btnStoreStart.IsEnabled = true; + btnEnd.IsEnabled = false; + break; + case 3: + btnStart.IsEnabled = false; + btnCheck.IsEnabled = true; + btnCountStart.IsEnabled = true; + btnStoreStart.IsEnabled = true; + btnEnd.IsEnabled = true; + break; + } + } + + public void InitSessionCount() + { + if (lvCount.Items.Count == 11) { + foreach(var item in lvCountItems) + { + item.Quantity = "0"; + } + } + else + { + lvCountItems.Add(new LvCountItem + { + Name = "500", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "1000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "2000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "5000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "10000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "20000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "50000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "100000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "200000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "500000", + Quantity = "0" + }); + lvCountItems.Add(new LvCountItem + { + Name = "Tổng", + Quantity = "0" + }); + lvCountItems[10].Quantity = "0"; + lvCountItems[10].Value = "0"; + } + + + lvCount.ItemsSource = lvCountItems; + + //lvCountItems[0].Quantity = "10"; + } + public long maxQuantitySheet = 10000; + public int quantityStored = 0; + public int totalAllDenominations = 0; + public int posDenomi; + public bool printerFlag = false; + public static string? recvDataString; + public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 }; + public int[] Notes = new int[5] { 0, 0, 0, 0, 0 }; + + private void SensorTimer_Tick(object? sender, EventArgs e) + { + try + { + timer.IsEnabled = false; + GetSensorValue(); + if (AppData.IsInTransaction) + { + if (AppData.WDTCount == 30) + { + ((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen(); + } + else if (AppData.WDTCount == 60) + { + //Nhận tiền và Kết thúc + StoreStart(); + EndSession(); + + ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen(); + AppData.IsInTransaction = false; + AppData.WDTCount = 0; + } + AppData.WDTCount++; + } + else + { + AppData.WDTCount = 0; + } + timer.IsEnabled = true; + } + catch (Exception) + { + + } + + + } + Stopwatch watch = new Stopwatch(); + private void GetSensorValue() + { + try + { + + int state = 0; + if (serialPortSensor.IsOpen == true) + { + //serialPortSensor.DiscardInBuffer(); + //serialPortSensor.DiscardOutBuffer(); + + serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3); + var buffer = new byte[16]; + + int n = serialPortSensor.Read(buffer, 0, buffer.Length); + + + for (int i = 1; i < n - 1; i++) + { + if ((buffer[i] == 13) && (buffer[i + 1] == 10)) + { + state = buffer[i - 1] - 48; + if (bInitialized) + { + if (state != 0) + gridMain.IsEnabled = false; + else + gridMain.IsEnabled = true; + } + switch (state) + { + case 0: + lblStatus.Content = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: ĐÓNG"; + break; + case 1: + lblStatus.Content = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: MỞ"; + break; + case 2: + lblStatus.Content = "NGĂN KÉT: MỞ, NGĂN TÚI: ĐÓNG"; + break; + case 3: + lblStatus.Content = "NGĂN KÉT: MỞ, NGĂN TÚI: MỞ"; + break; + } + break; + } + } + + // the code that you want to measure comes here + watch.Stop(); + + var elapsedMs = watch.ElapsedMilliseconds; + Debug.WriteLine(elapsedMs); + watch.Start(); + } + } + catch (Exception ex) + { + AppData.LogException("GetSensorValue", ex.ToString()); + if(serialPortSensor.IsOpen) + serialPortSensor.Close(); + serialPortSensor.Open(); + serialPortSensor.DiscardInBuffer(); + serialPortSensor.DiscardOutBuffer(); + } + } + + private void Timer_Tick(object? sender, EventArgs e) + { + timer.IsEnabled = false; + + APIModels.SendHealthCheck(); + + timer.IsEnabled = true; + } + public int UpdateTotalQuantity() + { + int total = 0; + foreach (var item in lvCountItems) + { + if (item.Name != "Tổng") + { + int quantity = 0; + if (int.TryParse(item.Quantity, out quantity)) + { + total += quantity; + } + } + } + return total; + } + + public int AutoSerialGet(SerialPort serialPort) + { + int ret; + ushort seri_num = 0; + ushort get_num = 0; + bool endflg = false; + + while (true) + { + ret = cCmdRsp.SendSerialSense(); + if (ret == Constants.E_OK) + { + ret = cCmdRsp.GetSerialNum(out seri_num); + if (ret == Constants.E_OK) + { + // Serial number acquisition + + if (cCmdRsp.ChkCntEnd()) + { + endflg = true; + Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]); + } + Debug.WriteLine("START"); + Debug.WriteLine($"Num Serial: {seri_num}"); + + while (get_num < seri_num) + { + get_num++; + ret = cCmdRsp.SendGetSerial(get_num); + + + switch (cCmdRsp.recv_dat.dat[18]) + { + case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break; + case 0x02: + //TempNote[1] ++; + switch (cCmdRsp.recv_dat.dat[17]) + { + case 0x00: TempQuantity[0]++; break; + case 0x01: TempQuantity[1]++; break; + case 0x02: TempQuantity[2]++; break; + case 0x03: TempQuantity[3]++; break; + case 0x04: TempQuantity[4]++; break; + case 0x05: TempQuantity[5]++; break; + case 0x06: TempQuantity[6]++; break; + case 0x07: TempQuantity[7]++; break; + case 0x08: TempQuantity[8]++; break; + case 0x09: TempQuantity[9]++; break; + + } + break; + case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break; + case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break; + case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break; + } + } + + Debug.WriteLine("END"); + //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds); + if (endflg) + { + + break; + } + } + else + { + Debug.WriteLine("END GET SERIAL: "+ret); + break; + } + } + else + { + Debug.WriteLine("END SEND SERIAL: "+ret); + break; + } + } + return 0; + } + + public void btnCountStart_Click(object sender, RoutedEventArgs e) + { + CountStart(); + AppData.WDTCount = 0; + } + + private void CountStart() + { + printerFlag = false; + + string currentMethod = MethodBase.GetCurrentMethod().Name; + try + { + + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + AppData.LogAction(currentMethod, null); + + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART); + //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort); + + //Thread.Sleep(20000); + if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { } + do + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE); + } + while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status + + //SR3 = 0x43 : Stacker full + + AutoSerialGet(serialPortDE70); + + if (sessions == null || sessions.Count == 0) + { + double tempSum = 0; + for (int i = 0; i < 10; i++) + { + lvCountItems[i].Quantity = TempQuantity[9 - i].ToString(); + tempSum += lvCountItems[i].getValue(); + } + + lvCountItems[10].Quantity = UpdateTotalQuantity().ToString(); + lvCountItems[10].Value = tempSum.ToString(); + + } + else + { + InitSessionCount(); + double sum = 0; + + for (int i = 0; i < 10; i++) + { + int a = 0; + for (int j = 0; j < sessions.Count; j++) + { + + a += sessions[j].QuantityDenomi[9 - i]; + + } + + a += TempQuantity[9 - i]; + + lvCountItems[i].Quantity = a.ToString(); + sum += lvCountItems[i].getValue(); + + } + //Update amount of money + lvCountItems[10].Quantity = UpdateTotalQuantity().ToString(); + lvCountItems[10].Value = sum.ToString(); + + } + SetStep(2); + } + catch (Exception ex) + { + AppData.LogException(currentMethod, ex.ToString()); + } + } + + private void btnCheck_Click(object sender, RoutedEventArgs e) + { + string currentMethod = MethodBase.GetCurrentMethod().Name; + + try + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + AppData.LogAction(currentMethod, null); + Array.Clear(TempQuantity, 0, TempQuantity.Length); + + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL); + + double sumStored; + + //TempNote[1] = 0; + + if (sessions != null) + { + sumStored = 0; + + for (int i = 0; i < 10; i++) + { + int a = 0; + for (int j = 0; j < sessions.Count; j++) + { + + a += sessions[j].QuantityDenomi[9 - i]; + //quantityStored += lvCountItems[i].getQuantity(); + } + lvCountItems[i].Quantity = a.ToString(); + sumStored += lvCountItems[i].getValue(); + } + lvCountItems[10].Quantity = UpdateTotalQuantity().ToString(); + lvCountItems[10].Value = sumStored.ToString(); + } + else + { + InitSessionCount(); + } + } + catch (Exception ex) + { + AppData.LogException(currentMethod, ex.ToString()); + } + AppData.WDTCount = 0; + } + private void btnStoreStart_Click(object sender, RoutedEventArgs e) + { + StoreStart(); + AppData.WDTCount = 0; + } + + private void StoreStart() + { + printerFlag = true; + + string currentMethod = MethodBase.GetCurrentMethod().Name; + + try + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + AppData.LogAction(currentMethod, null); + sessions.Add(new CountSession()); + + sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone(); + quantityStored = UpdateTotalQuantity(); + + Debug.WriteLine(quantityStored); + + Array.Clear(TempQuantity, 0, TempQuantity.Length); + + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART); + SetStep(3); + } + catch (Exception ex) + { + AppData.LogException(currentMethod, ex.ToString()); + } + } + + private void btnStart_Click(object sender, RoutedEventArgs e) + { + + string currentMethod = MethodBase.GetCurrentMethod().Name; + InitSession(); + AppData.IsInTransaction= true; + try + { + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + + AppData.LogAction(currentMethod, null); + + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE); + + var recvData = cCmdRsp.recv_dat; + + if (recvData.dat[14] == recvData.dat[16]) + { + cCmdRsp.SendLock(); + } + else + { + cCmdRsp.SendEventFix(recvData.dat[16]); + cCmdRsp.SendLock(); + } + SetStep(1); + } + catch (Exception ex) + { + AppData.LogException(currentMethod, ex.ToString()); + } + AppData.WDTCount = 0; + } + + private void btnEnd_Click(object sender, RoutedEventArgs e) + { + AppData.IsInTransaction = false; + AppData.WDTCount = 0; + EndSession(); + } + + private void EndSession() + { + string currentMethod = MethodBase.GetCurrentMethod().Name; + var totalQuantity = lvCountItems[10].Quantity; + var totalValue = lvCountItems[10].Value; + try + { + AppData.LogAction(currentMethod, null); + serialPortDE70.DiscardInBuffer(); + serialPortDE70.DiscardOutBuffer(); + + //SendData2Server + var data2Send = new CountingData2Send + { + Sessions = sessions, + MachineId = null, + UserId = AppData.CurrentCustomerAccount.CustomerId, + MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"), + RejectNotes = Notes[0], + GenuineNotes = quantityStored, + UnfitNotes = Notes[2], + CounterfeitNotes = Notes[3], + SuspendNotes = Notes[4] + + }; + var str = JsonConvert.SerializeObject(data2Send); + + APIModels.SendCountingData(data2Send); + //Reset all and ready to next session + + if (printerFlag == true) + { + PrintReceipt(); + printerFlag = false; + + } + InitSession(); + //Debug.WriteLine("Reject Note: " + Notes[0] ); + //Debug.WriteLine("Genuine note stored: " + quantityStored); + //Debug.WriteLine("Unfit note: " + Notes[2]); + //Debug.WriteLine("Counterfeit: " + Notes[3]); + //Debug.WriteLine("Suspend: " + Notes[4]); + + } + catch (Exception ex) + { + AppData.LogException(currentMethod, ex.ToString()); + } + + + String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n" + + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n" + + $"SỐ TIỀN: {totalValue} VND\r\n"; + + ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify); + } + + private void ShowError(string strError) + { + //gridMain.IsEnabled = false; + //btnCollect2.Visibility=Visibility.Collapsed; + //panelError.Visibility = Visibility.Visible; + //lblError.Text = strError; + //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen(); + ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError); + } + + private bool InitSession() + { + try + { + //Check status + cCmdRsp.SendDeSense(); + var data = cCmdRsp.recv_dat.dat; + int IsCassetteFull = 0; + int IsNotesInEscrow = 0; + IsCassetteFull = data[17] & 0x08; + IsNotesInEscrow = data[4] & 0x01; + + if (IsCassetteFull != 0) + { + ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen(); + return false; + } + else if (IsNotesInEscrow != 0) + { + ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC"); + } + else + { + InitSessionCount(); + sessions.Clear(); + Array.Clear(TempNote, 0, TempNote.Length); + Array.Clear(Notes, 0, Notes.Length); + quantityStored = 0; + maxQuantitySheet = 0; + cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK); + SetStep(0); + return true; + } + + } + catch(Exception ex) + { + AppData.LogException("InitSession", ex.ToString()); + } + return false; + } + + private void PrintReceipt() + { + var shopName = AppData.CurrentCustomerAccount.Name; + var shopCode = AppData.CurrentCustomerAccount.CustomerId; + var tradingCode = "TRA04052024CDM"; + var storeAccountNumber = 686868686688; + var currentTime = DateTime.Now; + var printDocument = new PrintDocument(); + printDocument.PrinterSettings.PrinterName = "CUSTOM K80"; + printDocument.PrintPage += (sender, e) => + { + e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10)); + e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60)); + e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90)); + e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120)); + e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150)); + e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180)); + e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210)); + e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240)); + e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270)); + e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300)); + // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string, + // or for more complex scenarios, directly manipulate the byte stream sent to the printer. + }; + printDocument.Print(); + + + } + + private void UserControl_Unloaded(object sender, RoutedEventArgs e) + { + EndTransaction(); + } + } +} + diff --git a/.svn/pristine/07/07ab6085662974f90c92b73a87ae3017a976c2f5.svn-base b/.svn/pristine/07/07ab6085662974f90c92b73a87ae3017a976c2f5.svn-base new file mode 100644 index 0000000..4465696 --- /dev/null +++ b/.svn/pristine/07/07ab6085662974f90c92b73a87ae3017a976c2f5.svn-base @@ -0,0 +1,49 @@ +using DE70_CMDv2; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SafeBagDE70 +{ + public static class AppData + { + public static List? customerAccounts = null; + public static CustomerAccount? CurrentCustomerAccount{get;set;} + public static CCmdRsp? cCmdRsp=null; + public static bool IsAuthenticated = false; + public static bool IsInTransaction = false; + public static int WDTCount = 0; + public static void Init() + { + customerAccounts = new List{ + new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" }, + new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" }, + new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" } + }; + CurrentCustomerAccount = customerAccounts[0]; + } + public static void LogAction(string strAction, string? strData) + { + if (strData != null) strData = "Data: " + strData; + File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") + + "Action: " + strAction + " " + strData); + } + + public static void LogException(string strAction, string? strData) + { + if (strData != null) strData = "Data: " + strData; + File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") + + "Action: " + strAction + " " + strData); + } + } + public class CustomerAccount + { + public string? Name { get; set; } + public string? CustomerId { get; set; } + public string? QRCode { get; set; } + public string? PINCode { get; set; } + } +} diff --git a/.svn/pristine/07/07baf310051dfa00e370cecf40ec2e397214b8fa.svn-base b/.svn/pristine/07/07baf310051dfa00e370cecf40ec2e397214b8fa.svn-base new file mode 100644 index 0000000..c29ae7c --- /dev/null +++ b/.svn/pristine/07/07baf310051dfa00e370cecf40ec2e397214b8fa.svn-base @@ -0,0 +1,211 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.svn/pristine/73/737ae15160f04efca3e2d838c77c26d2f29d0a27.svn-base b/.svn/pristine/73/737ae15160f04efca3e2d838c77c26d2f29d0a27.svn-base new file mode 100644 index 0000000..83eb037 --- /dev/null +++ b/.svn/pristine/73/737ae15160f04efca3e2d838c77c26d2f29d0a27.svn-base @@ -0,0 +1,51 @@ +using DE70_CMDv2; +using SafeBagDE70.Model; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace SafeBagDE70 +{ + public static class AppData + { + public static List? customerAccounts = null; + public static CustomerAccount? CurrentCustomerAccount{get;set;} + public static CCmdRsp? cCmdRsp=null; + public static bool IsAuthenticated = false; + public static bool IsInTransaction = false; + public static int WDTCount = 0; + public static void Init() + { + + customerAccounts = new List{ + new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" }, + new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" }, + new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" } + }; + CurrentCustomerAccount = customerAccounts[0]; + } + public static void LogAction(string strAction, string? strData) + { + if (strData != null) strData = "Data: " + strData; + File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") + + "Action: " + strAction + " " + strData); + } + + public static void LogException(string strAction, string? strData) + { + if (strData != null) strData = "Data: " + strData; + File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") + + "Action: " + strAction + " " + strData); + } + } + public class CustomerAccount + { + public string? Name { get; set; } + public string? CustomerId { get; set; } + public string? QRCode { get; set; } + public string? PINCode { get; set; } + } +} diff --git a/.svn/pristine/73/73f03dc42e6b54e168620b30c736c231a8a5dea9.svn-base b/.svn/pristine/73/73f03dc42e6b54e168620b30c736c231a8a5dea9.svn-base new file mode 100644 index 0000000..d6ae4a4 Binary files /dev/null and b/.svn/pristine/73/73f03dc42e6b54e168620b30c736c231a8a5dea9.svn-base differ diff --git a/.svn/pristine/75/75a45496f660b406e6738df28c2e6027a2788464.svn-base b/.svn/pristine/75/75a45496f660b406e6738df28c2e6027a2788464.svn-base new file mode 100644 index 0000000..e7c82e8 --- /dev/null +++ b/.svn/pristine/75/75a45496f660b406e6738df28c2e6027a2788464.svn-base @@ -0,0 +1,210 @@ +using CoreScanner; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Automation; +using System.Windows.Controls; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Shapes; +using System.Xml; + +namespace SafeBagDE70 +{ + /// + /// Interaction logic for WelcomeWindow.xaml + /// + public partial class WelcomeWindow : HandyControl.Controls.Window + { + public string? QRCodeContent = null; + public string? PinCode = null; + public bool IsAuthenticated = false; + public CCoreScannerClass? cCoreScannerClass=null; + public WelcomeWindow() + { + InitializeComponent(); + InitQRCodeScanner(); + } + private void LoginButton_Click(object sender, RoutedEventArgs e) + { + string pin = PinCodeBox.Password; + + if (ValidatePin(pin)) + { + PinCode=PinCodeBox.Password.ToString(); + if (AppData.customerAccounts != null) + { + CustomerAccount? cca = null; + if (PinCode != null) + { + var strPincode = PinCode.ToUpper(); + cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault(); + } + + if (cca != null) + { + DialogResult = true; + this.Close(); + } + else + { + lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại"; + } + } + } + else + { + MessageBox.Show("Invalid PIN. Please try again."); + } + } + + private void ForgotPin_Click(object sender, RoutedEventArgs e) + { + MessageBox.Show("Forgot PIN clicked."); + } + + private void Help_Click(object sender, RoutedEventArgs e) + { + MessageBox.Show("Help clicked."); + } + + private bool ValidatePin(string pin) + { + return true; + + } + private async void PinCodeButton_Click(object sender, RoutedEventArgs e) + { + var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe") + { + UseShellExecute = true + }; + Process.Start(onScreenKeyboardProcess); + try + { + //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink"; + //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe"); + //Process.Start(keyboardPath); + // AutomationElement.FromHandle(-1); + + // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe"; + // Process.Start(keyboardPath); + //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://")); + + //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe") + //{ + // UseShellExecute = true + //}; + //Process.Start(onScreenKeyboardProcess); + + QrCodePanel.Visibility = Visibility.Collapsed; + PinCodePanel.Visibility = Visibility.Visible; + + + cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent); + } + catch { + + } + + } + private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e) + { + PinCodePanel.Visibility = Visibility.Collapsed; + QrCodePanel.Visibility=Visibility.Visible; + cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent); + + + } + public void InitQRCodeScanner() + { + try + { + // Instantiate CoreScanner Class + cCoreScannerClass = new CCoreScannerClass(); + + // Call Open API + short[] scannerTypes = new short[1]; // Scanner Types you are interested in + scannerTypes[0] = 1; // 1 for all scanner types + short numberOfScannerTypes = 1; // Size of the scannerTypes array + int status; // Extended API return code + + cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status); + + // Subscribe for barcode events in cCoreScannerClass + + + // Let's subscribe for events + int opcode = 1001; // Method for Subscribe events + string outXML; // XML Output + string inXML = "" + + "" + + "1" + // Number of events you want to subscribe + "1" + // Comma separated event IDs + "" + + ""; + + cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status); + } + catch (Exception exp) + { + Console.WriteLine("Something wrong please check... " + exp.Message); + } + } + private void OnBarcodeEvent(short eventType, ref string pscanData) + { + string xmlString = pscanData; + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(xmlString); + + XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel"); + string rawDataHex = rawDataNode.InnerText.Trim(); + + QRCodeContent = HexStringToString(rawDataHex); + this.Dispatcher.Invoke(() => + { + + + if (AppData.customerAccounts != null) + { + CustomerAccount? cca = null; + if (QRCodeContent != null) + { + cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault(); + } + + if (cca != null) + { + cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent); + DialogResult = true; + this.Close(); + } + else + { + lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại"; + } + } + + }); + } + + static string HexStringToString(string hexString) + { + string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); + byte[] bytes = new byte[hexValues.Length]; + + for (int i = 0; i < hexValues.Length; i++) + { + bytes[i] = Convert.ToByte(hexValues[i], 16); + } + return Encoding.ASCII.GetString(bytes); + } + } +} diff --git a/.svn/pristine/78/78da6ced5cd4ceef6cfee414de2eac4da8a8f688.svn-base b/.svn/pristine/78/78da6ced5cd4ceef6cfee414de2eac4da8a8f688.svn-base new file mode 100644 index 0000000..0836a87 --- /dev/null +++ b/.svn/pristine/78/78da6ced5cd4ceef6cfee414de2eac4da8a8f688.svn-base @@ -0,0 +1,18 @@ + + + + + + + +