// BUY Cart
        protected void Button_Buy_Click(object sender, EventArgs e)
        {
            bool phoneNumExists = false;
            if (phoneNumExists)
            {
                // Make reciept on phone number
                // Make customer

                // Make reciept

            }
            else
            {
                // Make NEW CUSTOMER and Reciept on NEW CUSTOMER PHONE NUMBER
                Customer newCust = new Customer(null, TextBox_fullName.Text, TextBox_address.Text, TextBox_phoneNumNew.Text, TextBox_email.Text, 0);
                List<Animal> animals = new List<Animal>();
                foreach (Animal a in selectedAnimals)
                {
                    animals.Add(a);
                }
                Receipt newReceipt = new Receipt(animals, new DateTime(), 0);
                PersistenceController controller = Persistence.PersistenceController.Instance();
                controller.makeReceipt(newReceipt, newCust);

            }
        }
Beispiel #2
2
        private String saveFile(HttpPostedFile postedFile)
        {
            int userID = 0;
            string userName = getUserNameFromFile(postedFile);
            EReceiptLINQDataContext context = new EReceiptLINQDataContext();

            var lastReceiptNumber = from num in context.Receipts
                                    select num;

            int maxReceiptValue = (from c in lastReceiptNumber select c.RECEIPT_ID).Max();

            string savePath = ("~/IMG/receiptImage/" + userName + "/receipt" + (maxReceiptValue + 1) + ".jpg");
            DirectoryCheck(userName);
            FileUpload1.SaveAs(Server.MapPath(savePath));

            string pathOfFile = "http://localhost:49765/" + savePath.Substring(savePath.IndexOf("~") + 2);

            Receipt receiptImage = new Receipt
            {
                RECEIPT_URL = pathOfFile,
                UPLOAD_DATE = DateTime.Now,

            };
            context.Receipts.InsertOnSubmit(receiptImage);
            context.SubmitChanges();

            var userIDNumber = from u in context.Customers
                               where u.USER_NAME == userName
                               select u;

            foreach (var x in userIDNumber)
            {
                userID = x.USER_ID;
                break;
            }

            CustomerReceipt custRec = new CustomerReceipt
            {
                USER_ID = userID,
                RECEIPT_ID = (maxReceiptValue + 1),

            };
            context.CustomerReceipts.InsertOnSubmit(custRec);
            context.SubmitChanges();

            context.Connection.Close();
            Label1.Text = "Upload Successful";
            return savePath;
        }
 private void bindReceiptToUI(Receipt r)
 {
     lblReceiptNoValue.Text = r.Id == 0 ? "[New]" : r.Id.ToString();
     txtAmount.Text = r.Amount.ToString();
     dtDate.Value = r.Date==null? DateTime.Today: (DateTime)r.Date;
     cmbBills.SelectedItem = r.Bill;
 }
        // This method will go through the process of acquiring the data for an individual receipt, and then returning the finished receipt.
        public Receipt getReceiptEntry(string receiptOwner, int receiptNumber)
        {
            Receipt receipt = new Receipt(receiptOwner, receiptNumber);
            Console.WriteLine("\nReceipt {0}{1}:", receiptOwner, receiptNumber);
            Console.Write("Enter Receipt {0}{1}'s Communal Total: ", receiptOwner, receiptNumber);
            double communalTotal = Convert.ToDouble(Console.ReadLine());
            receipt.getCommunalTotal(communalTotal);

            Console.Write("\nAre there any individual items that are not communal? (y/n): ");
            string answer = Console.ReadLine().ToUpper();

            if (answer == "Y") {
                Console.WriteLine("Enter the first initial of the persons to whom the item(s) was bought for (A / V / M).");
                Console.Write("If multiple persons have items on this Receipt, separate their initials with a space: ");
                string indivItemOwner = Console.ReadLine().ToUpper();
                string[] initials = indivItemOwner.Split(' ');

                for (int j = 0; j < initials.Length; j++) {
                    indivItemOwner = initials[j];
                    switch (initials[j]) {
                        case "A":
                            Console.Write("\nEnter the total amount (including tax) that Andy owes for his items on Receipt {0}{1}: ", receiptOwner, receiptNumber);
                            receipt.getIndivTotal(indivItemOwner, Convert.ToDouble(Console.ReadLine()));
                            break;
                        case "V":
                            Console.Write("\nEnter the total amount (including tax) that Vinny owes for his items on Receipt {0}{1}: ", receiptOwner, receiptNumber);
                            receipt.getIndivTotal(indivItemOwner, Convert.ToDouble(Console.ReadLine()));
                            break;
                        case "M":
                            Console.Write("\nEnter the total amount (including tax) that Mike owes for his items on Receipt {0}{1}: ", receiptOwner, receiptNumber);
                            receipt.getIndivTotal(indivItemOwner, Convert.ToDouble(Console.ReadLine()));
                            break;
                        default:
                            Console.WriteLine("Error: Unrecognized first initial.");
                            break;
                    }
                }
            }
            // Now we display all of the data entered for the current receipt.
            Console.WriteLine("\nReceipt {0}{1}:", receiptOwner, receiptNumber);
            Console.WriteLine("Communal Total = {0}", receipt.returnCommunalTotal());
            if (receiptOwner == "A") {
                Console.WriteLine("Additional Amount Owed By Vince: {0}", receipt.returnVTotal());
                Console.WriteLine("Additional Amount Owed By Mike: {0}", receipt.returnMTotal());
            }
            else if (receiptOwner == "V") {
                Console.WriteLine("Additional Amount Owed By Andy: {0}", receipt.returnATotal());
                Console.WriteLine("Additional Amount Owed By Mike: {0}", receipt.returnMTotal());
            }
            else if (receiptOwner == "M") {
                Console.WriteLine("Additional Amount Owed By Andy: {0}", receipt.returnATotal());
                Console.WriteLine("Additional Amount Owed By Vince: {0}", receipt.returnVTotal());
            }
            return receipt;
        }
Beispiel #5
0
 public void Insert(Receipt receipt)
 {
     using (var context = new TrianglesDataContext())
     {
         context.Receipts.InsertOnSubmit(receipt);
         context.SubmitChanges();
     }
 }
 public Overpayment(int overpayment_id, int receipt_id, decimal total, DateTime overpayment_date_added, int staff_id)
 {
     this.overpayment_id = overpayment_id;
     this.receipt = new Receipt(receipt_id);
     this.total = total;
     this.overpayment_date_added = overpayment_date_added;
     this.staff = new Staff(staff_id);
 }
        private void btnNew_Click(object sender, EventArgs e)
        {
            receipt = new Receipt();
            loadOutstandingBills();
            bindReceiptToUI(receipt);

            cmbBills.Text = "";
            lblCustomerName.Text = "";
        }
 public void InitPageParameter(Receipt receipt, bool printReceipt)
 {
     this.ReceiptNo = receipt.ReceiptNo;
     this.ucEdit.InitPageParameter(ReceiptNo);
     this.ucList.InitPageParameter(receipt);
     if (printReceipt)
     {
         this.PrintReceipt(receipt);
     }
 }
Beispiel #9
0
        public void Update(Receipt receipt)
        {
            using (var context = new TrianglesDataContext())
            {
                var existedReceipt = context.Receipts.First(x => x.Id == receipt.Id);

                existedReceipt.Description = receipt.Description;
                existedReceipt.Payer = receipt.Payer;

                context.SubmitChanges();
            }
        }
 protected void Calculate_Click(object sender, EventArgs e)
 {
     if (IsValid)
     {
         Receipt receiptInstance = new Receipt(Double.Parse(TotalSum.Text));
         ReceiptPanel.Visible = true;
         SubTotal.Text = String.Format("{0:c}", receiptInstance.Subtotal);
         DiscountRate.Text = String.Format("{0:p0}", receiptInstance.DiscountRate);
         Discount.Text = String.Format("{0:c}", receiptInstance.MoneyOff);
         Total.Text = String.Format("{0:c}", receiptInstance.Total);
     }
 }
        protected void Send_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                Output.Visible = true;
                var receipt = new Receipt(double.Parse(Input.Text));
                Total.Text = String.Format("{0:C}", receipt.Subtotal);
                Discount.Text = String.Format("{0:C}", receipt.MoneyOff);
                PayValue.Text = String.Format("{0:C}", receipt.Total);
                DiscountRate.Text = String.Format("{0:P0}", receipt.DiscountRate);

            }
        }
    void Start () {
        var address = new Address
        {
            street = "123 Tornado Alley\nSuite 16",
            city = "East Westville",
            state = "KS"
        };

        var receipt = new Receipt
        {
            receipt = "Oz-Ware Purchase Invoice",
            date = new DateTime(2007, 8, 6),
            customer = new Customer
            {
                given = "Dorothy",
                family = "Gale"
            },
            items = new Item[]
            {
                new Item
                {
                    part_no = "A4786",
                    descrip = "Water Bucket (Filled)",
                    price = 1.47M,
                    quantity = 4
                },
                new Item
                {
                    part_no = "E1628",
                    descrip = "High Heeled \"Ruby\" Slippers",
                    price = 100.27M,
                    quantity = 1
                }
            },
            bill_to = address,
            ship_to = address,
            specialDelivery = "Follow the Yellow Brick\n" +
                              "Road to the Emerald City.\n" +
                              "Pay no attention to the\n" +
                              "man behind the curtain."
        };

        var serializer = new Serializer();
        var stringBuilder = new StringBuilder();
        var stringWriter = new StringWriter(stringBuilder);
        serializer.Serialize(stringWriter, receipt);

        Debug.Log(stringBuilder);
    }
Beispiel #13
0
 public ActionResult Edit(Receipt model)
 {
     using (CTSContext context = new CTSContext())
     {
         var receipts = context.Receipts.FirstOrDefault(p => p.Id == model.Id);
         receipts.BelongCompany = context.CourierCompanys.FirstOrDefault(p => p.Id == model.BelongCompany.Id);
         receipts.CourierNumber = model.CourierNumber;
         receipts.CustomerAddress = model.CustomerAddress;
         receipts.CustomerName = model.CustomerName;
         receipts.CustomerPhone = model.CustomerPhone;
         receipts.Remark = model.Remark;
         context.SaveChanges();
         return Json(new AjaxResult("编辑成功", AjaxResultType.Success));
     }
 }
    private void PrintReceipt(Receipt receipt)
    {
        receipt.ReceiptDetails = TheReceiptDetailMgr.SummarizeReceiptDetails(receipt.ReceiptDetails);

        IList<object> list = new List<object>();
        list.Add(receipt);
        list.Add(receipt.ReceiptDetails);
        //TheReportReceiptNoteMgr.FillValues(receipt.ReceiptTemplate, list);
        //报表url
        string strUrl = TheReportMgr.WriteToFile(receipt.ReceiptTemplate, list);
        //客户端打印
        //如果在UpdatePanel中调用JavaScript需要使用 ScriptManager.RegisterClientScriptBlock
        ScriptManager.RegisterClientScriptBlock(this, GetType(), "method", " <script language='javascript' type='text/javascript'>PrintOrder('" + strUrl + "'); </script>", false);
        //Page.ClientScript.RegisterStartupScript(GetType(), "method", " <script language='javascript' type='text/javascript'>PrintOrder('" + strUrl + "'); </script>");
    }
 public void ItCalculatesATotalWith1ItemDecimal()
 {
     var receipt = new Receipt()
     {
         ScannedItems = new List<ScannedItem>()
         {
             new ScannedItem { Name = "Apple" },
         },
         ItemPrices = new List<ItemPrice>()
         {
             new ItemPrice() { Name = "Apple", Price = 0.75M }
         }
     };
     Assert.AreEqual(0.75M, receipt.GetTotal());
 }
        private void ReceiptReport_Load(object sender, EventArgs e)
        {
            string stringFormula;

            BookingSystemDataSet ds = new BookingSystemDataSet();
            BookingSystemDataSetTableAdapters.TransactionsTableAdapter ta = new BookingSystemDataSetTableAdapters.TransactionsTableAdapter();
            ta.Fill(ds.Transactions);

            stringFormula = "{Transactions.ID}=" + id.ToString();
            crystalReportViewer1.SelectionFormula = stringFormula;

            Receipt crpt = new Receipt();
            crpt.SetDataSource(ds);
            crystalReportViewer1.ReportSource = crpt;
        }
 public void ItPrintsABasicReceiptItemWithDecimals()
 {
     var receipt = new Receipt
     {
         ItemPrices = new List<ItemPrice>
         {
             new ItemPrice { Name = "Apple", Price = 0.75M}
         },
         ScannedItems = new List<ScannedItem>
         {
             new ScannedItem() { Name="Apple" }
         }
     };
     var receiptPrinter = new ReceiptPrinter(receipt);
     Assert.AreEqual("Apple x1\t$0.75", receiptPrinter.PrintItems().Trim());
 }
 public void InitPageParameter(Receipt receipt)
 {
     IList<ReceiptDetail> receiptDetailList = new List<ReceiptDetail>();
     if (receipt.ReceiptDetails != null && receipt.ReceiptDetails.Count > 0)
     {
         foreach (ReceiptDetail receiptDetail in receipt.ReceiptDetails)
         {
             if (receiptDetail.HuId != null)
             {
                 receiptDetailList.Add(receiptDetail);
             }
         }
     }
     this.GV_List.DataSource = receiptDetailList;
     this.GV_List.DataBind();
 }
 public void ItCalculatesATotalWithDuplicateItem()
 {
     var receipt = new Receipt()
     {
         ScannedItems = new List<ScannedItem>()
         {
             new ScannedItem { Name = "Apple" },
             new ScannedItem { Name = "Apple" },
         },
         ItemPrices = new List<ItemPrice>()
         {
             new ItemPrice() { Name = "Apple", Price = 1 }
         }
     };
     Assert.AreEqual(2, receipt.GetTotal());
 }
Beispiel #20
0
        protected static void ValidateReceipt(Dictionary<Guid, decimal> owed, Receipt receipt)
        {
            IEnumerable<Payment> payments = Database.GetPaymentsByReceipt(receipt.Id);

            decimal total = 0;
            decimal tip = 0;
            decimal tax = 0;

            decimal pmtReduction = 0;
            foreach (Payment pmt in payments) {
                total += pmt.PaymentAmount;
                tip += pmt.Tip;
                tax += pmt.Tax;

                if (pmt.Payer == receipt.Payer) {
                    continue;
                }

                decimal payeeTotal = pmt.PaymentAmount + pmt.Tip + pmt.Tax;

                pmtReduction += payeeTotal;

                owed[pmt.Payer] += payeeTotal;
            }

            owed[receipt.Payer] -= pmtReduction;

            tip = Math.Round(tip, 2);

            tax = Math.Round(tax, 2);

            total += tip + tax;

            total = Math.Round(total, 2);

            if (receipt.Total != total) {
                throw new InvalidTotalException(receipt, total);
            }

            if (receipt.Tip != tip) {
                throw new InvalidTipException(receipt, tip);
            }

            if (receipt.Tax != tax) {
                throw new InvalidTaxException(receipt, tax);
            }
        }
Beispiel #21
0
 public ActionResult Add(Receipt model)
 {
     using (CTSContext context = new CTSContext())
     {
         model.BelongCompany = context.CourierCompanys.FirstOrDefault(p => p.Id == model.BelongCompany.Id);
         if (!context.Customers.Any(p => p.CustomerPhone.Equals(model.CustomerPhone)))
         {
             context.Customers.Add(new Customer()
             {
                 CustomerName = model.CustomerName,
                 CustomerPhone = model.CustomerPhone
             });
         }
         context.Receipts.Add(model);
         context.SaveChanges();
         return Json(new AjaxResult("添加成功", AjaxResultType.Success));
     }
 }
        public void SubmitChanges(Receipt document,BasicConfig config)
        {
            int sequence = 0;
            var envelope = new CommandEnvelope();
            envelope.Initialize(document);
            List<DocumentCommand> commandsToExecute = document.GetDocumentCommandsToExecute();

            CreateCommand createCommand; //= commandsToExecute.OfType<CreateCommand>().First();
            if (TryGetCreateCommand(commandsToExecute, out createCommand))
            {
                envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, createCommand));
               // _commandRouter.RouteDocumentCommand(createCommand);
                _auditLogWFManager.AuditLogEntry("Receipt",
                                                 string.Format("Created Receipt: {0}; for invoice: {1}", document.Id,
                                                               document.InvoiceId));
            }
            List<AfterCreateCommand> lineItemCommands;
            if (TryGetAfterCreateCommands(commandsToExecute, out lineItemCommands))
            {
                foreach (var item in lineItemCommands)
                {
                    envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, item));
                  //  _commandRouter.RouteDocumentCommand(item);
                    var _item = item as AddReceiptLineItemCommand;
                    _auditLogWFManager.AuditLogEntry("Receipt",
                                                     string.Format(
                                                         "Added Product type: {0}; Quantity: {1}; for Invoice: {2};",
                                                         _item.LineItemType, _item.Value, document.InvoiceId));
                }
            }
            ConfirmCommand confirmCommand;
            if (TryGetConfirmCommand(commandsToExecute, out confirmCommand))
            {
                envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, confirmCommand));
               // _commandRouter.RouteDocumentCommand(confirmCommand);
                _auditLogWFManager.AuditLogEntry("Receipt",
                                                 string.Format("Confirmed Receipt: {0}; for Invoice: {1}", document.Id,
                                                               document.InvoiceId));
               // _notifyService.SubmitRecieptNotification(document);

            }
            _commandEnvelopeRouter.RouteCommandEnvelope(envelope);
            document.CallClearCommands();
        }
 public void ItPrintsABasicReceipt()
 {
     var receipt = new Receipt
     {
         ItemPrices = new List<ItemPrice>
         {
             new ItemPrice { Name = "Apple", Price = 0.5M, Promotion = new BuyOneGetOneFree()},
             new ItemPrice { Name = "Banana", Price = 2.45M},
         },
         ScannedItems = new List<ScannedItem>
         {
             new ScannedItem() { Name="Apple" },
             new ScannedItem() { Name="Apple" },
             new ScannedItem() { Name="Banana" }
         }
     };
     var receiptPrinter = new ReceiptPrinter(receipt);
     Assert.AreEqual("Apple x2\t$0.50\r\nBanana x1\t$2.45\r\nTotal: $2.95", receiptPrinter.Print());
 }
        /// <summary>
        /// Creates a concrete Receipt based upon requested type
        /// </summary>
        /// <param name="type">The type of the Receipt to create</param>
        /// <returns>The concrete Receipt</returns>
        public static IReceipt CreateReceipt(Receipt type)
        {
            IReceipt receipt;
            switch (type)
            {
                case Receipt.Text:
                    receipt = new TextReceipt();
                    break;

                case Receipt.Html:
                    receipt = new HtmlReceipt();
                    break;

                default:
                    receipt = null;
                    break;
            }
            return receipt;
        }
        public bool LineItemIsConfirmed(Receipt receipt, Guid lineItemId, out decimal unconfirmedAmnt)
        {
            using (StructureMap.IContainer c =NestedContainer)
            {
                IReceiptRepository _receiptService = Using<IReceiptRepository>(c);
                bool isConfirmed = false;
                unconfirmedAmnt = 0m;
                var paymentDocLineItem = receipt.LineItems.FirstOrDefault(n => n.Id == lineItemId);

                if (paymentDocLineItem.LineItemType == OrderLineItemType.PostConfirmation)
                {
                    return true;
                }

                var invoiceReceipts = _receiptService.GetByInvoiceId(receipt.InvoiceId);
                if (invoiceReceipts.Count > 0)
                {
                    var paymentDoc =
                        invoiceReceipts.FirstOrDefault(
                            n => n.PaymentDocId == Guid.Empty && n.LineItems.Any(l => l.Id == lineItemId));
                    if (paymentDoc != null)
                    {
                        var childLineItems =
                            invoiceReceipts.Where(n => n.Id != paymentDoc.Id)
                                           .SelectMany(n => n.LineItems.Where(l => l.PaymentDocLineItemId == lineItemId));
                        decimal totalConfirmed = childLineItems.Sum(n => n.Value);

                        unconfirmedAmnt = paymentDocLineItem.Value - totalConfirmed;
                        if (unconfirmedAmnt < 0)
                            unconfirmedAmnt = 0;

                        if (totalConfirmed >= paymentDocLineItem.Value)
                        {
                            isConfirmed = true;
                        }
                    }
                }

                return isConfirmed;
            }
            
        }
 public void editReceipt(Receipt newReceipt, int receiptNumber)
 {
     receiptList.RemoveAt(receiptNumber - 1);
     receiptList.Insert(receiptNumber - 1, newReceipt);
     Receipt receipt = (Receipt)receiptList[receiptNumber - 1];
     Console.WriteLine("Receipt {0}{1} has been edited.  The following are the new totals for Receipt {0}{1}:", receipt.returnReceiptName(), receipt.returnReceiptNumber());
     Console.WriteLine("\nReceipt {0}{1}:", receipt.returnReceiptName(), receipt.returnReceiptNumber());
     Console.WriteLine("--------------");
     Console.WriteLine("Communal Total = {0}", receipt.returnCommunalTotal());
     Console.WriteLine("Communal Total Per Person = {0}", receipt.returnCommunalTotal() / 3);
     if (receipt.returnATotal() != 0) {
         Console.WriteLine("Additional Amount Owed By Andy = {0}", receipt.returnATotal());
     }
     if (receipt.returnVTotal() != 0) {
         Console.WriteLine("Additional Amount Owed By Vince = {0}", receipt.returnVTotal());
     }
     if (receipt.returnMTotal() != 0) {
         Console.WriteLine("Additional Amount Owed By Mike = {0}", receipt.returnMTotal());
     }
 }
Beispiel #27
0
        public Document CreateDocument(Guid id, DocumentType documentType, CostCentre documentIssuerCC, CostCentre documentRecipientCC, User documentIssuerUser, string DocumentReference, double? longitude=null, double? latitude=null)
        {
            Document doc = null;
            switch (documentType)
            {
                case DocumentType.Order:
                    doc = new Order(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, /*null, */documentIssuerUser, DocumentReference, longitude, latitude);
                    break;
                case DocumentType.DispatchNote://
                    doc = new DispatchNote(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, /*null, */documentIssuerUser, DocumentReference, longitude, latitude);
                    break;
                
                case DocumentType.Receipt:
                    doc = new Receipt(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, documentIssuerUser, DocumentReference, longitude, latitude);
                    break;
                case DocumentType.DisbursementNote:
                    doc = new DisbursementNote(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, documentIssuerUser, DocumentReference, longitude, latitude);
                    break;
                case DocumentType.CreditNote:
                    doc = new CreditNote(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, documentIssuerUser, DocumentReference, longitude, latitude);
                    break;
                case DocumentType.ReturnsNote:
                  
                    doc = new ReturnsNote(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, documentIssuerUser, DocumentReference, longitude, latitude);
                    break;
                case DocumentType.PaymentNote:
                    doc = new PaymentNote(id);
                    doc = Map(doc, documentType, documentIssuerCC, documentRecipientCC, documentIssuerUser, DocumentReference, longitude, latitude);
                    break;


            }

            return doc;
        }
Beispiel #28
0
 public Task <Receipt> UpdateAsync(Receipt item)
 {
     return(Receipts.UpdateAsync(item));
 }
Beispiel #29
0
 public Task <Receipt> CreateAsync(Receipt item)
 {
     return(Receipts.CreateAsync(item));
 }
        private void orederReceiptToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var edt = new Receipt(Convert.ToInt32(dataGridViewOrders.SelectedRows[0].Cells[0].Value));

            edt.ShowDialog();
        }
Beispiel #31
0
        /// <summary>
        /// Execute the task.
        /// </summary>
        /// <param name="Job">Information about the current job</param>
        /// <param name="BuildProducts">Set of build products produced by this node.</param>
        /// <param name="TagNameToFileSet">Mapping from tag names to the set of files they include</param>
        /// <returns>True if the task succeeded</returns>
        public override bool Execute(JobContext Job, HashSet <FileReference> BuildProducts, Dictionary <string, HashSet <FileReference> > TagNameToFileSet)
        {
            // Get the project path, and check it exists
            FileReference ProjectFile = null;

            if (Parameters.Project != null)
            {
                ProjectFile = ResolveFile(Parameters.Project);
                if (!FileReference.Exists(ProjectFile))
                {
                    CommandUtils.LogError("Couldn't find project '{0}'", ProjectFile.FullName);
                    return(false);
                }
            }

            // Get the directories used for staging this project
            DirectoryReference SourceEngineDir  = CommandUtils.EngineDirectory;
            DirectoryReference SourceProjectDir = (ProjectFile == null)? SourceEngineDir : ProjectFile.Directory;

            // Get the output directories. We flatten the directory structure on output.
            DirectoryReference TargetDir        = ResolveDirectory(Parameters.ToDir);
            DirectoryReference TargetEngineDir  = DirectoryReference.Combine(TargetDir, "Engine");
            DirectoryReference TargetProjectDir = DirectoryReference.Combine(TargetDir, ProjectFile.GetFileNameWithoutExtension());

            // Get the path to the receipt
            string ReceiptFileName = TargetReceipt.GetDefaultPath(SourceProjectDir.FullName, Parameters.Target, Parameters.Platform, Parameters.Configuration, Parameters.Architecture);

            // Try to load it
            TargetReceipt Receipt;

            if (!TargetReceipt.TryRead(ReceiptFileName, out Receipt))
            {
                CommandUtils.LogError("Couldn't read receipt '{0}'", ReceiptFileName);
                return(false);
            }

            // Expand all the paths from the receipt
            Receipt.ExpandPathVariables(SourceEngineDir, SourceProjectDir);

            // Stage all the build products needed at runtime
            HashSet <FileReference> SourceFiles = new HashSet <FileReference>();

            foreach (BuildProduct BuildProduct in Receipt.BuildProducts.Where(x => x.Type != BuildProductType.StaticLibrary && x.Type != BuildProductType.ImportLibrary))
            {
                SourceFiles.Add(new FileReference(BuildProduct.Path));
            }
            foreach (RuntimeDependency RuntimeDependency in Receipt.RuntimeDependencies.Where(x => x.Type != StagedFileType.UFS))
            {
                SourceFiles.UnionWith(CommandUtils.ResolveFilespec(CommandUtils.RootDirectory, RuntimeDependency.Path, new string[] { ".../*.umap", ".../*.uasset" }));
            }

            // Get all the target files
            List <FileReference> TargetFiles = new List <FileReference>();

            foreach (FileReference SourceFile in SourceFiles)
            {
                // Get the destination file to copy to, mapping to the new engine and project directories as appropriate
                FileReference TargetFile;
                if (SourceFile.IsUnderDirectory(SourceEngineDir))
                {
                    TargetFile = FileReference.Combine(TargetEngineDir, SourceFile.MakeRelativeTo(SourceEngineDir));
                }
                else
                {
                    TargetFile = FileReference.Combine(TargetProjectDir, SourceFile.MakeRelativeTo(SourceProjectDir));
                }

                // Fixup the case of the output file. Would expect Platform.DeployLowerCaseFilenames() to return true here, but seems not to be the case.
                if (Parameters.Platform == UnrealTargetPlatform.PS4)
                {
                    TargetFile = FileReference.Combine(TargetDir, TargetFile.MakeRelativeTo(TargetDir).ToLowerInvariant());
                }

                // Only copy the output file if it doesn't already exist. We can stage multiple targets to the same output directory.
                if (Parameters.Overwrite || !FileReference.Exists(TargetFile))
                {
                    DirectoryReference.CreateDirectory(TargetFile.Directory);
                    CommandUtils.CopyFile(SourceFile.FullName, TargetFile.FullName);
                }

                // Add it to the list of target files
                TargetFiles.Add(TargetFile);
            }

            // Apply the optional tag to the build products
            foreach (string TagName in FindTagNamesFromList(Parameters.Tag))
            {
                FindOrAddTagSet(TagNameToFileSet, TagName).UnionWith(TargetFiles);
            }

            // Add the target file to the list of build products
            BuildProducts.UnionWith(TargetFiles);
            return(true);
        }
        public async Task <JsonResult> ReceiveReceipt(Receipt1 receipts)
        {
            var bcg     = new BarCodeGenerator();
            var account = await BetDatabase.Accounts.SingleOrDefaultAsync(x => x.UserId == User.Identity.Name);

            var branchId = Convert.ToInt32(account.AdminE);
            var branch   = await BetDatabase.Branches.SingleOrDefaultAsync(x => x.BranchId == branchId);

            var receiptid = bcg.GenerateRandomString(16);
            var receipt   = new Receipt
            {
                UserId        = User.Identity.Name,
                BranchId      = Convert.ToInt16(account.AdminE),
                ReceiptStatus = 0,
                SetNo         = 2014927,
                // ReceiptId = Convert.ToInt32(receiptid)
            }; //Start New Reciept

            var    betStake = receipts.TotalStake.ToString(CultureInfo.InvariantCulture);
            string response;

            BetDatabase.Receipts.Add(receipt);
            await BetDatabase.SaveChangesAsync();

            var         ttodd        = receipts.TotalOdd;
            const float bettingLimit = 8000000;
            var         cost         = Convert.ToDouble(betStake);

            if ((cost >= 1000) && (cost <= bettingLimit))//betting limit
            {
                foreach (var betData in receipts.BetData)
                {
                    try
                    {
                        var      tempMatchId = Convert.ToInt32(betData.MatchId);
                        var      matchid     = BetDatabase.ShortMatchCodes.Single(x => x.ShortCode == tempMatchId).MatchNo;
                        Match    match       = BetDatabase.Matches.Single(h => h.BetServiceMatchNo == matchid);
                        DateTime _matchTime  = match.StartTime;
                        DateTime timenow     = DateTime.Now;
                        if (_matchTime < timenow)
                        {
                            response = ("The Match " + tempMatchId + " Has Started");
                            return(new JsonResult {
                                Data = new { message = response }
                            });
                        }
                        var bm = new Bet
                        {
                            BetOptionId = Int32.Parse(betData.OptionId),
                            RecieptId   = receipt.ReceiptId,
                            MatchId     = BetDatabase.ShortMatchCodes.Single(x => x.ShortCode == tempMatchId).MatchNo,
                            BetOdd      = Convert.ToDecimal(betData.Odd),
                        };
                        BetDatabase.Bets.Add(bm);
                        BetDatabase.SaveChanges();
                    }
                    catch (Exception er)
                    {
                        response = (" An error  has occured:" + er.Message);
                        return(new JsonResult {
                            Data = new { message = response }
                        });

                        var msg = er.Message;
                    }
                }
                // Requires Quick Attention

                receipt.TotalOdds     = Convert.ToDouble(ttodd);
                receipt.ReceiptStatus = 1;
                receipt.SetSize       = receipts.ReceiptSize;
                receipt.Stake         = cost;
                receipt.WonSize       = 0;
                receipt.SubmitedSize  = 0;
                receipt.ReceiptDate   = DateTime.Now;
                receipt.Serial        = Int2Guid(receiptid);
                account.DateE         = DateTime.Now;
                // receipt.RecieptID = 34;
                BetDatabase.Entry(receipt).State = EntityState.Modified;
                var statement = new Statement
                {
                    Account        = receipt.UserId,
                    Amount         = receipt.Stake,
                    Controller     = receipt.UserId,
                    StatetmentDate = DateTime.Now,
                    BalBefore      = account.AmountE,
                    BalAfter       = account.AmountE + receipt.Stake,
                    Comment        = "Bet Transaction for Ticket No" + receiptid
                };
                account.AmountE       = account.AmountE + receipt.Stake;
                statement.Transcation = "Teller Bet";
                statement.Method      = "Online";
                statement.Serial      = receiptid;

                branch.Balance = branch.Balance + Convert.ToDecimal(receipt.Stake);
                BetDatabase.Entry(branch).State = EntityState.Modified;
                BetDatabase.Accounts.AddOrUpdate(account);
                BetDatabase.Statements.Add(statement);
                BetDatabase.SaveChanges();
                var barcodeImage = bcg.CreateBarCode(receiptid);
                var tempPath     = Server.MapPath("~/Content/BarCodes/" + receiptid.Trim() + ".png");
                try
                {
                    barcodeImage.Save(tempPath, ImageFormat.Png);
                }
                catch (Exception)
                {
                }
                response = ("Success");
            }
            else if (cost < 1000)
            {
                receipt.ReceiptId = 0;
                response          = ("Minimum betting stake is UGX 1000. Please enter amount more than UGX 1000.");
            }
            else
            {
                receipt.ReceiptId = 0;
                response          = ("Maximum stake is UGX " + bettingLimit + ". Please enter amount less than UGX " + bettingLimit + ".");
            }

            return(new JsonResult {
                Data = new { message = response, ReceiptNumber = receipt.ReceiptId, ReceiptTime = String.Format("{0:dd/MM/yyyy}", DateTime.Now) + " - " + toJavaScriptDate(DateTime.Now), TellerName = account.UserId, BranchName = branch.BranchName, Balance = account.AmountE, Serial = receiptid, FormatedSerial = GetSerialNumber(receiptid) }
            });
        }
Beispiel #33
0
 private static void AppendTotal(Receipt receipt, StringBuilder sb)
 {
     sb.AppendLine("-----------------------");
     sb.AppendLine($"Total {DecimalToString(receipt.Total)}");
 }
Beispiel #34
0
    public override void GetFilesToDeployOrStage(ProjectParams Params, DeploymentContext SC)
    {
        // Engine non-ufs (binaries)

        if (SC.bStageCrashReporter)
        {
            StageExecutable("exe", SC, CommandUtils.CombinePaths(SC.LocalRoot, "Engine/Binaries", SC.PlatformDir), "CrashReportClient.");
        }

        // Stage all the build products
        foreach (BuildReceipt Receipt in SC.StageTargetReceipts)
        {
            SC.StageBuildProductsFromReceipt(Receipt);
        }

        // Copy the splash screen, windows specific
        SC.StageFiles(StagedFileType.NonUFS, CombinePaths(SC.ProjectRoot, "Content/Splash"), "Splash.bmp", false, null, null, true);


        /*foreach (string StageExePath in GetExecutableNames(SC))
         * {
         *  // set the icon on the original exe this will be used in the task bar when the bootstrap exe runs
         *  if (InternalUtils.SafeFileExists(CombinePaths(SC.ProjectRoot, "Build/Windows/Application.ico")))
         *  {
         *      GroupIconResource GroupIcon = null;
         *      GroupIcon = GroupIconResource.FromIco(CombinePaths(SC.ProjectRoot, "Build/Windows/Application.ico"));
         *
         *      // Update the icon on the original exe because this will be used when the game is running in the task bar
         *      using (ModuleResourceUpdate Update = new ModuleResourceUpdate(StageExePath, false))
         *      {
         *          const int IconResourceId = 101;
         *          if (GroupIcon != null)
         *          {
         *              Update.SetIcons(IconResourceId, GroupIcon);
         *          }
         *      }
         *  }
         * }*/

        // Stage the bootstrap executable
        if (!Params.NoBootstrapExe)
        {
            foreach (BuildReceipt Receipt in SC.StageTargetReceipts)
            {
                BuildProduct Executable = Receipt.BuildProducts.FirstOrDefault(x => x.Type == BuildProductType.Executable);
                if (Executable != null)
                {
                    // only create bootstraps for executables
                    if (SC.NonUFSStagingFiles.ContainsKey(Executable.Path) && Path.GetExtension(Executable.Path) == ".exe")
                    {
                        string BootstrapArguments = "";
                        if (!SC.IsCodeBasedProject && !ShouldStageCommandLine(Params, SC))
                        {
                            BootstrapArguments = String.Format("..\\..\\..\\{0}\\{0}.uproject", SC.ShortProjectName);
                        }

                        string BootstrapExeName;
                        if (SC.StageTargetConfigurations.Count > 1)
                        {
                            BootstrapExeName = Path.GetFileName(Executable.Path);
                        }
                        else if (Params.IsCodeBasedProject)
                        {
                            BootstrapExeName = Receipt.GetProperty("TargetName", SC.ShortProjectName) + ".exe";
                        }
                        else
                        {
                            BootstrapExeName = SC.ShortProjectName + ".exe";
                        }

                        StageBootstrapExecutable(SC, BootstrapExeName, Executable.Path, SC.NonUFSStagingFiles[Executable.Path], BootstrapArguments);
                    }
                }
            }
        }
    }
Beispiel #35
0
        public static void Main(string[] args)
        {
            /******************* REQUEST VARIABLES*******************************/

            string host      = "esplusqa.moneris.com";
            string store_id  = "monusqa002";
            string api_token = "qatoken";

            /****************** TRANSACTION VARIABLES *****************************/

            string order_id;                    //will prompt user for input
            string amount              = "5.00";
            string enc_track2          = "";
            string device_type         = "idtech";
            string crypt               = "7";
            string commcard_invoice    = "INVC090";
            string commcard_tax_amount = "1.00";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();


            /************************* Recur Variables **********************************/

            string recur_unit   = "month";
            string start_now    = "true";
            string start_date   = "2013/12/01";
            string num_recurs   = "12";
            string period       = "1";
            string recur_amount = "30.00";

            /************************* Recur Object Option1 ******************************/

            Recur recurring_cycle = new Recur(recur_unit, start_now, start_date,
                                              num_recurs, period, recur_amount);

            USEncPurchase P = new USEncPurchase(order_id,
                                                amount,
                                                enc_track2,
                                                device_type,
                                                crypt,
                                                commcard_invoice,
                                                commcard_tax_amount);

            P.SetRecur(recurring_cycle);



            HttpsPostRequest mpgReq =
                new HttpsPostRequest(host, store_id, api_token, P);


            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("ISO = " + receipt.GetISO());
                Console.WriteLine("BankTotals = " + receipt.GetBankTotals());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("Ticket = " + receipt.GetTicket());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                Console.WriteLine("Recur Success = " + receipt.GetRecurSuccess());
                Console.WriteLine("CardLevelResult = " + receipt.GetCardLevelResult());
                Console.WriteLine("MaskedPan = " + receipt.GetMaskedPan());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public IActionResult GetHistory(string walletName, string address)
        {
            if (string.IsNullOrWhiteSpace(walletName))
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No wallet name", "No wallet name provided"));
            }

            if (string.IsNullOrWhiteSpace(address))
            {
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "No address", "No address provided"));
            }

            try
            {
                var transactionItems = new List <ContractTransactionItem>();

                HdAccount account = this.walletManager.GetAccounts(walletName).First();

                // Get a list of all the transactions found in an account (or in a wallet if no account is specified), with the addresses associated with them.
                IEnumerable <AccountHistory> accountsHistory = this.walletManager.GetHistory(walletName, account.Name);

                // Wallet manager returns only 1 when an account name is specified.
                AccountHistory accountHistory = accountsHistory.First();

                List <FlatHistory> items = accountHistory.History.Where(x => x.Address.Address == address).ToList();

                // Represents a sublist of transactions associated with receive addresses + a sublist of already spent transactions associated with change addresses.
                // In effect, we filter out 'change' transactions that are not spent, as we don't want to show these in the history.
                List <FlatHistory> history = items.Where(t => !t.Address.IsChangeAddress() || (t.Address.IsChangeAddress() && t.Transaction.IsSpent())).ToList();

                // TransactionData in history is confusingly named. A "TransactionData" actually represents an input, and the outputs that spend it are "SpendingDetails".
                // There can be multiple "TransactionData" which have the same "SpendingDetails".
                // For SCs we need to group spending details by their transaction ID, to get all the inputs related to the same outputs.
                // Each group represents 1 SC transaction.
                // Each item.Transaction in a group is an input.
                // Each item.Transaction.SpendingDetails in the group represent the outputs, and they should all be the same so we can pick any one.
                var scTransactions = history
                                     .Where(item => item.Transaction.SpendingDetails != null)
                                     .Where(item => item.Transaction.SpendingDetails.Payments.Any(x => x.DestinationScriptPubKey.IsSmartContractExec()))
                                     .GroupBy(item => item.Transaction.SpendingDetails.TransactionId)
                                     .Select(g => new
                {
                    TransactionId = g.Key,
                    InputAmount   = g.Sum(i => i.Transaction.Amount),                 // Sum the inputs to the SC transaction.
                    Outputs       = g.First().Transaction.SpendingDetails.Payments,   // Each item in the group will have the same outputs.
                    OutputAmount  = g.First().Transaction.SpendingDetails.Payments.Sum(o => o.Amount),
                    BlockHeight   = g.First().Transaction.SpendingDetails.BlockHeight // Each item in the group will have the same block height.
                })
                                     .ToList();

                foreach (var scTransaction in scTransactions)
                {
                    // Consensus rules state that each transaction can have only one smart contract exec output, so FirstOrDefault is correct.
                    PaymentDetails scPayment = scTransaction.Outputs?.FirstOrDefault(x => x.DestinationScriptPubKey.IsSmartContractExec());

                    if (scPayment == null)
                    {
                        continue;
                    }

                    Receipt receipt = this.receiptRepository.Retrieve(scTransaction.TransactionId);

                    Result <ContractTxData> txDataResult = this.callDataSerializer.Deserialize(scPayment.DestinationScriptPubKey.ToBytes());

                    if (txDataResult.IsFailure)
                    {
                        continue;
                    }

                    ContractTxData txData = txDataResult.Value;

                    // If the receipt is not available yet, we don't know how much gas was consumed so use the full gas budget.
                    ulong gasFee = receipt != null
                        ? receipt.GasUsed * receipt.GasPrice
                        : txData.GasCostBudget;

                    long  totalFees      = scTransaction.InputAmount - scTransaction.OutputAmount;
                    Money transactionFee = Money.FromUnit(totalFees, MoneyUnit.Satoshi) - Money.FromUnit(txData.GasCostBudget, MoneyUnit.Satoshi);

                    var result = new ContractTransactionItem
                    {
                        Amount         = scPayment.Amount.ToUnit(MoneyUnit.Satoshi),
                        BlockHeight    = scTransaction.BlockHeight,
                        Hash           = scTransaction.TransactionId,
                        TransactionFee = transactionFee.ToUnit(MoneyUnit.Satoshi),
                        GasFee         = gasFee
                    };

                    if (scPayment.DestinationScriptPubKey.IsSmartContractCreate())
                    {
                        result.Type = ContractTransactionItemType.ContractCreate;
                        result.To   = receipt?.NewContractAddress?.ToBase58Address(this.network) ?? string.Empty;
                    }
                    else if (scPayment.DestinationScriptPubKey.IsSmartContractCall())
                    {
                        result.Type = ContractTransactionItemType.ContractCall;
                        result.To   = txData.ContractAddress.ToBase58Address(this.network);
                    }

                    transactionItems.Add(result);
                }

                return(this.Json(transactionItems.OrderByDescending(x => x.BlockHeight ?? Int32.MaxValue)));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
Beispiel #37
0
 public Receipt Create(Receipt item)
 {
     return(Receipts.Create(item));
 }
 public void ToggleSelect(Receipt receipt)
 {
     receipt.IsSelected = !receipt.IsSelected;
 }
Beispiel #39
0
        public static void Main(string[] args)
        {
            /******************* REQUEST VARIABLES*******************************/

            string host      = "esplusqa.moneris.com";
            string store_id  = "monusqa138";
            string api_token = "qatoken";

            /****************** TRANSACTION VARIABLES *****************************/

            string order_id;                    //will prompt user for input
            string cust_id             = "B_Urlac_54";
            string amount              = "1.00";
            string pan                 = "4005554444444403";
            string expdate             = "0812";
            string cavv                = "AAABBJg0VhI0VniQEjRWAAAAAAA";
            string commcard_invoice    = "COINV982";
            string commcard_tax_amount = "1.00";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();

            /************************ Transaction Object Option1 *************************/

            USCavvPurchase cavvPurchase = new USCavvPurchase(order_id,
                                                             cust_id,
                                                             amount,
                                                             pan,
                                                             expdate,
                                                             cavv,
                                                             commcard_invoice,
                                                             commcard_tax_amount);

            /************************ Transaction Object Option2 *************************/

            Hashtable cavvParams = new Hashtable();     //transaction hashtable option

            cavvParams.Add("order_id", order_id);
            cavvParams.Add("cust_id", cust_id);
            cavvParams.Add("amount", amount);
            cavvParams.Add("pan", pan);
            cavvParams.Add("expdate", expdate);
            cavvParams.Add("cavv", cavv);
            cavvParams.Add("commcard_invoice", commcard_invoice);
            cavvParams.Add("commcard_tax_amount", commcard_tax_amount);

            USCavvPurchase cavvPurchase2 = new USCavvPurchase(cavvParams);     //single paramater hashtable construtor

            /*************** Address Verification Service **********************/

            AvsInfo avsCheck = new AvsInfo();

            avsCheck.SetAvsStreetNumber("212");
            avsCheck.SetAvsStreetName("Payton Street");
            avsCheck.SetAvsZipCode("M1M1M1");

            cavvPurchase.SetAvsInfo(avsCheck);

            /****************** Card Validation Digits *************************/

            CvdInfo cvdCheck = new CvdInfo();

            cvdCheck.SetCvdIndicator("1");
            cvdCheck.SetCvdValue("099");

            cavvPurchase.SetCvdInfo(cvdCheck);

            /****************** Convenience Fee ********************************/

            ConvFeeInfo convFeeInfo = new ConvFeeInfo();

            convFeeInfo.SetConvenienceFee("1.00");
            cavvPurchase.SetConvFeeInfo(convFeeInfo);

            /*************************** Https Post Request *****************************/

            HttpsPostRequest mpgReq =
                new HttpsPostRequest(host, store_id, api_token, cavvPurchase);

            /****************************** Receipt *************************************/

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("BankTotals = " + receipt.GetBankTotals());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("Ticket = " + receipt.GetTicket());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                Console.WriteLine("Avs Response = " + receipt.GetAvsResultCode());
                Console.WriteLine("Cvd Response = " + receipt.GetCvdResultCode());
                Console.WriteLine("CfSuccess = " + receipt.GetCfSuccess());
                Console.WriteLine("CfStatus = " + receipt.GetCfStatus());
                Console.WriteLine("FeeAmount = " + receipt.GetFeeAmount());
                Console.WriteLine("FeeRate = " + receipt.GetFeeRate());
                Console.WriteLine("FeeType = " + receipt.GetFeeType());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #40
0
        public static void Main(string[] args)
        {
            /******************* REQUEST VARIABLES*******************************/

            string host      = "esqa.moneris.com";
            string store_id  = "moneris";
            string api_token = "hurgle";

            /****************** TRANSACTION VARIABLES *****************************/

            string order_id;                    //will prompt user for input
            string service_type = "session";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();

            AttributeQuery aq = new AttributeQuery(order_id, service_type);

            aq.setDeviceId("");
            aq.setAccountLogin("13195417-8CA0-46cd-960D-14C158E4DBB2");
            aq.setPasswordHash("489c830f10f7c601d30599a0deaf66e64d2aa50a");
            aq.setAccountNumber("3E17A905-AC8A-4c8d-A417-3DADA2A55220");
            aq.setAccountName("4590FCC0-DF4A-44d9-A57B-AF9DE98B84DD");
            aq.setAccountEmail("*****@*****.**");
            //aq.setCCNumberHash("4242424242424242");
            //aq.setIPAddress("192.168.0.1");
            //aq.setIPForwarded("192.168.1.0");
            aq.setAccountAddressStreet1("3300 Bloor St W");
            aq.setAccountAddressStreet2("4th Flr West Tower");
            aq.setAccountAddressCity("Toronto");
            aq.setAccountAddressState("Ontario");
            aq.setAccountAddressCountry("Canada");
            aq.setAccountAddressZip("M8X2X2");
            aq.setShippingAddressStreet1("3300 Bloor St W");
            aq.setShippingAddressStreet2("4th Flr West Tower");
            aq.setShippingAddressCity("Toronto");
            aq.setShippingAddressState("Ontario");
            aq.setShippingAddressCountry("Canada");
            aq.setShippingAddressZip("M8X2X2");


            HttpsPostRequest mpgReq =
                new HttpsPostRequest(host, store_id, api_token, aq);

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Hashtable results = new Hashtable();
                string[]  rules;

                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());

                results = receipt.GetResult();

                //Iterate through the response
                IDictionaryEnumerator r = results.GetEnumerator();
                while (r.MoveNext())
                {
                    Console.WriteLine(r.Key.ToString() + " = " + r.Value.ToString());
                }


                //Iterate through the rules that were fired
                rules = receipt.GetRules();

                for (int i = 0; i < rules.Length; i++)
                {
                    Console.WriteLine("RuleName = " + rules[i]);
                    Console.WriteLine("RuleCode = " + receipt.GetRuleCode(rules[i]));
                    Console.WriteLine("RuleMessageEn = " + receipt.GetRuleMessageEn(rules[i]));
                    Console.WriteLine("RuleMessageFr = " + receipt.GetRuleMessageFr(rules[i]));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #41
0
        private StandardModel HandleCommercePrint(dynamic arg)
        {
            int       soId = 0;
            var       id   = (string)arg.so_id;
            SaleOrder so   = null;

            if (int.TryParse(id, out soId))
            {
                so = this.SiteDatabase.GetById <SaleOrder>(soId);
            }
            else
            {
                so = this.SiteDatabase.Query <SaleOrder>()
                     .Where(row => row.SaleOrderIdentifier == id)
                     .FirstOrDefault();
            }

            if (so == null)
            {
                return(new StandardModel(404));;
            }

            var receipts = this.SiteDatabase.Query <Receipt>()
                           .Where(r => r.SaleOrderId == so.Id)
                           .ToList();

            Receipt receipt;

            if (this.Request.Query.index == null && receipts.Count == 1)
            {
                receipt = receipts.FirstOrDefault();
            }
            else if (this.Request.Query.index == null && receipts.Count > 1)
            {
                receipt = new Receipt()
                {
                    Identifier = "Specify Index"
                };
            }
            else
            {
                receipt = receipts
                          .Skip(this.Request.Query.index == null ? 0 : (int)this.Request.Query.index)
                          .FirstOrDefault();
            }

            if (receipt == null)
            {
                receipt = new Receipt()
                {
                    Identifier = so.ReceiptIdentifier
                };
            }

            var paymentlogs = this.SiteDatabase.Query <PaymentLog>()
                              .Where(p => p.SaleOrderIdentifier == so.SaleOrderIdentifier && p.IsErrorCode == false)
                              .OrderBy(log => log.PaymentDate)
                              .ToList();

            var totalPaid = paymentlogs.Sum(log => log.Amount);

            var paymentDetail = new
            {
                TransactionLog      = paymentlogs,
                PaymentRemaining    = so.TotalAmount - totalPaid,
                TotalPaid           = totalPaid,
                SplitedPaymentIndex = this.Request.Query.index == null ? -1 : (int)this.Request.Query.index
            };

            var dummyPage = new Page()
            {
                Title        = arg.form + " for " + so.SaleOrderIdentifier,
                ContentParts = JObject.FromObject(new
                {
                    Type = (string)arg.form
                })
            };

            return(new StandardModel(this, dummyPage, new { SaleOrder = so, PaymentDetail = paymentDetail, Receipt = receipt }));
        }
        public static void Main(string[] args)
        {
            string store_id  = "store5";
            string api_token = "yesguy";
            string order_id  = "Test" + DateTime.Now.ToString("yyyyMMddhhmmss");
            string amount    = "5.00";
            string pan       = "4242424242424242";
            string expdate   = "0412";
            string crypt     = "7";
            string processing_country_code = "CA";
            bool   status_check            = false;

            CofInfo cof = new CofInfo();

            cof.SetPaymentIndicator("U");
            cof.SetPaymentInformation("2");
            cof.SetIssuerId("168451306048014");

            MCPPreAuth mcpPreauth = new MCPPreAuth();

            mcpPreauth.SetOrderId(order_id);
            mcpPreauth.SetAmount(amount);
            mcpPreauth.SetPan(pan);
            mcpPreauth.SetExpDate(expdate);
            mcpPreauth.SetCryptType(crypt);
            //mcpPreauth.SetWalletIndicator(""); //Refer to documentation for details
            mcpPreauth.SetCofInfo(cof);

            //MCP Fields
            mcpPreauth.SetMCPVersion("1.0");
            mcpPreauth.SetCardholderAmount("500");
            mcpPreauth.SetCardholderCurrencyCode("840");
            //mcpPreauth.SetMCPRateToken("P1538681661706745");
            //mcpPreauth.SetCmId("8nAK8712sGaAkls56"); //set only for usage with Offlinx - Unique max 50 alphanumeric characters transaction id generated by merchant

            HttpsPostRequest mpgReq = new HttpsPostRequest();

            mpgReq.SetProcCountryCode(processing_country_code);
            mpgReq.SetTestMode(true); //false or comment out this line for production transactions
            mpgReq.SetStoreId(store_id);
            mpgReq.SetApiToken(api_token);
            mpgReq.SetTransaction(mcpPreauth);
            mpgReq.SetStatusCheck(status_check);
            mpgReq.Send();

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("ISO = " + receipt.GetISO());
                Console.WriteLine("BankTotals = " + receipt.GetBankTotals());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("Ticket = " + receipt.GetTicket());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                Console.WriteLine("IsVisaDebit = " + receipt.GetIsVisaDebit());
                //Console.WriteLine("StatusCode = " + receipt.GetStatusCode());
                //Console.WriteLine("StatusMessage = " + receipt.GetStatusMessage());
                Console.WriteLine("IssuerId = " + receipt.GetIssuerId());

                Console.WriteLine("MerchantSettlementAmount = " + receipt.GetMerchantSettlementAmount());
                Console.WriteLine("CardholderAmount = " + receipt.GetCardholderAmount());
                Console.WriteLine("CardholderCurrencyCode = " + receipt.GetCardholderCurrencyCode());
                Console.WriteLine("MCPRate = " + receipt.GetMCPRate());
                Console.WriteLine("MCPErrorStatusCode = " + receipt.GetMCPErrorStatusCode());
                Console.WriteLine("MCPErrorMessage = " + receipt.GetMCPErrorMessage());
                Console.WriteLine("HostId = " + receipt.GetHostId());
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #43
0
        public static void Main(string[] args)
        {
            string host      = "esplusqa.moneris.com";
            string store_id  = "monusqa002";
            string api_token = "qatoken";

            string data_key   = "E02MUD0Ao1z9154l5fh6309";
            string order_id   = "res_preauth_2";
            string amount     = "1.00";
            string cust_id    = "customer1"; //if sent will be submitted, otherwise cust_id from profile will be used
            string crypt_type = "1";

            USResPreauthCC usResPreauthCC = new USResPreauthCC(data_key, order_id, cust_id, amount, crypt_type);

            //usResPreauthCC.SetExpdate("1601"); //must be YYMM format

            //CustInfo Variables
            CustInfo custInfo = new CustInfo();

            custInfo.SetEmail("*****@*****.**");
            custInfo.SetInstructions("Make it fast!");


            Hashtable b = new Hashtable();

            b.Add("first_name", "Bob");
            b.Add("last_name", "Smith");
            b.Add("company_name", "Widget Company Inc.");
            b.Add("address", "111 Bolts Ave.");
            b.Add("city", "Toronto");
            b.Add("province", "Ontario");
            b.Add("postal_code", "M8T 1T8");
            b.Add("country", "Canada");
            b.Add("phone", "416-555-5555");
            b.Add("fax", "416-555-5555");
            b.Add("tax1", "123.45");          //federal tax
            b.Add("tax2", "12.34");           //prov tax
            b.Add("tax3", "15.45");           //luxury tax
            b.Add("shipping_cost", "456.23"); //shipping cost

            custInfo.SetBilling(b);

            /* OR you can pass the individual args.
             * custInfo.SetBilling(
             *                     "Bob",                  //first name
             *                     "Smith",                //last name
             *                     "Widget Company Inc.",  //company name
             *                     "111 Bolts Ave.",       //address
             *                     "Toronto",              //city
             *                     "Ontario",              //province
             *                     "M8T 1T8",              //postal code
             *                     "Canada",               //country
             *                     "416-555-5555",         //phone
             *                     "416-555-5555",         //fax
             *                     "123.45",               //federal tax
             *                     "12.34",                //prov tax
             *                     "15.45",                //luxury tax
             *                     "456.23"                //shipping cost
             * );
             */

            Hashtable s = new Hashtable();

            s.Add("first_name", "Bob");
            s.Add("last_name", "Smith");
            s.Add("company_name", "Widget Company Inc.");
            s.Add("address", "111 Bolts Ave.");
            s.Add("city", "Toronto");
            s.Add("province", "Ontario");
            s.Add("postal_code", "M8T 1T8");
            s.Add("country", "Canada");
            s.Add("phone", "416-555-5555");
            s.Add("fax", "416-555-5555");
            s.Add("tax1", "123.45");          //federal tax
            s.Add("tax2", "12.34");           //prov tax
            s.Add("tax3", "15.45");           //luxury tax
            s.Add("shipping_cost", "456.23"); //shipping cost

            custInfo.SetShipping(s);

            /* OR you can pass the individual args.
             * custInfo.SetShipping(
             *                     "Bob",                  //first name
             *                     "Smith",                //last name
             *                     "Widget Company Inc.",  //company name
             *                     "111 Bolts Ave.",       //address
             *                     "Toronto",              //city
             *                     "Ontario",              //province
             *                     "M8T 1T8",              //postal code
             *                     "Canada",               //country
             *                     "416-555-5555",         //phone
             *                     "416-555-5555",         //fax
             *                     "123.45",               //federal tax
             *                     "12.34",                //prov tax
             *                     "15.45",                //luxury tax
             *                     "456.23"                //shipping cost
             * );
             */

            Hashtable i1 = new Hashtable();

            i1.Add("name", "item1's name");
            i1.Add("quantity", "5");
            i1.Add("product_code", "item1's product code");
            i1.Add("extended_amount", "1.01");

            custInfo.SetItem(i1);

            /* OR you can pass the individual args.
             * custInfo.SetItem(
             *  "item1's name",         //name
             *  "5",                    //quantity
             *  "item1's product code", //product code
             *  "1.01"                  //extended amount
             * );
             */

            Hashtable i2 = new Hashtable();

            i2.Add("name", "item2's name");
            i2.Add("quantity", "7");
            i2.Add("product_code", "item2's product code");
            i2.Add("extended_amount", "5.01");

            custInfo.SetItem(i2);

            usResPreauthCC.SetCustInfo(custInfo);

            HttpsPostRequest mpgReq = new HttpsPostRequest(host, store_id, api_token, usResPreauthCC);

            /**********************   REQUEST  ************************/

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("DataKey = " + receipt.GetDataKey());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                Console.WriteLine("ResSuccess = " + receipt.GetResSuccess());
                Console.WriteLine("PaymentType = " + receipt.GetPaymentType());

                //ResolveData
                Console.WriteLine("\nCust ID = " + receipt.GetResDataCustId());
                Console.WriteLine("Phone = " + receipt.GetResDataPhone());
                Console.WriteLine("Email = " + receipt.GetResDataEmail());
                Console.WriteLine("Note = " + receipt.GetResDataNote());
                Console.WriteLine("Masked Pan = " + receipt.GetResDataMaskedPan());
                Console.WriteLine("Exp Date = " + receipt.GetResDataExpdate());
                Console.WriteLine("Crypt Type = " + receipt.GetResDataCryptType());
                Console.WriteLine("Avs Street Number = " + receipt.GetResDataAvsStreetNumber());
                Console.WriteLine("Avs Street Name = " + receipt.GetResDataAvsStreetName());
                Console.WriteLine("Avs Zipcode = " + receipt.GetResDataAvsZipcode());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #44
0
        public void TestJoin()
        {
            using (var db = CreateSqlServerCeDB())
            {
                try
                {
                    db.SqlMode = SqlModes.Text;
                    db.BeginTransaction();

                    // Insert a new order
                    Order newOrder = new Order();
                    newOrder.OrderName = "new order";
                    int orderID = Convert.ToInt32(db.Insert <Order>().Entity(newOrder).GetIdentity().Execute());
                    Assert.IsTrue(orderID > 0);

                    // Update order name to use the generated ID autoincremented value
                    newOrder.OrderName = string.Concat(newOrder.OrderName, " ", newOrder.ID);
                    db.Update <Order>(newOrder, o => o.ID == newOrder.ID);

                    // Add an order item associated to the newly added order
                    OrderItem orderItem = new OrderItem {
                        OrderID = newOrder.ID, ItemDescription = "Test item", Price = 5.5m
                    };
                    int orderItemID = Convert.ToInt32(db.Insert <OrderItem>().Entity(orderItem).GetIdentity().Execute());
                    Assert.IsTrue(orderItemID > 0);

                    // Add a receipt associated to the new ordeer / order item
                    Receipt receipt = new Receipt {
                        OrderItemID = orderItem.ID, AmountPaid = 5.5m
                    };
                    db.Insert <Receipt>(receipt);

                    // Query the newly added order with its order item (do not query receipt)
                    var orderWithItem = db.Query <Order>()
                                        .Join <Order, OrderItem>(JoinType.Left, o => o.OrderItems, (o, oi) => o.ID == oi.OrderID)
                                        .Where(o => o.ID == newOrder.ID)
                                        .FirstOrDefault();

                    // Query the newly added order with associated order item and receipt
                    var orderWithItemAndReceipt = db.Query <Order>()
                                                  .Join <Order, OrderItem>(JoinType.Left, o => o.OrderItems, (o, oi) => o.ID == oi.OrderID)
                                                  .Join <OrderItem, Receipt>(JoinType.Left, oi => oi.ItemReceipt, (oi, r) => oi.ID == r.OrderItemID)
                                                  .Where(o => o.ID == newOrder.ID).FirstOrDefault();

                    Assert.IsNotNull(orderWithItem);
                    Assert.IsTrue(orderWithItem.OrderItems.Count == 1);
                    Assert.IsNull(orderWithItem.OrderItems[0].ItemReceipt);

                    Assert.IsNotNull(orderWithItemAndReceipt.OrderItems[0].ItemReceipt);

                    // Delete all added items
                    db.Delete <Order>(o => o.ID == orderID);
                    db.Delete <OrderItem>(oi => oi.ID == orderItemID);
                    db.Delete <Receipt>(r => r.OrderItemID == orderItemID);

                    // Verify items are deleted
                    var receipts = db.Query <Receipt>().Where(r => r.OrderItemID == orderItemID).ToList();
                    Assert.IsTrue(receipts.Count == 0);

                    var orderItems = db.Query <OrderItem>().Where(oi => oi.ID == orderItemID).ToList();
                    Assert.IsTrue(orderItems.Count == 0);

                    var orders = db.Query <Order>().Where(o => o.ID == orderID).ToList();
                    Assert.IsTrue(orders.Count == 0);

                    db.Commit();
                }
                catch
                {
                    db.RollBack();
                    throw;
                }
            }
        }
Beispiel #45
0
 public static Task<Receipt> Add(Employee employee, Receipt receipt)
 {
     receipt.Bill = receipt.Bill.GetManaged();
     receipt.Employee = employee;
     return ReceiptDataAccess.Add(receipt);
 }
 public async Task SaveReceiptAsync(Receipt receipt)
 {
     db.Receipts.Add(receipt);
     await db.SaveChangesAsync();
 }
        /// <summary>
        /// Returns an extra report containing the GRNF.
        /// This function is used for creating the report for the first time as well (Not just export). Which is why we can't
        /// just use the overload with the ReceiptConfirmationPrintoutID as a parameter.
        /// </summary>
        /// <param name="receiptID"></param>
        /// <param name="IDPrinted">Use this if you're trying to get a GRNF printed previously using some ID</param>
        /// <param name="isDocumentBrowser">Use this For Docuement Browser </param>
        /// <returns></returns>
        public static XtraReport CreateGRNFPrintout(int receiptID, int?IDPrinted, bool isDocumentBrowser, FiscalYear fiscalYear)
        {
            ReceiptConfirmationPrintoutStore printout = new ReceiptConfirmationPrintoutStore(CurrentContext.LoggedInUserName);

            BLL.ReceiptConfirmationPrintout rc = new BLL.ReceiptConfirmationPrintout();

            printout.BranchName.Text = GeneralInfo.Current.HospitalName;
            printout.xrGRVLabel.Text = "GRNF No.";
            int printedID;

            BLL.ReceiveDoc rDoc = new ReceiveDoc();
            rDoc.LoadByReceiptID(receiptID);

            var activity = new Activity();

            activity.LoadByPrimaryKey(rDoc.StoreID);
            var supplier = new Supplier();

            supplier.LoadByPrimaryKey(rDoc.SupplierID);

            var       hsup       = new Supplier();
            DataTable homeOffice = hsup.GetHubHeadOffice();


            if (supplier.ID == (int)homeOffice.Rows[0]["SupplierID"] && !Settings.IsCenter)
            {
                printout.ReportType = ReceiptConfirmationPrintoutStore.GRNFReportType.IGRV;
            }
            else if (supplier.ID != (int)homeOffice.Rows[0]["SupplierID"])
            {
                printout.ReportType = ReceiptConfirmationPrintoutStore.GRNFReportType.GRV;
            }
            if (rDoc.RowCount == 0 && isDocumentBrowser)
            {
                rDoc.LoadDeletedByReceiptID(receiptID);
            }
            else if (rDoc.RowCount == 0)
            {
                throw new Exception("This Receipt Doesn't have corresponding Receipt Doc Entries.");
            }

            if (rDoc.ReturnedStock)
            {
                BLL.Institution ru       = new Institution();
                BLL.IssueDoc    issueDoc = new IssueDoc();
                if (!rDoc.IsColumnNull("ReturnedFromIssueDocID"))
                {
                    issueDoc.LoadByPrimaryKey(rDoc.ReturnedFromIssueDocID);
                    ru.LoadByPrimaryKey(issueDoc.ReceivingUnitID);
                }
                else
                {
                    BLL.PO po = new PO();
                    po.LoadByReceiptID(receiptID);
                    ru.LoadByPrimaryKey(Int32.Parse(po.RefNo));
                }

                printout.xrFromFacilityValue.Text = ru.Name;
                printout.ReportType = ReceiptConfirmationPrintoutStore.GRNFReportType.SRM;
            }

            // determine if this is a transfer? account to account or store to store

            Receipt receipt = new Receipt();

            receipt.LoadByPrimaryKey(receiptID);


            printedID = rc.PrepareDataForPrintout(receiptID, CurrentContext.UserId, false, 1, IDPrinted, null, fiscalYear);
            DataTable dataTable = rc.DefaultView.ToTable();

            printout.DataSource            = dataTable;
            printout.xrLabelStoreName.Text = activity.FullActivityName;

            ReceiveDocConfirmation receiveDocConfirmation = new ReceiveDocConfirmation();
            DataTable Users = receiveDocConfirmation.GetUserNamebyReceipt(receiptID);

            if (Users.Rows.Count > 0)
            {
                printout.PreparedBy.Text = Users.Rows[0]["ReceivedBy"].ToString();
                printout.CheckedBy.Text  = Users.Rows[0]["ConfirmedBy"].ToString();
            }

            if (ReceiveDoc.IsThereShortageOrDamage(receiptID))
            {
                ReceiptConfirmationShortagePrintout printoutShortage =
                    new ReceiptConfirmationShortagePrintout();

                rc.PrepareDataForPrintout(receiptID, CurrentContext.UserId, true, 1, printedID, null, fiscalYear);
                printoutShortage.DataSource                     = rc.DefaultView.ToTable();
                printout.xrShortageReport.ReportSource          = printoutShortage;
                printout.PrintingSystem.ContinuousPageNumbering = true;
            }
            else
            {
                printout.ReportFooter.Visible = false;
            }



            CalendarLib.DateTimePickerEx dtDate = new CalendarLib.DateTimePickerEx();
            //dtDate.CustomFormat = "dd/MM/yyyy";
            dtDate.Value       = rDoc.EurDate;
            printout.Date.Text = dtDate.Text;
            if (InstitutionIType.IsVaccine(GeneralInfo.Current))
            {
                return(CreateModel19Printout(dataTable.DefaultView.ToTable(), dtDate.Text));
            }
            return(printout);
        }
        public void RecordLocationTransaction(OrderLocationTransaction orderLocationTransaction, InventoryTransaction inventoryTransaction, Receipt receipt, User user)
        {
            LocationTransaction locationTransaction = GenerateOrderLocationTransaction(orderLocationTransaction, orderLocationTransaction.Location, user);

            if (inventoryTransaction.Hu != null)
            {
                locationTransaction.HuId  = inventoryTransaction.Hu.HuId;
                locationTransaction.LotNo = inventoryTransaction.Hu.LotNo;
            }
            if (locationTransaction.LotNo == null || locationTransaction.LotNo == string.Empty)
            {
                locationTransaction.LotNo = inventoryTransaction.LotNo;
            }
            locationTransaction.BatchNo       = inventoryTransaction.LocationLotDetailId;
            locationTransaction.RefLocation   = inventoryTransaction.RefLocation;
            locationTransaction.ReceiptNo     = receipt.ReceiptNo;
            locationTransaction.IpNo          = receipt.ReferenceIpNo;
            locationTransaction.Qty           = inventoryTransaction.Qty;
            locationTransaction.EffectiveDate = DateTime.Parse(receipt.CreateDate.ToString("yyyy-MM-dd"));
            if (orderLocationTransaction.OrderDetail.OrderHead.Type == BusinessConstants.CODE_MASTER_ORDER_TYPE_VALUE_TRANSFER)
            {
                OrderLocationTransaction outOrderLocationTransaction = this.orderLocationTransactionMgr.GetOrderLocationTransaction(orderLocationTransaction.OrderDetail.Id, BusinessConstants.IO_TYPE_OUT)[0];
                locationTransaction.RefLocation     = outOrderLocationTransaction.Location.Code;
                locationTransaction.RefLocationName = outOrderLocationTransaction.Location.Name;
            }

            this.CreateLocationTransaction(locationTransaction);
        }
Beispiel #49
0
        public override (ReceiptInfo, DeviceStatus) PrintReceipt(Receipt receipt)
        {
            var receiptInfo = new ReceiptInfo();

            // Abort all unfinished or erroneus receipts
            AbortReceipt();

            var(fiscalMemorySerialNumber, deviceStatus) = GetFiscalMemorySerialNumber();
            if (!deviceStatus.Ok)
            {
                return(receiptInfo, deviceStatus);
            }

            receiptInfo.FiscalMemorySerialNumber = fiscalMemorySerialNumber;

            // Opening receipt
            (_, deviceStatus) = OpenReceipt(
                receipt.UniqueSaleNumber,
                receipt.Operator,
                receipt.OperatorPassword
                );
            if (!deviceStatus.Ok)
            {
                AbortReceipt();
                deviceStatus.AddInfo($"Error occured while opening new fiscal receipt");
                return(receiptInfo, deviceStatus);
            }

            // Printing receipt's body
            deviceStatus = PrintReceiptBody(receipt);
            if (!deviceStatus.Ok)
            {
                AbortReceipt();
                deviceStatus.AddInfo($"Error occured while printing receipt items");
                return(receiptInfo, deviceStatus);
            }

            // Get the receipt date and time (current fiscal device date and time)
            DateTime?dateTime;

            (dateTime, deviceStatus) = GetDateTime();
            if (!dateTime.HasValue || !deviceStatus.Ok)
            {
                AbortReceipt();
                return(receiptInfo, deviceStatus);
            }
            receiptInfo.ReceiptDateTime = dateTime.Value;

            // Get receipt amount
            decimal?receiptAmount;

            (receiptAmount, deviceStatus) = GetReceiptAmount();
            if (!receiptAmount.HasValue || !deviceStatus.Ok)
            {
                (_, deviceStatus) = AbortReceipt();
                return(receiptInfo, deviceStatus);
            }
            receiptInfo.ReceiptAmount = receiptAmount.Value;

            // Closing receipt
            string closeReceiptResponse;

            (closeReceiptResponse, deviceStatus) = CloseReceipt();
            if (!deviceStatus.Ok)
            {
                (_, deviceStatus) = AbortReceipt();
                deviceStatus.AddInfo($"Error occurred while closing the receipt");
                return(receiptInfo, deviceStatus);
            }

            // Get receipt number
            string lastDocumentNumberResponse;

            (lastDocumentNumberResponse, deviceStatus) = GetLastDocumentNumber(closeReceiptResponse);
            if (!deviceStatus.Ok)
            {
                (_, deviceStatus) = AbortReceipt();
                deviceStatus.AddInfo($"Error occurred while reading last document number");
                return(receiptInfo, deviceStatus);
            }
            receiptInfo.ReceiptNumber = lastDocumentNumberResponse;

            return(receiptInfo, deviceStatus);
        }
        public static void Main(string[] args)
        {
            /******************* REQUEST VARIABLES*******************************/

            string host      = "esplusqa.moneris.com";
            string store_id  = "monusqa002";
            string api_token = "qatoken";
            //string status = "true";

            /****************** TRANSACTION VARIABLES *****************************/

            string order_id;                    //will prompt user for input
            string amount = "1.00";
            string txn_number;
            string crypt = "7";
            string dynamic_descriptor = "123456";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();

            Console.Write("Please enter a txn number: ");
            txn_number = Console.ReadLine();

            USRefund r = new USRefund(order_id, amount, txn_number, crypt);

            r.SetDynamicDescriptor(dynamic_descriptor);
            //r.SetCashIndicator("");

            HttpsPostRequest mpgReq = new HttpsPostRequest(host, store_id, api_token, r);


            /*Status Check Example
             * HttpsPostRequest mpgReq =
             *        new HttpsPostRequest(host, store_id, api_token, status,
             *                   new USRefund(order_id, amount, txn_number, crypt));
             */

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("ISO = " + receipt.GetISO());
                Console.WriteLine("BankTotals = " + receipt.GetBankTotals());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("Ticket = " + receipt.GetTicket());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                //Console.WriteLine("StatusCode = " + receipt.GetStatusCode());
                //Console.WriteLine("StatusMessage = " + receipt.GetStatusMessage());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #51
0
        public void Init()
        {
            List <IStat> stats = new List <IStat>
            {
                new RegenerationStat(100f, StatType.Health),
                new RegenerationStat(100f, StatType.Energy),
                new RegenerationStat(100f, StatType.Stamina),
                new Stat(0f, StatType.MagicDmg),
                new Stat(30f, StatType.Intelligence),
                new Stat(50f, StatType.Luck)
            };
            List <IStat> orc_stats = new List <IStat>
            {
                new RegenerationStat(1f, StatType.Health),
                new RegenerationStat(100f, StatType.Energy),
                new RegenerationStat(100f, StatType.Stamina),
                new Stat(0f, StatType.MagicDmg),
                new Stat(1f, StatType.Intelligence),
                new Stat(1f, StatType.Luck)
            };

            #region Enemy
            enemy_0 = new Enemy("Orc", "ver. 3.3", orc_stats, new Storage <IItem>(), new Storage <ConsumableItem>(), new Storage <IEquiped>());
            enemy_1 = new Enemy("Orc", "ver. 3.3", orc_stats, new Storage <IItem>(), new Storage <ConsumableItem>(), new Storage <IEquiped>());
            enemy_2 = new Enemy("Orc", "ver. 3.3", orc_stats, new Storage <IItem>(), new Storage <ConsumableItem>(), new Storage <IEquiped>());
            enemy_3 = new Enemy("Orc", "ver. 3.3", orc_stats, new Storage <IItem>(), new Storage <ConsumableItem>(), new Storage <IEquiped>());
            enemy_4 = new Enemy("Orc", "ver. 3.3", orc_stats, new Storage <IItem>(), new Storage <ConsumableItem>(), new Storage <IEquiped>());
            #endregion

            #region Items
            item_0 = new Resources(11, "iron", "resource item");
            item_1 = new Resources(11, "iron", "resource item");
            item_2 = new Resources(11, "iron", "resource item");
            item_3 = new Resources(11, "iron", "resource item");
            item_4 = new Resources(11, "iron", "resource item");
            #endregion

            hero = new Hero("Kazisvet III.", "z Bozi vule král", stats, new Storage <IItem>(), new Storage <ConsumableItem>(), new Storage <IEquiped>());


            #region Receipt

            Resources iron = new Resources(11, "iron", "resource item");
            Resources wood = new Resources(12, "wood", "resource item");
            Resources coal = new Resources(13, "coal", "resource item");


            Dictionary <IItem, int> materials = new Dictionary <IItem, int>
            {
                { iron, 3 },
                { wood, 2 },
                { coal, 4 }
            };
            Equipment receipt_weapon = new Equipment(111, "sword of destiny", "ultimate weapon", EquipSlot.RightHand);

            receipt_weapon.AddEquipEffect(new EquipEffect(EffectTarget.Character, StatType.Luck, +20f));
            recept = new Receipt(receipt_weapon, materials, 333, "Sword of Destiny Receipt", "Receipt for ultimate weapon");

            #endregion

            Equipment helm = new Equipment(1, "Helm of Fire", "+10 fire dmg", EquipSlot.Head);
            helm.AddEquipEffect(new EquipEffect(EffectTarget.Character, StatType.MagicDmg, +10));

            itemReward = new List <IItem>()
            {
                helm
            };

            statReward = new List <IStat>
            {
                new RegenerationStat(10f, StatType.Health),
                new RegenerationStat(5f, StatType.Energy),
                new RegenerationStat(5f, StatType.Stamina),

                new Stat(2f, StatType.Intelligence),
                new Stat(1f, StatType.Luck)
            };
        }
        public static void Main(string[] args)
        {
            /********************** Post Request Variables *************************/

            string host      = "esplusqa.moneris.com";
            string store_id  = "monusqa002";
            string api_token = "qatoken";

            /********************** Transactional Variables **********************/

            string order_id;                    //will prompt for user input
            string amount              = "5.00";
            string enc_track2          = "";
            string device_type         = "0812";
            string crypt               = "7";
            string commcard_invoice    = "INV98798";
            string commcard_tax_amount = "1.00";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();

            /*************** Address Verification Service **********************/

            AvsInfo avsCheck = new AvsInfo();

            avsCheck.SetAvsStreetNumber("212");
            avsCheck.SetAvsStreetName("Payton Street");
            avsCheck.SetAvsZipCode("M1M1M1");

            USEncPurchase encPurchaseTxn =
                new USEncPurchase(order_id, amount, enc_track2, device_type, crypt, commcard_invoice, commcard_tax_amount);

            encPurchaseTxn.SetAvsInfo(avsCheck);

            /****************** Card Validation Digits *************************/

            CvdInfo cvdCheck = new CvdInfo();

            cvdCheck.SetCvdIndicator("1");
            cvdCheck.SetCvdValue("099");

            encPurchaseTxn.SetCvdInfo(cvdCheck);

            /************************** Request *************************/

            HttpsPostRequest mpgReq =
                new HttpsPostRequest(host, store_id, api_token, encPurchaseTxn);

            /************************** Receipt *************************/

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("ISO = " + receipt.GetISO());
                Console.WriteLine("BankTotals = " + receipt.GetBankTotals());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("Ticket = " + receipt.GetTicket());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                Console.WriteLine("Avs Response = " + receipt.GetAvsResultCode());
                Console.WriteLine("Cvd Response = " + receipt.GetCvdResultCode());
                Console.WriteLine("CardLevelResult = " + receipt.GetCardLevelResult());
                Console.WriteLine("MaskedPan = " + receipt.GetMaskedPan());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #53
0
 /// <summary>
 /// Друк чека
 /// </summary>
 public LogRRO PrintReceipt(Receipt pReceipt)
 {
     return(RRO.PrintReceiptAsync(pReceipt).Result);
 }
Beispiel #54
0
 /// <summary>
 /// Constructor accepting a timestamp and potentially a receipt.
 /// </summary>
 /// <param name="date">Timestamp to be available.</param>
 /// <param name="receipt">Receipt to be available.</param>
 public Timestamp(DateTime date, Receipt receipt)
 {
     this.date    = date;
     this.receipt = receipt;
 }
        protected virtual DeviceStatus PrintReceiptBody(Receipt receipt)
        {
            if (receipt.Items == null || receipt.Items.Count == 0)
            {
                throw new StandardizedStatusMessageException("Receipt.Items must be not null or empty", "E410");
            }

            DeviceStatus deviceStatus;

            uint itemNumber = 0;

            // Receipt items
            foreach (var item in receipt.Items)
            {
                itemNumber++;
                if (item.Type == ItemType.Comment)
                {
                    (_, deviceStatus) = AddComment(item.Text);
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.AddInfo($"Error occurred in the comment of Item {itemNumber}");
                        return(deviceStatus);
                    }
                }
                else
                {
                    if (item.PriceModifierValue < 0m)
                    {
                        throw new StandardizedStatusMessageException("PriceModifierValue amount must be positive number", "E403");
                    }
                    if (item.PriceModifierValue != 0m && item.PriceModifierType == PriceModifierType.None)
                    {
                        throw new StandardizedStatusMessageException("PriceModifierValue must be 0 if priceModifierType is None", "E403");
                    }
                    try
                    {
                        (_, deviceStatus) = AddItem(
                            item.Text,
                            item.UnitPrice,
                            item.TaxGroup,
                            item.Quantity,
                            item.PriceModifierValue,
                            item.PriceModifierType);
                    }
                    catch (StandardizedStatusMessageException e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.AddError(e.Code, e.Message);
                    }
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.AddInfo($"Error occurred in Item {itemNumber}");
                        return(deviceStatus);
                    }
                }
            }

            // Receipt payments
            if (receipt.Payments == null || receipt.Payments.Count == 0)
            {
                (_, deviceStatus) = FullPaymentAndCloseReceipt();
                if (!deviceStatus.Ok)
                {
                    AbortReceipt();
                    deviceStatus.AddInfo($"Error occurred while making full payment in cash and closing the receipt");
                    return(deviceStatus);
                }
            }
            else
            {
                uint paymentNumber = 0;
                foreach (var payment in receipt.Payments)
                {
                    paymentNumber++;
                    try
                    {
                        (_, deviceStatus) = AddPayment(payment.Amount, payment.PaymentType);
                    }
                    catch (StandardizedStatusMessageException e)
                    {
                        deviceStatus = new DeviceStatus();
                        deviceStatus.AddError(e.Code, e.Message);
                    }
                    if (!deviceStatus.Ok)
                    {
                        AbortReceipt();
                        deviceStatus.AddInfo($"Error occurred in Payment {paymentNumber}");
                        return(deviceStatus);
                    }
                }
                (_, deviceStatus) = CloseReceipt();
                if (!deviceStatus.Ok)
                {
                    AbortReceipt();
                    deviceStatus.AddInfo($"Error occurred while closing the receipt");
                    return(deviceStatus);
                }
            }

            return(deviceStatus);
        }
        public static void Main(string[] args)
        {
            /******************* REQUEST VARIABLES*******************************/

            string host      = "esplusqa.moneris.com";
            string store_id  = "monus00001";
            string api_token = "montoken";

            /****************** TRANSACTION VARIABLES *****************************/

            string order_id;                            //will prompt user for input
            string cust_id = "";
            string amount  = "5.00";
            string card    = "4242424242424242";
            string exp     = "1212";
            string crypt   = "7";

            Console.Write("Please enter an order ID: ");
            order_id = Console.ReadLine();

            /********************* Addendum1  ****************************/
            string customer_code                 = "ID12345";
            string local_tax_amount              = "1.00";
            string discount_amount               = "0.50";
            string freight_amount                = "0.50";
            string duty_amount                   = "0.50";
            string national_tax_amount           = "0.00";
            string other_tax_amount              = "0.00";
            string vat_invoice_ref_num           = "123456789012345";
            string customer_vat_registration_num = "1234567890123";
            string vat_tax_amount                = "1.00";
            string vat_tax_rate                  = "0.00";
            string destination_zip               = "90210";
            string ship_from_zip                 = "90210";

            Addendum1 addendum1 = new Addendum1(customer_code, local_tax_amount, discount_amount, freight_amount,
                                                duty_amount, national_tax_amount, other_tax_amount, vat_invoice_ref_num,
                                                customer_vat_registration_num, vat_tax_amount, vat_tax_rate, destination_zip, ship_from_zip);

            /********************* Addendum2  ****************************/
            string item_description1 = "Item1";
            string product_code1     = "PROD00001";
            string commodity_code1   = "IT1";
            string quantity1         = "1.00";
            string unit_cost1        = "1.00";
            string ext_amount1       = "1.00";
            string uom1 = "EA";
            string tax_collected_ind1     = "Y";
            string item_discount_amount1  = "0.25";
            string item_local_tax_amount1 = "1.00";
            string item_other_tax_amount1 = "1.00";
            string item_other_tax_type1   = "0.00";
            string item_other_tax_rate1   = "0.00";
            string item_other_tax_id1     = "VAT";

            Addendum2 addendum2 = new Addendum2(item_description1, product_code1, commodity_code1, quantity1,
                                                unit_cost1, ext_amount1, uom1, tax_collected_ind1, item_discount_amount1,
                                                item_local_tax_amount1, item_other_tax_amount1, item_other_tax_type1,
                                                item_other_tax_rate1, item_other_tax_id1);

            string item_description2 = "Item2";
            string product_code2     = "PROD00002";
            string commodity_code2   = "IT2";
            string quantity2         = "2.00";
            string unit_cost2        = "2.00";
            string ext_amount2       = "2.00";
            string uom2 = "EA";
            string tax_collected_ind2     = "Y";
            string item_discount_amount2  = "0.25";
            string item_local_tax_amount2 = "2.00";
            string item_other_tax_amount2 = "2.00";
            string item_other_tax_type2   = "0.00";
            string item_other_tax_rate2   = "0.00";
            string item_other_tax_id2     = "VAT";

            addendum2.AddAddendum2(item_description2, product_code2, commodity_code2, quantity2,
                                   unit_cost2, ext_amount2, uom2, tax_collected_ind2, item_discount_amount2,
                                   item_local_tax_amount2, item_other_tax_amount2, item_other_tax_type2,
                                   item_other_tax_rate2, item_other_tax_id2);


            HttpsPostRequest mpgReq =
                new HttpsPostRequest(host, store_id, api_token,
                                     new USL23IndependentRefund(order_id, cust_id, amount, card, exp, crypt, addendum1, addendum2));

            try
            {
                Receipt receipt = mpgReq.GetReceipt();

                Console.WriteLine("CardType = " + receipt.GetCardType());
                Console.WriteLine("TransAmount = " + receipt.GetTransAmount());
                Console.WriteLine("TxnNumber = " + receipt.GetTxnNumber());
                Console.WriteLine("ReceiptId = " + receipt.GetReceiptId());
                Console.WriteLine("TransType = " + receipt.GetTransType());
                Console.WriteLine("ReferenceNum = " + receipt.GetReferenceNum());
                Console.WriteLine("ResponseCode = " + receipt.GetResponseCode());
                Console.WriteLine("ISO = " + receipt.GetISO());
                Console.WriteLine("BankTotals = " + receipt.GetBankTotals());
                Console.WriteLine("Message = " + receipt.GetMessage());
                Console.WriteLine("AuthCode = " + receipt.GetAuthCode());
                Console.WriteLine("Complete = " + receipt.GetComplete());
                Console.WriteLine("TransDate = " + receipt.GetTransDate());
                Console.WriteLine("TransTime = " + receipt.GetTransTime());
                Console.WriteLine("Ticket = " + receipt.GetTicket());
                Console.WriteLine("TimedOut = " + receipt.GetTimedOut());
                Console.WriteLine("Corporate Card = " + receipt.GetIsCorporateCard());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #57
0
        private static void TestCreatingReceiptsForAUser(Repository repository)
        {
            User[] allUsers = repository.Users.ToArray();

            var anyUserWithAnId = allUsers.FirstOrDefault(it => it.UserID != null);
            
            if (anyUserWithAnId == null)
            {
                Console.WriteLine("Again, this is probably a demo organisation. There are no UserIDs returned for these organisations.");
                return;
            }

            // Create a receipt
            Receipt receipt = new Receipt
                {
                    Contact = new Contact {Name = "Mojo Coffee"},
                    User = anyUserWithAnId,
                    Date = DateTime.Today.Date,
                    LineAmountTypes = LineAmountType.Inclusive,
                    LineItems = new LineItems
                        {
                            new LineItem
                                {
                                    Description = "Flat White",
                                    Quantity = 1m,
                                    AccountCode = "429",
                                    UnitAmount = 3.8m
                                },
                            new LineItem
                                {
                                    Description = "Mocha",
                                    Quantity = 1m,
                                    AccountCode = "429",
                                    UnitAmount = 4.2m
                                }
                        }
                };


            // Save the receipt to Xero
            receipt = repository.Create(receipt);

            if (receipt.ReceiptID == Guid.Empty)
            {
                string message = string.Format("The receipt was not succesfully created: {0}", receipt.ValidationErrors.Select(it => it.Message).Aggregate((s1, s2) => string.Concat(s1, ";", s2)));
                throw new ApplicationException(message);
            }

            Console.WriteLine("Receipt {0} was created for {1} for user {2}", receipt.ReceiptID, receipt.Contact.Name, receipt.User.FullName);


            // Upload an attachment against the newly creacted receipt
            FileInfo attachmentFileInfo = new FileInfo(AnyAttachmentFilename);

            if (!attachmentFileInfo.Exists)
            {
                throw new ApplicationException("The Receipt.png file cannot be loaded from disk!");
            }


            // Upload the attachment against the receipt
            Console.WriteLine("Attaching file {0} to Receipt {1}...", attachmentFileInfo.Name, receipt.ReceiptID);
            repository.Attachments.UpdateOrCreate(receipt, attachmentFileInfo);


            // Fetch the attachment that was just uploaded
            Attachment attachment = repository.Attachments.GetAttachmentFor(receipt);

            if (attachment.ContentLength != attachmentFileInfo.Length)
            {
                Console.WriteLine("The uploaded attachment filesize {0} does not match the original filesize {1}", attachment.ContentLength, attachmentFileInfo.Length);
            }
            else if (attachment.Filename != attachmentFileInfo.Name)
            {
                Console.WriteLine("The uploaded attachment filename '{0}' does not match the original filename '{1}'", attachment.Filename, attachmentFileInfo.Name);
            }
            else
            {
                Console.WriteLine("Attachment succesfully uploaded!");
            }
        }
        private void SaveReceipt(string isNext, bool isChequePayment)
        {
            List<Receipt> receipts;
            Receipt receipt = null;
            OpenItemReceiptAllocation openItemReceiptAllocation;
            CashReceiptDetail cashReceiptDetail;
            int refNo = 0;
            isChanged = true;

            try
            {
                receipts = new List<Receipt>();

                if (IsApplyPaymentsApplicable)
                {
                    foreach (OpenItemSearch openItem in openItems.Where(item => item.AmountDue > 0).OrderBy(item => item.OpenItemID))
                    {
                        if (refNo != openItem.ContractNo || IsApplyPaymentsApplicable == false)
                        {
                            receipt = new Receipt();

                            if (receipts.Count == 0 && receiptID != 0)
                            {
                                receipt.ID = Receipt.ID;
                            }

                            receipt.ReceiptBatchID = Receipt.ReceiptBatchID;
                            receipt.ReceiptDate = Receipt.ReceiptDate;
                            receipt.ApplyToTypeID = Receipt.ApplyToTypeID;
                            receipt.Reference = Receipt.Reference;
                            receipt.LastUserID = ((OperationsPrincipal)Thread.CurrentPrincipal).Identity.User.UserEntityId;
                            receipt.ContractID = openItem.ContractNo;
                            receipt.InternalReference = receipt.ContractID.ToString();

                            if (receiptApplyTo == ReceiptApplyTo.Invoice)
                            {
                                receipt.InvoiceAssetId = business.InvoiceFunctions.GetInvoiceAssetID(openItem.ContractNo, applyToObjectID.GetValueOrDefault());
                                receipt.InternalReference = receipt.InvoiceAssetId.GetValueOrDefault().ToString();
                            }

                            if (batchType == ReceiptBatchType.CashCheque)
                            {
                                if (isChequePayment)
                                {
                                    receipt.ChequeReceiptDetail = new ChequeReceiptDetail();
                                    receipt.ChequeReceiptDetail.AccountName = Receipt.ChequeReceiptDetail.AccountName;
                                    receipt.ChequeReceiptDetail.BankName = Receipt.ChequeReceiptDetail.BankName;
                                    receipt.ChequeReceiptDetail.BSBNumber = Receipt.ChequeReceiptDetail.BSBNumber;
                                    receipt.ChequeReceiptDetail.ChequeNumber = Receipt.ChequeReceiptDetail.ChequeNumber;
                                    receipt.ChequeReceiptDetail.PaymentTypeID = (int)paymentType;
                                    receipt.ChequeReceiptDetail.ReceiptID = receipt.ID;
                                    receipt.ChequeReceiptDetail.Receipt = receipt;
                                }
                                else
                                {
                                    receipt.ChequeReceiptDetail = null;
                                    cashReceiptDetail = new CashReceiptDetail();
                                    cashReceiptDetail.ReceiptID = receipt.ID;

                                    if (receipts.Count == 0 && Receipt.CashReceiptDetails != null && Receipt.CashReceiptDetails.Count > 0)
                                    {
                                        cashReceiptDetail.ID = Receipt.CashReceiptDetails.FirstOrDefault().ID;
                                    }

                                    cashReceiptDetail.PaymentTypeID = (int)paymentType;
                                    receipt.CashReceiptDetails = new List<CashReceiptDetail>();
                                    receipt.CashReceiptDetails.Add(cashReceiptDetail);
                                }
                            }
                            else if (batchType == ReceiptBatchType.DirectDebit)
                            {
                                receipt.DirectDebitReceiptDetails = new List<DirectDebitReceiptDetail>();

                                if (receipts.Count == 0)
                                {
                                    receipt.DirectDebitReceiptDetails.Add(new DirectDebitReceiptDetail { LesseeBankAccountID = DDCCAccountID, ID = Receipt.DirectDebitReceiptDetails.FirstOrDefault().ID, ReceiptID = Receipt.ID });
                                }
                                else
                                {
                                    receipt.DirectDebitReceiptDetails.Add(new DirectDebitReceiptDetail { LesseeBankAccountID = DDCCAccountID });
                                }
                            }
                            else if (batchType == ReceiptBatchType.CreditCard)
                            {
                                receipt.CreditCardReceiptDetails = new List<CreditCardReceiptDetail>();

                                if (receipts.Count == 0)
                                {
                                    receipt.CreditCardReceiptDetails.Add(new CreditCardReceiptDetail { LesseeBankAccountID = DDCCAccountID, ID = Receipt.CreditCardReceiptDetails.FirstOrDefault().ID, ReceiptID = Receipt.ID });
                                }
                                else
                                {
                                    receipt.CreditCardReceiptDetails.Add(new CreditCardReceiptDetail { LesseeBankAccountID = DDCCAccountID });
                                }
                            }                          

                            receipt.OpenItemReceiptAllocations = new List<OpenItemReceiptAllocation>();
                            receipts.Add(receipt);
                            refNo = openItem.ContractNo;
                        }

                        openItemReceiptAllocation = new OpenItemReceiptAllocation();
                        openItemReceiptAllocation.OpenItemID = openItem.OpenItemID;
                        openItemReceiptAllocation.ReceiptID = receiptID;
                        openItemReceiptAllocation.GrossAmountDue = openItem.AmountDue;
                        openItemReceiptAllocation.GrossAmountApplied = Convert.ToDecimal(openItem.AmountApplied);

                        receipt.OpenItemReceiptAllocations.Add(openItemReceiptAllocation);
                    }
                }
                else
                {
                    receipt = new Receipt();

                    receipt.ID = Receipt.ID;
                    receipt.ReceiptBatchID = Receipt.ReceiptBatchID;
                    receipt.ReceiptDate = Receipt.ReceiptDate;
                    receipt.ApplyToTypeID = Receipt.ApplyToTypeID;
                    receipt.Reference = Receipt.Reference;
                    receipt.LastUserID = ((OperationsPrincipal)Thread.CurrentPrincipal).Identity.User.UserEntityId;
                    receipt.GrossAmountReceived = amountReceived;
                    receipt.NetAmountReceived = amountReceived;

                    if (receiptApplyTo == ReceiptApplyTo.Quote)
                    {
                        receipt.QuoteID = applyToObjectID.GetValueOrDefault();
                        receipt.InternalReference = receipt.QuoteID.ToString();
                    }

                    if (batchType == ReceiptBatchType.CashCheque)
                    {
                        if (isChequePayment)
                        {
                            receipt.ChequeReceiptDetail = new ChequeReceiptDetail();
                            receipt.ChequeReceiptDetail.AccountName = Receipt.ChequeReceiptDetail.AccountName;
                            receipt.ChequeReceiptDetail.BankName = Receipt.ChequeReceiptDetail.BankName;
                            receipt.ChequeReceiptDetail.BSBNumber = Receipt.ChequeReceiptDetail.BSBNumber;
                            receipt.ChequeReceiptDetail.ChequeNumber = Receipt.ChequeReceiptDetail.ChequeNumber;
                            receipt.ChequeReceiptDetail.PaymentTypeID = (int)paymentType;
                            receipt.ChequeReceiptDetail.ReceiptID = receipt.ID;
                            receipt.ChequeReceiptDetail.Receipt = receipt;
                        }
                        else
                        {
                            receipt.ChequeReceiptDetail = null;
                            receipt.CashReceiptDetails = new List<CashReceiptDetail>();
                            receipt.CashReceiptDetails.Add(new CashReceiptDetail() { ReceiptID = receipt.ID, PaymentTypeID = (int)paymentType });

                            if (receipts.Count == 0 && Receipt.CashReceiptDetails != null && Receipt.CashReceiptDetails.Count > 0)
                            {
                                receipt.CashReceiptDetails.FirstOrDefault().ID = Receipt.CashReceiptDetails.FirstOrDefault().ID;
                            }
                        }
                    }
                    else if (batchType == ReceiptBatchType.DirectDebit)
                    {
                        receipt.DirectDebitReceiptDetails = new List<DirectDebitReceiptDetail>();

                        if (receipts.Count == 0)
                        {
                            receipt.DirectDebitReceiptDetails.Add(new DirectDebitReceiptDetail { LesseeBankAccountID = DDCCAccountID, ID = Receipt.DirectDebitReceiptDetails.FirstOrDefault().ID, ReceiptID = Receipt.ID });
                        }
                        else
                        {
                            receipt.DirectDebitReceiptDetails.Add(new DirectDebitReceiptDetail { LesseeBankAccountID = DDCCAccountID });
                        }
                    }
                    else if (batchType == ReceiptBatchType.CreditCard)
                    {
                        receipt.CreditCardReceiptDetails = new List<CreditCardReceiptDetail>();

                        if (receipts.Count == 0)
                        {
                            receipt.CreditCardReceiptDetails.Add(new CreditCardReceiptDetail { LesseeBankAccountID = DDCCAccountID, ID = Receipt.CreditCardReceiptDetails.FirstOrDefault().ID, ReceiptID = Receipt.ID });
                        }
                        else
                        {
                            receipt.CreditCardReceiptDetails.Add(new CreditCardReceiptDetail { LesseeBankAccountID = DDCCAccountID });
                        }
                    }                    

                    receipts.Add(receipt);
                }

                ReceiptFunctions.Save(receipts);

                isChanged = false;

                if (Convert.ToBoolean(isNext))
                {
                    receiptID = 0;
                    SetReceiptDefaults(Receipt.ReceiptBatchID);
                    SetIcon();
                    RaisePropertyChanged("IsReceiptinEditMode");
                }
                else
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                ExceptionLogger.WriteLog(ex);
                ShowErrorMessage("Error occurred while Saving Receipt", "Add Receipt - Error");
                IsBusy = false;
            }
        }
Beispiel #59
0
 public Receipt Update(Receipt item)
 {
     return(Receipts.Update(item));
 }
      public ReceiptExportDocument Map(Receipt receipt)
      {
          var mapto = new ReceiptExportDocument();
          var order = _mainOrderRepository.GetById(receipt.DocumentParentId);
          string orderExternalRef = "";
           string outletCode = "";
          string salesmanCode = "";
          string shipToAddress = "";
          Guid orderId;

          if (order != null)
          {
              orderExternalRef = order.ExternalDocumentReference;
              mapto.OrderTotalGross = order.TotalGross;
              mapto.OrderNetGross = order.TotalNet;

          }
          if (order != null && order.DocumentIssuerCostCentre is DistributorSalesman)
          {
              salesmanCode = order.DocumentIssuerCostCentre.CostCentreCode;

          }
          else if(order != null && order.DocumentRecipientCostCentre is DistributorSalesman)
          {
              salesmanCode = order.DocumentRecipientCostCentre.CostCentreCode;
          }
           if (order != null && order.IssuedOnBehalfOf!=null)
           {
               outletCode = order.IssuedOnBehalfOf.CostCentreCode;
           }

           if (order != null)
           {
               shipToAddress = order.ShipToAddress;
               
           }

         
          mapto.Id = receipt.Id;
          mapto.InvoiceRef = receipt.InvoiceId.ToString();
          mapto.OrderExternalRef = orderExternalRef;
          mapto.OutletCode = outletCode;
          mapto.ReceiptRef = receipt.DocumentReference;
          mapto.SalesmanCode = salesmanCode;

          mapto.PaymentDate = receipt.DocumentDateIssued;
          mapto.ShipToAddress = shipToAddress;
          mapto.RouteName = GetOnBehalfOfCCRouteName(order.Id);
        
          mapto.LineItems = receipt.LineItems.Select(s => MapItem(s)).ToList();
          return mapto;
      }