Skip to main content

Intigrate POS Printer in asp.net core 6. Web Project

There are two methods to call POS printer to print

  1. PrintGuestCheck
  2. PayBill_Print


using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Tawoon.IT_SoftwareTemplate.BusinnessModels.BaseVM.Dashboard;
using Tawoon.IT_SoftwareTemplate.BusinnessModels.Enum;
using Tawoon.IT_SoftwareTemplate.Entities;
using Tawoon.IT_SoftwareTemplate.Entities.Models;
using System.IO;
using System.Drawing.Printing;
using System.Drawing;
using System.Net.Sockets;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Tawoon.IT_SoftwareTemplate.BusinnessModels.BaseVM;
using Microsoft.Extensions.Options;
using Tawoon.IT_SoftwareTemplate.Helper;
using Microsoft.AspNetCore.Http;
using System.Drawing.Imaging;

namespace Tawoon.IT_SoftwareTemplate.Controllers
{
    public class DashboardController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager _userManager;
        private readonly IHostingEnvironment _env;
        private readonly IOptions _config;
        private readonly UtilityFunctions _utilityFunctions;
        int tableIdGlobal = 0;
        double receivedAmount = 0;
        int paymentMethodId = 0;
        double returnAmount = 0;
        double dueAmount = 0;
        int lineHeight = 8;
        int CountLineNumber = 1;
        const char ESC ='\x1b';
        const char FS = '\x1c';
        const char GS = '\x1d';
        public DashboardController(UtilityFunctions utilityFunctions, IOptions config,IHostingEnvironment env,ApplicationDbContext context, UserManager userManager )
        {
            _context = context;
            _userManager = userManager;
            this._env = env;
            _config =  config;
            _utilityFunctions = utilityFunctions;
        }


        private void TcpPrint(string host, byte[] data)
        {
            Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            s.Connect(host, 9100);
            s.Send(data);
            s.Disconnect(false);
        }

        private byte[] GetPrintData( List MenuList, string TableName, int OrderId, string cookingDeptname)
        {
            StringBuilder sb = new StringBuilder();

           

            // Initialize printer
            sb.Append(ESC + "@");

            // Align center
            sb.Append(ESC + "a" + (char)1);

            // Use bold
            sb.Append(ESC + "E" + (char)1);

            // Add header text
            sb.Append(_config.Value.CompanyName+"\n");
            sb.AppendFormat("{0}\n\n", cookingDeptname);
            sb.AppendFormat("Table No-{0}\n", TableName);

            sb.AppendFormat("Order No-{0}\n\n", OrderId);

            sb.AppendFormat("Date'{0}'     ", DateTime.Now.ToShortDateString());
            sb.AppendFormat("Time-'{0}'\n\n", DateTime.Now.ToShortTimeString());
            // Revert to align left and normal weight
           

            sb.Append("Order List\n");
            sb.Append("-----------------\n");


            sb.Append(ESC + "a" + (char)0);
            sb.Append(ESC + "E" + (char)0);

            int count = 1; 

            foreach (var item in MenuList)
            {
                sb.AppendFormat(count+". {0}:{1}\n",item.MenuName, item.Qty );
            }
            // Format some text
            sb.Append("\n\n\n");
           
            

            // Feed and cut paper
            sb.Append(GS + "V\x41\0");

            return Encoding.Default.GetBytes(sb.ToString());
        }
        public IActionResult AdminDashboard()
        {
            return View();
        }
        public IActionResult SalesDashboard()
        {
            var sd = _context.DailyCashBooks.Select(x => new DailyCashBook
            {
                Id = x.Id,
                IsOpenningDone = x.IsOpenningDone,
                CreatedDate = x.CreatedDate

            }).ToList();

            var ss = sd.SingleOrDefault(x => x.CreatedDate.ToString("MM/dd/yyyy") == DateTime.Today.Date.ToString("MM/dd/yyyy")).IsOpenningDone;


            if (ss)
            {
                return View();
            }

            else
            {
                return RedirectToAction("OpenningAmount");
            }
        }

        public IActionResult OpenningAmount()
        {
            return View();
        }

        public IActionResult Cashout()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task OpenningAmount(DailyCashBook dailyCashBook)
        {
            if (ModelState.IsValid)
            {
                try
                {

                    var sd = _context.DailyCashBooks.Select(x => new DailyCashBook
                    {
                        Id = x.Id,
                        IsOpenningDone = x.IsOpenningDone,
                        CreatedDate = x.CreatedDate

                    }).ToList();

                    var model = sd.SingleOrDefault(x => x.CreatedDate.ToString("MM/dd/yyyy") == DateTime.Today.Date.ToString("MM/dd/yyyy"));
                        
                      model.OpnenningAmount = dailyCashBook.OpnenningAmount;
                      model.UserId  = User.FindFirstValue(ClaimTypes.NameIdentifier);
                      model.OpenningTime = DateTime.Now;
                      model.IsOpenningDone = true;



                    _context.Update(model);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DailyCashBookExists(dailyCashBook.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(SalesDashboard));
            }
            return View(dailyCashBook);
        }

        private bool DailyCashBookExists(int id)
        {
            return _context.DailyCashBooks.Any(e => e.Id == id);
        }
        public IActionResult ClossingAmount()
        {
            return View();
           
        }

        public async Task OrderDetails(int id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var diningtable = await _context.Diningtables.FindAsync(id);
            
            ViewData["TableId"] = id;

            ViewData["TableName"] = diningtable.Name;

            ViewData["tableStatus"] = diningtable.Status;


            if (diningtable.Status == "Busy")
            {

                var Order = _context.Orders.Where(x => x.DiningtableId == id).FirstOrDefault();

                var Employee = _context.Employees.Find(Order.EmployeeId);

                ViewData["EmployeeId"] = Employee.Id;

                ViewData["EmployeeName"] = Employee.FistName + " " + Employee.LastName;

            }
            else
            {
                ViewData["EmployeeId"] = "";

                ViewData["EmployeeName"] = "";
            }



            return View();
        }

        [HttpPost]
        public object GetAllItemByTableNo([FromBody] int data)
        {

            var orders = _context.Orders.Where(x => x.DiningtableId == data && x.IsPrinted == false).ToList();
            List orderDetailsMulti = new List();

            foreach (var item in orders)
            {
                var OrderDetailsDb = _context.Orderdetails.Where(x => x.OrderId == item.Id).ToList();

                var orderDetailsToPrint = OrderDetailsDb.Join(_context.Menus, od => od.MenuId, m => m.Id, (od, m) => new OrderDetailsForPrint
                {

                    Id = m.Id,
                    MenuName = m.Name,
                    Qty = od.Quantity,
                    CookingDeptId = m.CookingDepartmentId,
                    Price = m.Price.ToString()

                }).ToList();

                orderDetailsMulti.AddRange(orderDetailsToPrint);
            }

            List orderDetails = new List();
            int qty = 0;
            foreach (var item in orderDetailsMulti)
            {
                var MenuFound = orderDetails.Find(x => x.MenuName == item.MenuName);
                if (MenuFound != null)
                {

                    orderDetails.Find(x => x.MenuName == item.MenuName).Qty = (Convert.ToInt32(orderDetails.Find(x => x.MenuName == item.MenuName).Qty) + Convert.ToInt32(item.Qty)).ToString();
                }
                else
                {
                    orderDetails.Add(item);
                }
            }
            return orderDetails;
        }

        [HttpPost]
        public bool PrintGuestCheck([FromBody] int data)
        {
            var orders = _context.Orders.Where(x => x.DiningtableId == data && x.IsPrinted == false).ToList();

            tableIdGlobal = data;

            PrintDocument prtdoc = new PrintDocument();
            string strDefaultPrinter = prtdoc.PrinterSettings.PrinterName;
            prtdoc.OriginAtMargins = true;
            prtdoc.DefaultPageSettings.Landscape = true;
            PrintDocument pd = new PrintDocument();

            PaperSize ps = new PaperSize("", 285, 520);  //paper size 
            pd.PrintPage += new PrintPageEventHandler(printPOSPage);
            pd.PrintController = new StandardPrintController();
            pd.DefaultPageSettings.Margins.Left = 0;
            pd.DefaultPageSettings.Margins.Right = 0;
            pd.DefaultPageSettings.Margins.Top = 0;
            pd.DefaultPageSettings.Margins.Bottom = 10;
            // pd.DefaultPageSettings.PaperSize = ps;

            pd.Print();

            return true;

        }

        private void printPOSPage(object sender, PrintPageEventArgs e)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding.GetEncoding("windows-1252");

            var orders = _context.Orders.Where(x => x.DiningtableId == tableIdGlobal && x.IsPrinted == false).ToList();
            double discount = orders.FirstOrDefault().DiscountAmount;
            List orderDetailsMulti = new List();

            foreach (var item in orders)
            {
                var OrderDetailsDb = _context.Orderdetails.Where(x => x.OrderId == item.Id).ToList();

                var orderDetailsToPrint = OrderDetailsDb.Join(_context.Menus, od => od.MenuId, m => m.Id, (od, m) => new OrderDetailsForPrint
                {

                    Id = m.Id,
                    MenuName = m.Name,
                    Qty = od.Quantity,
                    CookingDeptId = m.CookingDepartmentId,
                    Price =  m.Price.ToString()

                }).ToList();

                orderDetailsMulti.AddRange(orderDetailsToPrint);
            }


            List orderDetails = new List();
            int qty = 0;
            foreach (var item in orderDetailsMulti)
            {
                var MenuFound = orderDetails.Find(x => x.MenuName == item.MenuName);
                if (MenuFound != null)
                {
                    
                    orderDetails.Find(x => x.MenuName == item.MenuName).Qty = (Convert.ToInt32(orderDetails.Find(x => x.MenuName == item.MenuName).Qty) + Convert.ToInt32(item.Qty)).ToString();
                }
                else
                {
                    orderDetails.Add(item);
                }
            }

            Graphics g = e.Graphics;
            // Head Takes = 50 Char
            // Regular Takes = 62 Char
            // Product 

            Font Head = new Font("Arial Narrow", 10, FontStyle.Regular);
            Font Regular = new Font("Arial Narrow", 8, FontStyle.Regular);
            Font RegularBold = new Font("Arial Narrow", 8, FontStyle.Bold);
            SolidBrush sb = new SolidBrush(Color.Black);

            var stream = _env.WebRootFileProvider.GetFileInfo(_config.Value.LogoPath).CreateReadStream();


            Image Logo = Image.FromStream(stream);

            e.Graphics.DrawImage(Logo, 30, 0, 200, 80);


            g.DrawString(_config.Value.CompanyName, Head, sb, 100, NewLine(9));
            g.DrawString(_config.Value.Address, Regular, sb, 50, NewLine(2));
            g.DrawString("Cell Mobile:"+_config.Value.MobilePhone, Regular, sb, 100, NewLine(2));
            g.DrawString("------------------------------------Invoice---------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("Invoice Number: ", Regular, sb, 0, NewLine(2));
            g.DrawString(orders.FirstOrDefault().InvoiceNumber, Regular, sb, 70, CurrentLine());
            g.DrawString("Date:", Regular, sb, 160, CurrentLine());
            g.DrawString(DateTime.Now.ToString("dd-MMM-yyy"), Regular, sb, 185, CurrentLine());
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("Sl.", Regular, sb, 0, NewLine(2));
            g.DrawString("Item Description", Regular, sb, 30, CurrentLine());
            g.DrawString("Unit Price", Regular, sb, 150, CurrentLine());
            g.DrawString("Qty", Regular, sb, 200, CurrentLine());
            g.DrawString("Total", Regular, sb, 240, CurrentLine());
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));

            int itemNo = 1;
            double sum = 0.0;
            double vat = 0.0;
            foreach (var item in orderDetails)
            {
                // get the line Needed for the ProductID string 

                List LineList = new List();


                if (item.ToString().Length > 22)
                {
                    string temp = item.MenuName;
                    while (temp.ToString().Length > 22)
                    {

                        string CutTemp = temp.Substring(0, 22);
                        if (CutTemp[22 - 1].ToString() != " ")
                        {
                            // find the space back in the line 
                            for (int i = 22 - 1; i > 0; i--)
                            {
                                if (CutTemp[i].ToString() == " ")
                                {
                                    CutTemp = temp.Substring(1, i);
                                    LineList.Add(CutTemp);
                                    temp = temp.Substring(i);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            temp = temp.Substring(22 - 1);
                            LineList.Add(CutTemp);
                        }


                    }
                    if (temp.ToString().Length > 0)
                    {
                        LineList.Add(temp.ToString());
                    }

                }
                else
                {
                    LineList.Add(item.MenuName);
                }




                g.DrawString(itemNo.ToString() + " ", Regular, sb, 0, NewLine(2));
                for (int i = 0; i < LineList.Count; i++)
                {
                    if (i == 0)
                    {
                        g.DrawString(LineList[i], Regular, sb, 10, CurrentLine());
                    }
                    else
                    {
                        g.DrawString(LineList[i], Regular, sb, 10, NewLine(2));
                    }

                }

                g.DrawString(item.Price.ToString(), Regular, sb, 155, CurrentLine());
                g.DrawString(item.Qty.ToString(), Regular, sb, 210, CurrentLine());
                g.DrawString((Convert.ToDouble( item.Price) * Convert.ToDouble(item.Qty)).ToString()+ "Tk", Regular, sb, 235, CurrentLine());
                itemNo++;

                sum += (Convert.ToDouble(item.Qty) * Convert.ToDouble( item.Price));

            }
            vat = Math.Floor((sum - discount) * _config.Value.VAT / 100);
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("Sub Total: ", Regular, sb, 150, NewLine(2));
            g.DrawString(sum.ToString()+" Tk", Regular, sb, 235, CurrentLine());

            g.DrawString("(-) Discount: ", Regular, sb, 150, NewLine(2));
            g.DrawString(discount.ToString()+" Tk", Regular, sb, 235, CurrentLine());


            g.DrawString("------------------------------------------", Regular, sb, 150, NewLine(2));
            // g.DrawString( (sum  - Convert.ToDouble(orderDetails.FirstOrDefault().Less)).ToString()  ,Regular, sb, 235, NewLine(2));
            g.DrawString("(+) VAT (+"+_config.Value.VAT+"%): ", Regular, sb, 150, NewLine(2));
            g.DrawString((vat).ToString() + " Tk", Regular, sb, 235, CurrentLine());
            g.DrawString("------------------------------------------", Regular, sb, 150, NewLine(2));


            g.DrawString("Net Payable: ", Regular, sb, 150, NewLine(2));
            g.DrawString(( sum - discount).ToString() + " Tk", Regular, sb, 235, CurrentLine());

            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));

            g.DrawString("** Your Total Saving Today **", Regular, sb, 0, NewLine(2));
            g.DrawString(discount.ToString() + " Tk", Regular, sb, 235, CurrentLine());


            g.DrawString("** VAT againts this cahallan is payable through central registration **", Regular, sb, 0, NewLine(4));

            g.DrawString("Thank you for your visit.", Regular, sb, 100, NewLine(2));

            g.DrawString("Purchase of defected item must be exchanged by 24 hours with invoice.", Regular, sb, 0, NewLine(2));

            g.DrawString("For any quries or complain, please call"+_config.Value.CellPhone+" (11.00 AM - 11.00PM)", Regular, sb, 0, NewLine(2));


          
           
            g.DrawString("Developed by Tawoon.org", Regular, sb, 95, NewLine(5));
            g.DrawString("", Regular, sb, 95, NewLine(4));
    }
       
        private int CurrentLine()
        {
            return CountLineNumber * lineHeight;
        }

        private int NewLine(int newLineNumber)
        {
            CountLineNumber = CountLineNumber + newLineNumber;
            return CountLineNumber * lineHeight;

        }
        [HttpPost]
        public bool PayBill([FromBody] PaymentDataView_Model paymentData)
        {
            // Update the Table Status 
            tableIdGlobal = paymentData.TableId;
            receivedAmount = paymentData.ReceivedAmount;
            paymentMethodId = paymentData.PayemntMethodId;
            returnAmount = paymentData.RetrunAmount;
            dueAmount = paymentData.DueAmount;


            var table = _context.Diningtables.SingleOrDefault(x => x.Id == paymentData.TableId);
            table.Status = "Free";
            _context.Update(table);
            _context.SaveChanges();

            var orders = _context.Orders.Where(x => x.DiningtableId == paymentData.TableId && x.IsPrinted == false).ToList();
          

            // Update Order Print Status 

            for (int i=0; i x.Id == paymentData.TableId);
            table.Status = "Free";
            _context.Update(table);
            _context.SaveChanges();

            var orders = _context.Orders.Where(x => x.DiningtableId == paymentData.TableId && x.IsPrinted == false).ToList();
            // send the print command to USP POS printer 

            PrintDocument prtdoc = new PrintDocument();
            string strDefaultPrinter = prtdoc.PrinterSettings.PrinterName;
            prtdoc.OriginAtMargins = true;
            prtdoc.DefaultPageSettings.Landscape = true;
            PrintDocument pd = new PrintDocument();

            //PaperSize ps = new PaperSize("", 285, 520);  //paper size 
            //pd.PrintPage += new PrintPageEventHandler(printPOSPagePayBill);
            //pd.PrintController = new StandardPrintController();
            //pd.DefaultPageSettings.Margins.Left = 0;
            //pd.DefaultPageSettings.Margins.Right = 0;
            //pd.DefaultPageSettings.Margins.Top = 0;
            //pd.DefaultPageSettings.Margins.Bottom = 10;
            //// pd.DefaultPageSettings.PaperSize = ps;
            //pd.Print();

            // Update Order Print Status 

            for (int i = 0; i < orders.Count; i++)
            {
                if (i == 0)
                {
                    orders[i].IsPrinted = true;
                    orders[i].PaymentmodeId = paymentData.PayemntMethodId;
                    orders[i].PaidAmount = paymentData.ReceivedAmount - paymentData.RetrunAmount;
                    orders[i].DueAmount = paymentData.DueAmount;

                    _context.Update(orders[i]);
                    _context.SaveChanges();
                }
                else
                {
                    orders[i].IsPrinted = true;
                    orders[i].PaymentmodeId = paymentData.PayemntMethodId;


                    _context.Update(orders[i]);
                    _context.SaveChanges();
                }

            }

           
            double discount = orders.FirstOrDefault().DiscountAmount;
            List orderDetailsMulti = new List();

            foreach (var item in orders)
            {
                var OrderDetailsDb = _context.Orderdetails.Where(x => x.OrderId == item.Id).ToList();

                var orderDetailsToPrint = OrderDetailsDb.Join(_context.Menus, od => od.MenuId, m => m.Id, (od, m) => new OrderDetailsForPrint
                {

                    Id = m.Id,
                    MenuName = m.Name,
                    Qty = od.Quantity,
                    CookingDeptId = m.CookingDepartmentId,
                    Price = m.Price.ToString()

                }).ToList();

                orderDetailsMulti.AddRange(orderDetailsToPrint);
            }


            List orderDetails = new List();
            int qty = 0;
            foreach (var item in orderDetailsMulti)
            {
                var MenuFound = orderDetails.Find(x => x.MenuName == item.MenuName);
                if (MenuFound != null)
                {

                    orderDetails.Find(x => x.MenuName == item.MenuName).Qty = (Convert.ToInt32(orderDetails.Find(x => x.MenuName == item.MenuName).Qty) + Convert.ToInt32(item.Qty)).ToString();
                }
                else
                {
                    orderDetails.Add(item);
                }
            }



            string baseUri = $"{Request.Scheme}://{Request.Host}";
            string imageUrl = string.Empty;
            imageUrl = baseUri + "/" + _config.Value.LogoPath;
            double Payable = orderDetails.Sum(x => Convert.ToDouble(x.Price)) - discount;

            double due = 0;
            double returnAmount = 0;

            due = Payable - returnAmount;
            if (due < 0)
            {
                due = due * (-1);
                returnAmount = due;
                
               
            }
            else if (due > 0)
            {
                returnAmount = 0;
            }
            else
            {
                  due = 0;
                 returnAmount = 0;
            }

            PrintInvoiceModel printInvoiceModel = new PrintInvoiceModel();
            printInvoiceModel.CompanyName = _config.Value.CompanyName;
            printInvoiceModel.Address = _config.Value.Address;
            printInvoiceModel.LogoUrl = imageUrl;
            printInvoiceModel.CellPhone = _config.Value.MobilePhone;
            printInvoiceModel.Email = _config.Value.Email;
            printInvoiceModel.Date = DateTime.Now.Date.ToString("dd-MM-yy");
            printInvoiceModel.Time = DateTime.Now.ToString("hh:mm tt");
            printInvoiceModel.orderDetailsForPrints = orderDetails;
            printInvoiceModel.Discount = discount;
            printInvoiceModel.VAT = _config.Value.VAT;
            printInvoiceModel.ReceivedAmount = receivedAmount;
            printInvoiceModel.SubTotal = orderDetails.Sum(x => Convert.ToDouble(x.Price));
            printInvoiceModel.Payable = Payable;
            printInvoiceModel.Retrun = returnAmount;
            printInvoiceModel.Due = due;
            printInvoiceModel.InvoiceNo = orders.FirstOrDefault().InvoiceNumber;






            return printInvoiceModel;
            
        }

        public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, format);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
        public async Task PrintPreview(PrintInvoiceModel printInvoiceModel )
        {

            return View();
        }
        private void printPOSPagePayBill(object sender, PrintPageEventArgs e)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            Encoding.GetEncoding("windows-1252");

            var orders = _context.Orders.Where(x => x.DiningtableId == tableIdGlobal && x.IsPrinted == false).ToList();
            double discount = orders.FirstOrDefault().DiscountAmount;
            List orderDetailsMulti = new List();

            foreach (var item in orders)
            {
                var OrderDetailsDb = _context.Orderdetails.Where(x => x.OrderId == item.Id).ToList();

                var orderDetailsToPrint = OrderDetailsDb.Join(_context.Menus, od => od.MenuId, m => m.Id, (od, m) => new OrderDetailsForPrint
                {

                    Id = m.Id,
                    MenuName = m.Name,
                    Qty = od.Quantity,
                    CookingDeptId = m.CookingDepartmentId,
                    Price = m.Price.ToString()

                }).ToList();

                orderDetailsMulti.AddRange(orderDetailsToPrint);
            }


            List orderDetails = new List();
            int qty = 0;
            foreach (var item in orderDetailsMulti)
            {
                var MenuFound = orderDetails.Find(x => x.MenuName == item.MenuName);
                if (MenuFound != null)
                {

                    orderDetails.Find(x => x.MenuName == item.MenuName).Qty = (Convert.ToInt32(orderDetails.Find(x => x.MenuName == item.MenuName).Qty) + Convert.ToInt32(item.Qty)).ToString();
                }
                else
                {
                    orderDetails.Add(item);
                }
            }

            Graphics g = e.Graphics;
            // Head Takes = 50 Char
            // Regular Takes = 62 Char
            // Product 

            Font Head = new Font("Arial Narrow", 10, FontStyle.Regular);
            Font Regular = new Font("Arial Narrow", 8, FontStyle.Regular);
            Font RegularBold = new Font("Arial Narrow", 8, FontStyle.Bold);
            SolidBrush sb = new SolidBrush(Color.Black);

            var stream = _env.WebRootFileProvider.GetFileInfo(_config.Value.LogoPath).CreateReadStream();


            Image Logo = Image.FromStream(stream);

            e.Graphics.DrawImage(Logo, 35, 0, 200, 80);

            
            g.DrawString(_config.Value.CompanyName, Head, sb, 100, NewLine(9));
            g.DrawString(_config.Value.Address, Regular, sb, 50, NewLine(2));
            g.DrawString("Cell Mobile:"+_config.Value.MobilePhone, Regular, sb, 100, NewLine(2));
            g.DrawString("------------------------------------Invoice---------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("Invoice Number: ", Regular, sb, 0, NewLine(2));
            g.DrawString(orders.FirstOrDefault().InvoiceNumber, Regular, sb, 70, CurrentLine());
            g.DrawString("Date:", Regular, sb, 160, CurrentLine());
            g.DrawString(DateTime.Now.ToString("dd-MMM-yyy"), Regular, sb, 185, CurrentLine());
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("Sl.", Regular, sb, 0, NewLine(2));
            g.DrawString("Item Description", Regular, sb, 30, CurrentLine());
            g.DrawString("Unit Price", Regular, sb, 150, CurrentLine());
            g.DrawString("Qty", Regular, sb, 200, CurrentLine());
            g.DrawString("Total", Regular, sb, 240, CurrentLine());
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));

            int itemNo = 1;
            double sum = 0.0;
            double vat = 0.0;
            foreach (var item in orderDetails)
            {
                // get the line Needed for the ProductID string 

                List LineList = new List();


                if (item.ToString().Length > 22)
                {
                    string temp = item.MenuName;
                    while (temp.ToString().Length > 22)
                    {

                        string CutTemp = temp.Substring(0, 22);
                        if (CutTemp[22 - 1].ToString() != " ")
                        {
                            // find the space back in the line 
                            for (int i = 22 - 1; i > 0; i--)
                            {
                                if (CutTemp[i].ToString() == " ")
                                {
                                    CutTemp = temp.Substring(1, i);
                                    LineList.Add(CutTemp);
                                    temp = temp.Substring(i);
                                    break;
                                }
                            }
                        }
                        else
                        {
                            temp = temp.Substring(22 - 1);
                            LineList.Add(CutTemp);
                        }


                    }
                    if (temp.ToString().Length > 0)
                    {
                        LineList.Add(temp.ToString());
                    }

                }
                else
                {
                    LineList.Add(item.MenuName);
                }




                g.DrawString(itemNo.ToString() + " ", Regular, sb, 0, NewLine(2));
                for (int i = 0; i < LineList.Count; i++)
                {
                    if (i == 0)
                    {
                        g.DrawString(LineList[i], Regular, sb, 10, CurrentLine());
                    }
                    else
                    {
                        g.DrawString(LineList[i], Regular, sb, 10, NewLine(2));
                    }

                }

                g.DrawString(item.Price.ToString(), Regular, sb, 155, CurrentLine());
                g.DrawString(item.Qty.ToString(), Regular, sb, 210, CurrentLine());
                g.DrawString((Convert.ToDouble(item.Price) * Convert.ToDouble(item.Qty)).ToString()+ "Tk", Regular, sb, 235, CurrentLine());
                itemNo++;

                sum += (Convert.ToDouble(item.Qty) * Convert.ToDouble(item.Price));

              
            }

            vat = Math.Floor((sum - discount) * _config.Value.VAT/ 100);
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("Sub Total: ", Regular, sb, 150, NewLine(2));
            g.DrawString(sum.ToString()+" Tk", Regular, sb, 235, CurrentLine());

            g.DrawString("(-) Discount: ", Regular, sb, 150, NewLine(2));
            g.DrawString(discount.ToString()+" Tk", Regular, sb, 235, CurrentLine());
            g.DrawString("------------------------------------------", Regular, sb, 150, NewLine(2));

            g.DrawString("(+) VAT ("+_config.Value.VAT+"%): ", Regular, sb, 150, NewLine(2));
            g.DrawString((vat).ToString() + " Tk", Regular, sb, 235, CurrentLine());
            g.DrawString("------------------------------------------", Regular, sb, 150, NewLine(2));


            g.DrawString("Net Payable: ", Regular, sb, 150, NewLine(2));
            g.DrawString(((sum - discount)+vat).ToString() + " Tk", Regular, sb, 235, CurrentLine());

            g.DrawString("-----------------------------------------------", Regular, sb, 150, NewLine(2));
            g.DrawString("Received: ", Regular, sb, 150, NewLine(2));
            g.DrawString( receivedAmount.ToString()+" Tk", Regular, sb, 235, CurrentLine());
            g.DrawString("-----------------------------------------------", Regular, sb, 150, NewLine(2));


            g.DrawString("Retrun: ", Regular, sb, 150, NewLine(2));
            g.DrawString(returnAmount.ToString()+ "Tk", Regular, sb, 235, CurrentLine());
            g.DrawString("-----------------------------------------------", Regular, sb, 150, NewLine(2));

            g.DrawString("Due: ", Regular, sb, 150, NewLine(2));
            g.DrawString(dueAmount.ToString()+ "Tk", Regular, sb, 235, CurrentLine());
            g.DrawString("-------------------------------------------------------------------------------------------", Regular, sb, 0, NewLine(2));
            g.DrawString("** Your Total Saving Today **", Regular, sb, 0, NewLine(2));
            g.DrawString(discount.ToString() + " Tk", Regular, sb, 235, CurrentLine());


            g.DrawString("** VAT againts this cahallan is payable through central registration **", Regular, sb, 0, NewLine(4));

            g.DrawString("Thank you for your visit.", Regular, sb, 100, NewLine(2));

            g.DrawString("Purchase of defected item must be exchanged by 24 hours with invoice.", Regular, sb, 0, NewLine(2));

            g.DrawString("For any quries or complain, please call"+_config.Value.CellPhone+" (11.00 AM - 11.00PM)", Regular, sb, 0, NewLine(2));




            g.DrawString("Developed by Tawoon.org", Regular, sb, 95, NewLine(5));
            g.DrawString("", Regular, sb, 95, NewLine(4));

        }

        [HttpPost]  
        public object BillPreview([FromBody] int data)
        {


            BillPreviewModel billPreviewModel = new BillPreviewModel();

            double tatalAmount = 0;
            double discount = 0;

            double netAmount = 0; 


            // Update Order Print Status 

            var orders = _context.Orders.Where(x => x.DiningtableId == data && x.IsPrinted == false).ToList();


            // send the print command t0 IP printer 

            foreach (var item in orders)
            {
                tatalAmount = tatalAmount + item.TotalPrice;
                discount = item.DiscountAmount;

            }
            double vat = ((tatalAmount - discount) * _config.Value.VAT / 100);

            double netPayableRounded = Math.Floor((tatalAmount - discount) + vat);

            billPreviewModel.TotalBill = tatalAmount.ToString();
            billPreviewModel.Discount = discount.ToString();
            billPreviewModel.VAT = vat.ToString();
            billPreviewModel.NetBill = netPayableRounded.ToString();

            return billPreviewModel;

        }

        public bool AddDiscount([FromBody] AddDiscountViewModel discount )
        {
           

            var orders = _context.Orders.Where(x => x.DiningtableId == discount.TableId && x.IsPrinted == false).ToList();

            foreach (var item in orders)
            {
                item.DiscountAmount = discount.DiscountAmount;

                _context.Update(item);
                _context.SaveChanges();
            }
            return true;

        }

        [HttpPost]
        public async Task SaveOrderVoid([FromBody] OrderViewModel model )
        { 


          
            int DiningTableId = Convert.ToInt32(model.DiningTableId);
            List itemTotalPriceList = new List();
            List MenuListFromOrder = new List();
            List VoidMenuListFromVoid = new List();

            List itemtoRemove = new List();


            var orders = _context.Orders.Where(x => x.DiningtableId == DiningTableId && x.IsPrinted == false).ToList();

         
            foreach (var item in model.OrderDetails)
            {
                VoidMenuListFromVoid.Add(item.MenuId);
            }


            foreach (var order in orders)
            {
                var details = _context.Orderdetails.Where(x => x.OrderId == order.Id).ToList();
                foreach (var d in details)
                {
                    MenuListFromOrder.Add(d.MenuId);
                } 
            }


            var ss = MenuListFromOrder.Distinct().ToList();

          
            for(int i =0; i x.OrderId == order.Id).ToList();
                for (int i = 0; i < itemtoRemove.Count; i++)
               
                {

                    for (int j= 0; j < details.Count; j++)
                    {
                        if (details[j].MenuId == itemtoRemove[i])
                        {

                            details[j].Quantity = "0";

                            _context.Update(details[j]);

                            _context.SaveChanges();


                        }

                       
                    }
                }
            }


            




            // re-assign the item qty in order details table

            //foreach (var item in model.OrderDetails)
            //{

            //   //2
            //    for (int i = 0; i x.OrderId == orders[i].Id).ToList().Count;
                  
            //        //2
            //        for (int k = 0; k < orderDetailsCount; k++)
            //        {
            //            if (i == 0)
            //            {
            //                var orderDetails = _context.Orderdetails.SingleOrDefault(x => x.OrderId == orders[i].Id && x.MenuId == item.MenuId);
            //                orderDetails.Quantity = item.Quantity;
            //                _context.Update(orderDetails);
            //                _context.SaveChanges();


                          


            //            }
            //            else
            //            {
            //                var orderDetails = _context.Orderdetails.SingleOrDefault(x => x.OrderId == orders[i].Id && x.MenuId == item.MenuId);
            //                orderDetails.Quantity = "0";
            //                _context.Update(orderDetails);
            //                _context.SaveChanges();

            //            }

                       

            //        }



            //    }


            //    }




            // re-calculate the order by orderId
            double sum = 0;

            foreach (var order in orders)
            {
                var details = _context.Orderdetails.Where(x => x.OrderId == order.Id).ToList();
                foreach (var d in details)
                {
                    var price = _context.Menus.SingleOrDefault(x => x.Id == d.MenuId).Price;

                    sum += Convert.ToDouble(d.Quantity) * Convert.ToDouble(price);


                }
            }

            for (int i = 0; i < orders.Count; i++)
            {
                if (i == 0)
                {
                    orders[i].TotalPrice = sum;
                    _context.Update(orders[i]);
                    _context.SaveChanges();

                }

                else
                {
                    orders[i].TotalPrice = 0;
                    _context.Update(orders[i]);
                    _context.SaveChanges();

                }
            }





         
            return true;
        }


        [HttpPost]
        public async Task SaveOrder([FromBody] OrderViewModel order)
        {
                double totalPrice = Convert.ToDouble(order.TotalPrice);
                int DiningTableId = Convert.ToInt32(order.DiningTableId);
                int employeeID   = Convert.ToInt32(order.EmployeeId);
                string lastInvoiceNumber = _context.Orders.OrderByDescending(x => x.Id).Select(x=>x.InvoiceNumber).FirstOrDefault();
                var ss = _context.Orders.OrderBy(x => x.Id).FirstOrDefault();
            Order orderModel = new Order {
                CreatedAt = DateTime.Now,
                IsPrinted = false, 
                Note = order.Note,
                EmployeeId = employeeID,
                DiningtableId = DiningTableId,  
                CreatedBy = User.FindFirstValue(ClaimTypes.NameIdentifier), 
                TotalPrice = totalPrice,
                InvoiceNumber = _utilityFunctions.GetUnicInvoiceNumber(lastInvoiceNumber),
                Date = DateTime.Now.ToString("MM/dd/yyyy"),
                     
            };
            _context.Add(orderModel);
            await _context.SaveChangesAsync();
          

          

            List orderDetailsList = new List();

            foreach (var item in order.OrderDetails)
            {
                Orderdetail orderDetails = new Orderdetail
                {
                    OrderId = orderModel.Id,
                    MenuId = item.MenuId,
                    Quantity = item.Quantity,
                    ExtraIngredients = item.ExtraIngredients, 
                    CreatedAt = DateTime.Now

                };

               orderDetailsList.Add(orderDetails);
            }
            
            _context.AddRange(orderDetailsList);
            await _context.SaveChangesAsync();

            var diningtable = await _context.Diningtables.FindAsync(DiningTableId);
            var diningTableName = diningtable.Name;
            diningtable.Status = TableStatus.Busy.ToString();

            _context.Update(diningtable);
            _context.SaveChanges();


            // send the Print Command to the Printer

           

            var arabic_Chinees = orderDetailsList.Join(_context.Menus, od => od.MenuId, m => m.Id, (od, m) => new OrderDetailsForPrint
            {

                Id = m.Id,
                MenuName = m.Name,
                Qty = od.Quantity,
                CookingDeptId = m.CookingDepartmentId

            }).Where(x => x.CookingDeptId == 1).ToList();

            var drinks_kabab = orderDetailsList.Join(_context.Menus, od => od.MenuId, m => m.Id, (od, m) => new OrderDetailsForPrint
            {

                Id = m.Id,
                MenuName = m.Name,
                Qty = od.Quantity,
                CookingDeptId = m.CookingDepartmentId

            }).Where(x => x.CookingDeptId == 2).ToList();



            //string ipAddress_drinks_kabab = _config.Value.KitchenLanPrinter_IP;
            //byte[] data = GetPrintData(drinks_kabab, diningTableName, orderModel.Id, "Drinks & Kabab");
            //TcpPrint(ipAddress_drinks_kabab, data);



            //string ipAddress_arabic_chinees = _config.Value.KitchenLanPrinter_IP;
            //byte[] data_arabic = GetPrintData(arabic_Chinees, diningTableName, orderModel.Id, "Arabic & Chinees");
            //TcpPrint(ipAddress_arabic_chinees, data_arabic);

            return true;

        }


        [HttpPost]
        public bool SaveTransection([FromBody] TransectionModel transectionData)
        {
            double cashoutAmount =    transectionData.Amount=="" ? 0:Convert.ToDouble(transectionData.Amount);
            int CashOutSubTypesId = transectionData.CashOutSubTypesId =="" ? 0 : Convert.ToInt32(transectionData.CashOutSubTypesId);
            int CashoutTypeId = transectionData.CashoutTypeId =="" ? 0: Convert.ToInt32(transectionData.CashoutTypeId);
            int EmployeeId = transectionData.EmployeesId =="" ? 0 : Convert.ToInt32(transectionData.EmployeesId);
            int SupplierId = transectionData.SuppliersId == ""? 0 : Convert.ToInt32(transectionData.SuppliersId);

            LedgerBook ledger = new LedgerBook { 
                    CashOutAmount = cashoutAmount,
                    CashOutSubTypesId = CashOutSubTypesId,
                    CashoutTypeId = CashoutTypeId,
                    Collection = 0,
                    EmployeesId = EmployeeId,
                    EntryTime = DateTime.Now,
                    IsValid = true,
                    Less = 0, 
                    Refund = 0,
                    Sales = 0,
                    SuppliersId = SupplierId,
                    TrDate = DateTime.Now,
                    TrNo = "",
                    UserId = User.FindFirstValue(ClaimTypes.NameIdentifier)



        };
            _context.Add(ledger);
          var result =  _context.SaveChanges();


            return  result>0? true: false;
           
        }
    }
}


Comments

Popular posts from this blog

Object Storage System Design

Object Storage System Design 𝐁𝐮𝐜𝐤𝐞𝐭. A logical container for objects. The bucket name is globally unique. To upload data to S3, we must first create a bucket. 𝐎𝐛𝐣𝐞𝐜𝐭. An object is an individual piece of data we store in a bucket. It contains object data (also called payload) and metadata. Object data can be any sequence of bytes we want to store. The metadata is a set of name-value pairs that describe the object. In S3, an object resides in a bucket. The path looks like this: /bucket-to-share/style.css. The bucket only has metadata. The object has metadata and the actual data. The diagram below (Figure 1) illustrates how file uploading works. In this example, we first create a bucket named and then upload a file named “style.css” to the bucket. 1. The client sends an HTTP PUT request to create a bucket named “bucket-to-share.” The request is forwarded to the API service. 2. The API service calls Identity and Access Management (IAM) to ensure the user is authorized and has W...

Debug Entity Validation Exception C#

      Try this try and cath. put your SaveChanges() method inside the try block.             try             {                 db.tbl_Payroll_full_day_leaves.Add(tbl_Payroll_Leaves);                 if (0 < db.SaveChanges())                 {                     return true;                 }                 else                 {                     return false;                 }             }             catch (DbEntityValidationException e)       ...