using BarcodeLib; using BiskLog_Point_Of_Sale.Classes; using BiskLog_Point_Of_Sale.Company_Setup; using BiskLog_Point_Of_Sale.Dialogs; using BiskLog_Point_Of_Sale.Multiple_Login; using BiskLog_Point_Of_Sale.Properties; using Microsoft.Reporting.WinForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Point_Of_Sale_Managment { public partial class ReceiptModule : Form { SqlConnection cn; SqlCommand cm; SqlDataReader dr; DatabaseConn conn = new DatabaseConn(); bool soldToCustomer = false; public static List receiptClasses = new List(); public static List receiptClasses2 = new List(); string printLocation = ""; string printerReceiptDefault = Settings.Default.ReceiptPrinter; private decimal m_balance, m_tendered, m_vat = 0; private string receiptID; public ReceiptModule(string receiptID = null) { InitializeComponent(); cn = new SqlConnection(conn.MyConnection()); holding.Left = (ClientSize.Width - holding.Width) / 2; if (!String.IsNullOrEmpty(receiptID)) this.receiptID = receiptID; } private async void SaleCancellation_Load(object sender, EventArgs e) { if (!String.IsNullOrEmpty(receiptID)) { textBox1.Text = receiptID; holding.Visible = true; await getReceipt(textBox1.Text); holding.Visible = false; } } private void SaleCancellation_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) { this.Close(); } } private async void TextBox1_TextChanged(object sender, EventArgs e) { holding.Visible = true; await getReceipt(textBox1.Text); holding.Visible = false; } public void cancelSales(string transactionKey) { SqlTransaction transaction; cn.Open(); transaction = cn.BeginTransaction(); try { cm = new SqlCommand("Update tblCart set status = @status where branchID = @branch and transno = @transno", cn); cm.Parameters.AddWithValue("@status", "CANCELLED"); cm.Parameters.AddWithValue("@transno", transactionKey); cm.Parameters.AddWithValue("@branch", Settings.Default.BranchID); cm.Transaction = transaction; cm.ExecuteNonQuery(); cm = new SqlCommand("Insert into tblCancelledTransactions (transno,dateCancelled,cancelledBy,branchID,countID) " + "values (@transno,@dateCancelled,@cancelledBy,@branchID,@countID)", cn); cm.Parameters.AddWithValue("@dateCancelled", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); cm.Parameters.AddWithValue("@transno", transactionKey); cm.Parameters.AddWithValue("@branchID", Settings.Default.BranchID); cm.Parameters.AddWithValue("@cancelledBy", MainLogin.login_user); cm.Parameters.AddWithValue("@countID", transactionKey + Settings.Default.BranchID + DateTime.Now.ToString("yyyyMMddHHmmssfff")); cm.Transaction = transaction; cm.ExecuteNonQuery(); if (soldToCustomer) { cm = new SqlCommand("Declare @debit decimal(19,2) = Case when (Select paid from CreditPurchases where receiptID = @transaction and branchID = @branchID) is not null then " + "(Select paid from CreditPurchases where receiptID = @transaction and branchID = @branchID) else " + "(Select SUM(total) from tblCart where transno = @transaction and branchID = @branchID) end " + "Declare @customerID varchar(50) = (Select customerID from tblCustomerPurchases where transactionID = @transaction and branchID = @branchID) " + "Declare @total decimal(19,2) = Case when (Select SUM(debit - credit) from CustomerAccounts where branchID = @branchID " + "and customerID = @customerID) is null then 0 else (Select SUM(debit - credit) from CustomerAccounts where branchID = @branchID and customerID = @customerID) end " + "set @total = (@total + @debit) - @credit " + "Insert into CustomerAccounts(customerID, transactionID, date, debit, credit, balance, comments, branchID, countID) " + "Values(@customerID, @transactionID, @date, @debit, @credit, @total, @comments, @branchID, @countID) " + "Delete from tblCustomerPurchases where transactionID = @transaction and branchID = @branchID and customerID = @customerID", cn); cm.Parameters.AddWithValue("@transaction", transactionKey); cm.Parameters.AddWithValue("@transactionID", DateTime.Now.ToString("yyyyMMddHHmmssfff")); cm.Parameters.AddWithValue("@branchID", Settings.Default.BranchID); cm.Parameters.AddWithValue("@credit", 0); cm.Parameters.AddWithValue("@comments", "ReceiptID with transaction ID : " + transactionKey + " was cancelled"); cm.Parameters.AddWithValue("@date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); cm.Parameters.AddWithValue("@countID", transactionKey + Settings.Default.BranchID + DateTime.Now.ToString("yyyyMMddHHmmssfff")); cm.Transaction = transaction; cm.ExecuteNonQuery(); } foreach (DataGridViewRow row in dataGridView1.Rows) { cm = new SqlCommand("Declare @baseunit varchar(150) = (Select baseUnit from tblProduct where pcode = @pcode) " + "Declare @dquantity int = Case when @baseUnit = @unit then 1 * @quantity else " + "(Select[quantity/unit] * @quantity as quantity from ProductAltUnit where pcode = @pcode and unitCode = @unit and branchID = @branchID) end " + "Declare @newQuantity int = (Select MAX(quantity) + MIN(@dquantity) from tblInventory where pcode = @pcode and branchID = @branchID) " + "Update tblInventory set quantity = @newQuantity where pcode = @pcode and branchID = @branchID " + "Insert into tblInventoryEntries(pcode, quantity, date, countID, branchID) values (@pcode, @newQuantity, @date, @countID, @branchID)", cn); cm.Parameters.AddWithValue("@quantity", row.Cells[3].Value.ToString()); cm.Parameters.AddWithValue("@unit", row.Cells[7].Value.ToString()); cm.Parameters.AddWithValue("@pcode", row.Cells[6].Value.ToString()); cm.Parameters.AddWithValue("@date", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); cm.Parameters.AddWithValue("@branchID", Settings.Default.BranchID); cm.Parameters.AddWithValue("@countID", transactionKey + Settings.Default.BranchID + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); cm.Transaction = transaction; cm.ExecuteNonQuery(); } transaction.Commit(); cn.Close(); string title = "Cancelled"; string message = "Receipt with transaction number " + transactionKey + " has been cancelled successfully"; NoAction noAction = new NoAction(title, message); noAction.BringToFront(); noAction.ShowDialog(); } catch (Exception ex) { transaction.Rollback(); cn.Close(); ErrorLogging.WriteToFile(ex.ToString()); } } public async Task getReceipt(string key) { m_balance = 0; m_tendered = 0; m_vat = 0; int i = 1; try { dataGridView1.Invoke(new Action(() => { decimal total = (decimal)0.00; decimal discount = (decimal)0.00; decimal vat = (decimal)0.00; dataGridView1.Rows.Clear(); cn.Open(); cm = new SqlCommand("Exec usp_fetch_receipts_by_transaction_number @BranchID = @branch,@TransNumber = @transno", cn); cm.Parameters.AddWithValue("@transno", key); cm.Parameters.AddWithValue("@branch", Settings.Default.BranchID); dr = cm.ExecuteReader(); bool found = dr.HasRows; while (dr.Read()) { dataGridView1.Rows.Add(i, dr["Product"].ToString().ToUpper(), dr["Price"].ToString().ToUpper(), dr["quantity"].ToString(), dr["unitName"].ToString(), dr["total"].ToString(), dr["ProductID"].ToString(), dr["unit"].ToString()); lblBalance.Text = $" {Settings.Default.currrencyCode} {dr["balance"].ToString()}"; lblTendered.Text = $" {Settings.Default.currrencyCode} {dr["tendered"].ToString()}"; lblDiscount.Text = $" {Settings.Default.currrencyCode} {dr["discount"].ToString()}"; lblDate.Text = dr["date"].ToString(); lblCashier.Text = dr["cashier"].ToString(); lblCustomer.Text = !String.IsNullOrEmpty(dr["name_key1"].ToString()) ? dr["name_key1"].ToString() : "Walk-In Purchase"; discount = decimal.Parse(dr["discount"].ToString()); vat = decimal.Parse(!String.IsNullOrEmpty(dr["vat"].ToString()) ? dr["vat"].ToString() : "0"); lblVAT.Text = $" {Settings.Default.currrencyCode} {vat}"; total += decimal.Parse(dr["total"].ToString()); m_balance = decimal.Parse(dr["balance"].ToString()); m_tendered = decimal.Parse(dr["tendered"].ToString()); m_vat = vat; i++; } dr.Close(); cn.Close(); lblSubTotal.Text = $" {Settings.Default.currrencyCode} {total}"; lblBillTotal.Text = $" {Settings.Default.currrencyCode} {total - discount + vat}"; if (found) { detailsBox.Visible = true; btnPrint.Enabled = true; btnCancel.Enabled = true; } else { detailsBox.Visible = false; btnPrint.Enabled = false; btnCancel.Enabled = false; } })); } catch (Exception ex) { ErrorLogging.WriteToFile(ex.ToString()); cn.Close(); } } private void TextBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 8) { //accepts backspace } else if ((e.KeyChar < 48) || (e.KeyChar > 57)) //ascii code 48-57 between 0-9 { e.Handled = true; } } private void BtnCancel_Click(object sender, EventArgs e) { string title = "Confirm Cancellation"; string message = "Are you sure you would like to cancel this transaction ?"; Confirmation confirmation = new Confirmation(title, message); confirmation.BringToFront(); confirmation.ShowDialog(); if (confirmation.DialogResult == DialogResult.Yes) { if (Settings.Default.cancellationConfirmation) { Prompt promptCancel = new Prompt(); promptCancel.BringToFront(); promptCancel.ShowDialog(); if ((promptCancel.DialogResult == DialogResult.OK) && (promptCancel.confirmed)) { cancelSales(textBox1.Text); ClearModule(); } } else { cancelSales(textBox1.Text); ClearModule(); } } } private void ClearModule() { dataGridView1.Rows.Clear(); textBox1.Text = ""; lblBalance.Text = ""; lblTendered.Text = ""; lblDiscount.Text = ""; lblDate.Text = ""; lblCashier.Text = ""; lblCustomer.Text = ""; lblVAT.Text = ""; lblSubTotal.Text = ""; lblBillTotal.Text = ""; detailsBox.Visible = false; btnPrint.Enabled = false; btnCancel.Enabled = false; } public Image getBarcodeImage(string Bcode) { Barcode barcodeAPI = new Barcode(); Color foreColor = Color.Black; Color backColor = Color.Transparent; return barcodeAPI.Encode(TYPE.UPCA, Bcode, foreColor, backColor, 290, 120); } private async void btnPrint_Click(object sender, EventArgs e) { holding.Visible = true; Task task = new Task(() => { PreparePrint(); return 1; }); task.Start(); await task; holding.Visible = false; } private async Task PreparePrint() { try { textBox1.Invoke(new Action(() => { receiptClasses.Clear(); receiptClasses2.Clear(); MemoryStream ms = new MemoryStream(); getBarcodeImage(textBox1.Text).Save(ms, ImageFormat.Png); byte[] imageBytes = ms.ToArray(); string barcodeStringImage = Convert.ToBase64String(imageBytes); bottom bottomReceipt = new bottom(lblVAT.Text, textBox1.Text, lblCashier.Text, m_balance, m_tendered, lblDiscount.Text, lblDate.Text, lblSubTotal.Text, lblBillTotal.Text, Form1.bCompanyName, Form1.branchName, Form1.branchLocation, Form1.branchTel, Form1.tin, Form1.vatno, barcodeStringImage); receiptClasses2.Add(bottomReceipt); foreach (DataGridViewRow row in dataGridView1.Rows) { ReceiptObject receipt = new ReceiptObject(row.Cells[1].Value.ToString(), decimal.Parse(row.Cells[2].Value.ToString()), int.Parse(row.Cells[3].Value.ToString()), decimal.Parse(row.Cells[5].Value.ToString())); receiptClasses.Add(receipt); } if (printerReceiptDefault == "Microsoft XPS Document Writer" || printerReceiptDefault == "Microsoft Print to PDF") { FolderBrowserDialog folder = new FolderBrowserDialog(); DialogResult result = folder.ShowDialog(); if (result == DialogResult.OK && !String.IsNullOrEmpty(folder.SelectedPath)) { printLocation = folder.SelectedPath; LocalReport report = new LocalReport(); string path = Path.GetDirectoryName(Application.ExecutablePath); string fullpath = Path.GetDirectoryName(Application.ExecutablePath).Remove(path.Length - 10) + @"\Receipt.rdlc"; report.ReportPath = fullpath; report.DataSources.Add(new ReportDataSource("ReceiptReport", receiptClasses)); report.DataSources.Add(new ReportDataSource("ReceiptRest", receiptClasses2)); ReceiptConfig.PrintToPrinter(report, printLocation, printerReceiptDefault); } } else { printLocation = ""; LocalReport report = new LocalReport(); string path = Path.GetDirectoryName(Application.ExecutablePath); string fullpath = Path.GetDirectoryName(Application.ExecutablePath).Remove(path.Length - 10) + @"\Receipt.rdlc"; report.ReportPath = fullpath; report.DataSources.Add(new ReportDataSource("ReceiptReport", receiptClasses)); report.DataSources.Add(new ReportDataSource("ReceiptRest", receiptClasses2)); ReceiptConfig.PrintToPrinter(report, printLocation, printerReceiptDefault); } })); } catch (Exception ex) { } } } }