Biskilog POS desktop appilcation
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

411 lines
19 KiB

using BiskLog_Point_Of_Sale.Classes;
using BiskLog_Point_Of_Sale.Company_Setup;
using BiskLog_Point_Of_Sale.Multiple_Login;
using BiskLog_Point_Of_Sale.Properties;
using Microsoft.Reporting.WinForms;
using Point_Of_Sale_Managment;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BiskLog_Point_Of_Sale.Delivery
{
public partial class NewDelivery : Form
{
SqlConnection cn;
SqlCommand cm;
DatabaseConn conn = new DatabaseConn();
SqlTransaction transaction;
int i = 1;
decimal itemTotal = decimal.Parse("0.00");
string customerID = "DELCUS" + String.Format("{0:d12}", (DateTime.Now.Ticks / 10) % 1000000000);
public static List<OrderInvoice> deliveryInvoice = new List<OrderInvoice>();
public static List<products> productsList = new List<products>();
string printLocation = "";
List<string> cart = new List<string>();
string currency;
public NewDelivery(CustomerClass recipient = null)
{
InitializeComponent();
cn = new SqlConnection(conn.MyConnection());
currency = Settings.Default.currrencyCode + " ";
if (recipient != null)
{
customerID = recipient.id;
lblFullname.Text = recipient.firstname + " " + recipient.surname;
lblAddress.Text = recipient.address;
lblEmail.Text = recipient.email;
lblTelephone.Text = recipient.telephone;
}
}
private void Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Exit_MouseEnter(object sender, EventArgs e)
{
exit.BackColor = Color.Crimson;
}
private void Exit_MouseLeave(object sender, EventArgs e)
{
exit.BackColor = Color.FromArgb(20, 158, 137);
}
private void NewDelivery_Load(object sender, EventArgs e)
{
DateTime Today = lblFrom.Value;
lblTo.Value = Today.AddDays(5);
}
private void PictureBox1_Click(object sender, EventArgs e)
{
AddProductDelivery addProduct = new AddProductDelivery(this);
addProduct.BringToFront();
addProduct.ShowDialog();
invoiceDetails.ClearSelection();
}
public void loadProductManual(string productName, int quantity, decimal price, string id,string unitname,string unitcode,string distinctive)
{
itemTotal += price;
//invoiceDetails.Rows.Add(i, productName, quantity, Settings.Default.currrencyCode + " " + price, id);
//i++;
if (!cart.Contains(id) && !id.Equals(distinctive) && !cart.Contains(distinctive))
{
invoiceDetails.Rows.Add(i, productName, quantity, unitname, currency + price, id, unitcode, distinctive);
cart.Add(distinctive);
i++;
}
else if (!cart.Contains(id) && id.Equals(distinctive) && !cart.Contains(distinctive))
{
invoiceDetails.Rows.Add(i, productName,quantity, unitname, currency + price, id, unitcode, distinctive);
cart.Add(id);
i++;
}
else if (!id.Equals(distinctive) && !cart.Contains(distinctive))
{
invoiceDetails.Rows.Add(i, productName, quantity, unitname, currency + price, id, unitcode, distinctive);
cart.Add(distinctive);
i++;
}
else
{
foreach (DataGridViewRow row in invoiceDetails.Rows)
{
if (row.Cells[5].Value.ToString().Equals(id) && row.Cells[7].Value.ToString().Equals(distinctive))
{
int total_quantity = int.Parse(row.Cells[2].Value.ToString());
decimal total_bill = decimal.Parse(row.Cells[4].Value.ToString().Substring(currency.Length));
total_quantity += quantity;
row.Cells[2].Value = total_quantity;
row.Cells[4].Value = currency + " " + (total_bill*total_quantity);
}
}
}
lblItemT.Text = Settings.Default.currrencyCode + " " + itemTotal.ToString();
lblTotal.Text = Settings.Default.currrencyCode + " " + (decimal.Parse(lblCharges.Text) + itemTotal).ToString();
}
private void InvoiceDetails_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
string colName = invoiceDetails.Columns[e.ColumnIndex].Name;
if (colName == "Delete")
{
decimal price = decimal.Parse(invoiceDetails.Rows[e.RowIndex].Cells[3].Value.ToString().Substring(Settings.Default.currrencyCode.Length));
itemTotal -= price;
lblItemT.Text = Settings.Default.currrencyCode + " " + itemTotal.ToString();
lblTotal.Text = Settings.Default.currrencyCode + " " + (decimal.Parse(lblCharges.Text) + itemTotal).ToString();
invoiceDetails.Rows.Remove(invoiceDetails.Rows[e.RowIndex]);
int b = 1;
foreach (DataGridViewRow row in invoiceDetails.Rows)
{
row.Cells[0].Value = b;
b++;
}
invoiceDetails.ClearSelection();
}
}
}
private void LblCharges_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;
}
else if (e.KeyChar == 46)
{
// accepts . character
}
}
public int ScheduleDelivery()
{
try
{
cn.Open();
transaction = cn.BeginTransaction();
string deliveryID = "D" + MainLogin.login_user.Substring(0, 2).ToUpper() + String.Format("{0:d12}", (DateTime.Now.Ticks / 10) % 1000000000);
foreach (DataGridViewRow row in invoiceDetails.Rows)
{
cm = new SqlCommand("Insert into tblDeliveryDetails (deliveryID,pcode,quantity,cost,countID,unit) values " +
"(@deliveryID,@pcode,@quantity,@cost,@countID,@unit)", cn, transaction);
cm.Parameters.AddWithValue("@deliveryID", deliveryID);
cm.Parameters.AddWithValue("@pcode", row.Cells[5].Value.ToString());
cm.Parameters.AddWithValue("@quantity", row.Cells[2].Value.ToString());
cm.Parameters.AddWithValue("@unit", row.Cells[6].Value.ToString());
cm.Parameters.AddWithValue("@cost", (row.Cells[4].Value.ToString()).Substring(Settings.Default.currrencyCode.Length));
cm.Parameters.AddWithValue("@countID", row.Cells[7].Value.ToString() + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
cm.ExecuteNonQuery();
products p = new products(row.Cells[1].Value.ToString(), row.Cells[2].Value.ToString(), row.Cells[3].Value.ToString(), row.Cells[4].Value.ToString());
productsList.Add(p);
}
//tblDeliveryHead insert
cm = new SqlCommand("Insert into tblDeliveryHead (deliveryID,generatedBy,dateInitiated,destination,customerID,status,branchID,totalCost) " +
"values (@deliveryID,@generatedBy,@dateInitiated,@destination,@customerID,@status,@branchID,@totalCost)", cn, transaction);
cm.Parameters.AddWithValue("@deliveryID", deliveryID);
cm.Parameters.AddWithValue("@generatedBy", MainLogin.login_user);
cm.Parameters.AddWithValue("@dateInitiated", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
cm.Parameters.AddWithValue("@destination", lblAddress.Text);
cm.Parameters.AddWithValue("@customerID", customerID);
cm.Parameters.AddWithValue("@status", "PROCESSING");
cm.Parameters.AddWithValue("@branchID", Settings.Default.BranchID);
cm.Parameters.AddWithValue("@totalCost", (lblTotal.Text).Substring(Settings.Default.currrencyCode.Length));
cm.ExecuteNonQuery();
//tblDeliveryRecipient insert
cm = new SqlCommand("Insert into tblDeliveryRecipients (deliveryID,fullname,address,telephone,customerID,email,fromDate,toDate) " +
"values (@deliveryID,@fullname,@address,@telephone,@customerID,@email,@fromDate,@toDate)", cn, transaction);
cm.Parameters.AddWithValue("@deliveryID", deliveryID);
cm.Parameters.AddWithValue("@fullname", lblFullname.Text);
cm.Parameters.AddWithValue("@telephone", lblTelephone.Text);
cm.Parameters.AddWithValue("@address", lblAddress.Text);
cm.Parameters.AddWithValue("@customerID", customerID);
cm.Parameters.AddWithValue("@email", lblEmail.Text);
cm.Parameters.AddWithValue("@fromDate", lblFrom.Value.ToString("yyyy-MM-dd"));
cm.Parameters.AddWithValue("@toDate", lblTo.Value.ToString("yyyy-MM-dd"));
cm.ExecuteNonQuery();
transaction.Commit();
cn.Close();
deliveryInvoice.Clear();
lblAddress.Invoke(new Action(() =>
{
string moneyCode = Settings.Default.currrencyCode + " ";
OrderInvoice order = new OrderInvoice(
orderDate: DateTime.Now.ToString("yyyy-MM-dd"), beginDate: lblFrom.Value.ToString("yyyy-MM-dd"), endDate: lblTo.Value.ToString("yyyy-MM-dd"),
ProductsCost: lblItemT.Text, additional: moneyCode + lblCharges.Text, All: lblTotal.Text, address: lblAddress.Text, email: lblEmail.Text,
telephone: lblTelephone.Text, branchtelephone: Settings.Default.BranchTelephone, branchLocation: Settings.Default.BranchCity, branchName: Settings.Default.BranchName,
orderid: deliveryID, companyName: Settings.Default.CompanyName, customer: lblFullname.Text
);
deliveryInvoice.Add(order);
}));
try
{
if (!Directory.Exists(Environment.CurrentDirectory + @"\Order Invoice"))
{
Directory.CreateDirectory(Environment.CurrentDirectory + @"\Order Invoice");
}
printLocation = Environment.CurrentDirectory + @"\Order Invoice\" + deliveryID + ".pdf";
LocalReport report = new LocalReport();
string path = Path.GetDirectoryName(Application.ExecutablePath);
string fullpath = Path.GetDirectoryName(Application.ExecutablePath).Remove(path.Length - 10) +
@"\Delivery\OrderInvoice.rdlc";
report.ReportPath = fullpath;
report.DataSources.Add(new ReportDataSource("Details", deliveryInvoice));
report.DataSources.Add(new ReportDataSource("products", productsList));
OrderInvoiceConfig.PrintToPrinter(report, printLocation, "Microsoft Print to PDF");
}
catch (Exception ex)
{
ErrorLogging.WriteToFile(ex.ToString());
}
return 1;
}
catch (Exception ex)
{
ErrorLogging.WriteToFile(ex.ToString());
transaction.Rollback();
cn.Close();
return 0;
}
}
public int sendInvoice()
{
try
{
MailMessage mail = new MailMessage();
string client = Settings.Default.smtpServer;
string clientPort = Settings.Default.smtpPort;
string username = Settings.Default.emailAddress;
string password = passwordEncryption.Decrypt(Settings.Default.password);
SmtpClient smtpClient = new SmtpClient(client);
mail.From = new MailAddress(username);
lblEmail.Invoke(new Action(() => mail.To.Add(lblEmail.Text)));
mail.Subject = "Order invoice";
lblFullname.Invoke(new Action(() => mail.Body = "Hello " + lblFullname.Text + " your order invoice has been attached to this mail"));
string file = printLocation;
System.Net.Mail.Attachment attachment;
attachment = new Attachment(file);
mail.Attachments.Add(attachment);
smtpClient.Port = int.Parse(clientPort);
smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
smtpClient.EnableSsl = true;
smtpClient.Send(mail);
return 1;
}
catch
{
return 0;
}
}
bool IsValidEmail(string email)
{
try
{
var addr = new MailAddress(email);
return addr.Address == email;
}
catch
{
return false;
}
}
private async void Button1_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(lblFullname.Text) || !String.IsNullOrEmpty(lblAddress.Text) || !String.IsNullOrEmpty(lblTelephone.Text))
{
if (!String.IsNullOrEmpty(lblEmail.Text))
{
if (IsValidEmail(lblEmail.Text))
{
Task<int> task = new Task<int>(ScheduleDelivery);
holding.Visible = true;
task.Start();
int result = await task;
if (result == 1)
{
string title = "Order Successful";
string message = "Order has been processed successfully pending assignment to delivery truck";
NoAction noAction = new NoAction(title, message);
noAction.BringToFront();
noAction.ShowDialog();
Task<int> taskO = new Task<int>(sendInvoice);
taskO.Start();
int youin = await taskO;
if (youin == 1)
{
string titled = "Invoice Mailed";
string messaged = "Order invoice has been successfully mailed to the customer";
NoAction noActiond = new NoAction(titled, messaged);
noActiond.BringToFront();
noActiond.ShowDialog();
}
else
{
string titles = "Invoice not mailed";
string messages = "An error occurred while trying to mail invoice to customer";
NoAction noActions = new NoAction(titles, messages);
noActions.BringToFront();
noActions.ShowDialog();
}
}
else
{
string title = "Order not successful";
string message = "An error occurred while processing order, please try again later";
NoAction noAction = new NoAction(title, message);
noAction.BringToFront();
noAction.ShowDialog();
}
holding.Visible = false;
}
else
{
string title = "Invalid Email";
string message = "An error occurred while processing order due to an invalid email address entered," +
" please correct the email and try again";
NoAction noAction = new NoAction(title, message);
noAction.BringToFront();
noAction.ShowDialog();
}
}
else
{
Task<int> task = new Task<int>(ScheduleDelivery);
holding.Visible = true;
task.Start();
int result = await task;
if (result == 1)
{
string title = "Order Successful";
string message = "Order has been processed successfully pending assignment to delivery truck";
NoAction noAction = new NoAction(title, message);
noAction.BringToFront();
noAction.ShowDialog();
}
else
{
string title = "Order not successful";
string message = "An error occurred while processing order, please try again later";
NoAction noAction = new NoAction(title, message);
noAction.BringToFront();
noAction.ShowDialog();
}
holding.Visible = false;
}
}
else
{
string title = "Order not successful";
string message = "Please make sure the receipent's name, address and telephone number fields are not empty and try again";
NoAction noAction = new NoAction(title, message);
noAction.BringToFront();
noAction.ShowDialog();
}
}
private void LblTelephone_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 LblCharges_TextChanged(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(lblCharges.Text))
{
lblTotal.Text = Settings.Default.currrencyCode + " " + (decimal.Parse(lblCharges.Text) + itemTotal).ToString();
}
else
{
lblTotal.Text = Settings.Default.currrencyCode + " " + (decimal.Parse("0.00") + itemTotal).ToString();
}
}
}
}