예제 #1
0
        private string formatPurchaseOfflineOutEvent(PurchaseTransaction model)
        {
            var str = new StringBuilder();

            str.Append($"Reference Number: {model.ReceiptNum};");
            return(str.ToString());
        }
예제 #2
0
        private static decimal CalculatePurchaseTransactionTotalCOGS(PurchaseTransaction purchaseTransaction)
        {
            var totalCOGS = 0m;

            foreach (var line in purchaseTransaction.PurchaseTransactionLines)
            {
                if (line.SoldOrReturned <= 0)
                {
                    continue;
                }
                var lineNetTotal = line.PurchasePrice - line.Discount;
                if (lineNetTotal == 0)
                {
                    continue;
                }
                var lineFractionOfTransactionDiscount = line.SoldOrReturned * lineNetTotal /
                                                        purchaseTransaction.GrossTotal * purchaseTransaction.Discount;
                var lineFractionOfTransactionTax = line.SoldOrReturned * lineNetTotal /
                                                   purchaseTransaction.GrossTotal * purchaseTransaction.Tax;
                var lineCOGS = line.SoldOrReturned * lineNetTotal - lineFractionOfTransactionDiscount +
                               lineFractionOfTransactionTax;
                totalCOGS += lineCOGS;
            }
            return(totalCOGS);
        }
        public void CreatePurchaseTransaction(PurchaseTransaction purchaseTransaction)
        {
            var command = new CreatePurchaseTransactionCommand
            {
                PurchaseTransaction = purchaseTransaction
            };

            processXml.Process(command.ToXml());
        }
예제 #4
0
        private static PurchaseTransaction CreatePurchaseTransaction()
        {
            var purchaseTransactionId = new PurchaseTransactionId(SequentialGuid.NewSequentialGuid());
            var storeId = new StoreId(SequentialGuid.NewSequentialGuid());
            var store   = Store.Create(storeId, "Kwik-E-Mart");

            return(PurchaseTransaction
                   .CreateFull(purchaseTransactionId, store, new List <LineItemStripped>(), DateTime.Now));
        }
        /// <summary>
        /// Gets all items by purchase transaction.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        /// <returns>
        /// The purchase transaction's items.
        /// </returns>
        public IList <PurchaseTransaction_Item> GetAllItemsByPurchaseTransaction(PurchaseTransaction transaction)
        {
            if (transaction == null)
            {
                throw new ArgumentNullException();
            }

            return(this.itemRepository.GetAllItemsByPurchaseTransaction(transaction));
        }
예제 #6
0
        public void updateRelatedTableColumns(ref PurchaseTransaction model)
        {
            var vehicleNum = model.VehicleNum;
            var vehicle    = vehicleRepository.Get()
                             .Include(a => a.VehicleType).DefaultIfEmpty()
                             .Where(a => a.VehicleNum == vehicleNum)
                             .Select(a => new { a.VehicleNum, a.VehicleTypeId, VehicleTypeCode = a.VehicleType == null ? "" : a.VehicleType.VehicleTypeCode }).ToList().FirstOrDefault();

            model.VehicleTypeId   = vehicle?.VehicleTypeId ?? 0;
            model.VehicleTypeCode = vehicle?.VehicleTypeCode;

            var supplierId = model.SupplierId;

            model.SupplierName = supplierRepository.Get()
                                 .Where(a => a.SupplierId == supplierId).Select(a => a.SupplierName).FirstOrDefault();

            var rawMaterialId = model.RawMaterialId;
            var material      = rawMaterialRepository.Get()
                                .Where(a => a.RawMaterialId == rawMaterialId)
                                .Include(a => a.Category).DefaultIfEmpty()
                                .Select(a => new { a.RawMaterialDesc, a.CategoryId, CategoryDesc = a.Category == null ? null : a.Category.CategoryDesc })
                                .FirstOrDefault();

            model.RawMaterialDesc = material?.RawMaterialDesc;
            model.CategoryId      = material?.CategoryId ?? 0;
            model.CategoryDesc    = material?.CategoryDesc;

            var purchaseOrderId = model.PurchaseOrderId;
            var poDetails       = purchaseOrderRepository.Get()
                                  .Where(a => a.PurchaseOrderId == purchaseOrderId).Select(a => new { a.PONum, a.Price, a.POType }).FirstOrDefault();

            model.PONum  = poDetails?.PONum ?? String.Empty;
            model.Price  = poDetails?.Price ?? 0;
            model.POType = poDetails?.POType;

            var sourceId = model.SourceId;
            var source   = sourceRepository.Get()
                           .Where(a => a.SourceId == sourceId)
                           .Include(a => a.SourceCategory).DefaultIfEmpty()
                           .Select(a => new { a.SourceDesc, a.SourceCategoryId, SourceCategoryDesc = a.SourceCategory == null ? null : a.SourceCategory.Description })
                           .FirstOrDefault();

            model.SourceName         = source?.SourceDesc;
            model.SourceCategoryId   = source?.SourceCategoryId ?? 0;
            model.SourceCategoryDesc = source?.SourceCategoryDesc;

            var msId = model.MoistureReaderId;

            model.MoistureReaderDesc = moistureReaderRepository.Get()
                                       .Where(a => a.MoistureReaderId == msId).Select(a => a.Description).FirstOrDefault();


            var userAccountId = model.WeigherOutId;

            model.WeigherOutName = userAccountRepository.Get().Where(a => a.UserAccountId == userAccountId)
                                   .Select(a => a.FullName).FirstOrDefault();
        }
예제 #7
0
 private static bool IsPurchaseTransactionInDatabase(PurchaseTransaction purchaseTransaction)
 {
     if (purchaseTransaction != null)
     {
         return(true);
     }
     MessageBox.Show("Please check if the transaction has been issued or exists.", "Invalid Sales Transaction",
                     MessageBoxButton.OK);
     return(false);
 }
예제 #8
0
 private void UpdatePurchaseTransactionLines(PurchaseTransaction purchaseTransaction)
 {
     PurchaseTransactionLines.Clear();
     foreach (var line in purchaseTransaction.PurchaseTransactionLines.ToList())
     {
         PurchaseTransactionLines.Add(new PurchaseTransactionLineVM {
             Model = line
         });
     }
 }
예제 #9
0
        private void submitTransactionButton_Click(object sender, EventArgs e)
        {
            if (this.itemsToPurchase.Count == 0)
            {
                ErrorHandler.DisplayErrorBox("Error", "Cannot submit an empty transaction.");
                return;
            }

            if (this.customerID == "null")
            {
                ErrorHandler.DisplayErrorBox("Error", "Must select a customer.");
                return;
            }

            try
            {
                var theController       = new TransactionController();
                var furnitureController = new FurnitureController();

                var transaction = new PurchaseTransaction
                {
                    TransactionTime = DateTime.Now,
                    CustomerId      = this.customerID,
                    EmployeeId      = this.session.Id.ToString(),
                    Items           = new List <PurchaseTransaction_Item>(this.itemsToPurchase)
                };


                theController.AddPurchaseTransaction(transaction);

                furnitureController.UpdateQuantitiesByIds(transaction.Items);
                MessageBox.Show(this.itemsToPurchase.Count + @" item(s) were purchased for a total of " + this.totalPriceLabel.Text + ".", @"Transaction Successful",
                                MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
                this.clearTransaction();
            }
            catch (NullReferenceException nullReference)
            {
                ErrorHandler.DisplayErrorMessageToUserAndLog("Session Error", "The login session is null.", nullReference);
            }
            catch (InvalidCastException invalidCast)
            {
                ErrorHandler.DisplayErrorMessageToUserAndLog("Session Error", "The tag cannot be cast as a login session.", invalidCast);
            }
            catch (MySqlException sqlException)
            {
                ErrorHandler.DisplayErrorMessageToUserAndLog("SQL Error",
                                                             "The transaction could not be added to the database.", sqlException);
            }
            catch (ArgumentOutOfRangeException rangeException)
            {
                ErrorHandler.DisplayErrorMessageToUserAndLog("Quantity Error",
                                                             rangeException.Message, rangeException);
            }
        }
예제 #10
0
        public void PurchaseTransaction_created()
        {
            var purchaseTransactionId = new PurchaseTransactionId(SequentialGuid.NewSequentialGuid());
            var storeId = new StoreId(SequentialGuid.NewSequentialGuid());
            var store   = Store.Create(storeId, "Kwik-E-Mart");
            var sut     = PurchaseTransaction.CreateFull(purchaseTransactionId, store, new List <LineItemStripped>(), DateTime.Now);

            Assert.NotNull(sut);
            Assert.Contains("Kwik-E-Mart", sut.Store.Name);
            Assert.NotNull(sut.LineItems);
        }
예제 #11
0
 private void SetNewTransactionMode(PurchaseTransaction purchaseTransaction)
 {
     NewEntryVM.ResetEntryFields();
     Model.PurchaseTransaction = purchaseTransaction;
     UpdatePurchaseTransactionLines(purchaseTransaction);
     SelectedPurchaseTransactionSupplier = new SupplierVM {
         Model = Model.PurchaseTransaction.Supplier
     };
     SelectedPurchaseTransactionLine = null;
     NotEditing = true;
 }
예제 #12
0
        public void InsertTransaction(PurchaseTransaction purchase)
        {
            using (var db = new StoreDB())
            {
                PURCHASE_TRANSACTIONS prod = Mapper.Map <PURCHASE_TRANSACTIONS>(purchase);


                db.Set <PURCHASE_TRANSACTIONS>().Add(prod);
                db.SaveChanges();
            }
        }
        public PurchaseTransaction ReadPurchaseTransaction(
            string purchaseTransactionNumber)
        {
            var command = new ReadPurchaseTransactionCommand
            {
                Office = session.Office,
                PurchaseTransactionNumber = purchaseTransactionNumber
            };
            var response = processXml.Process(command.ToXml());

            return(PurchaseTransaction.FromXml(response));
        }
예제 #14
0
        public AuditLog initAuditLogDelete(PurchaseTransaction model)
        {
            var auditLogRefNum = $"Reference Num: R{model.BalingStationNum}{model.ReceiptNum}";

            var auditLog = new AuditLog()
            {
                AuditLogEventId = auditLogEventRepository.GetPurchaseDeletedEventId(),
                UserAccountId   = model.LoggedInUserId,
                Notes           = auditLogRefNum
            };

            return(auditLog);
        }
예제 #15
0
        private void Purchase()
        {
            if (!ValidateInputFields())
            {
                RaiseNotification("Alert", "Please all the required fields");
                return;
            }

            var transaction = new PurchaseTransaction();
            var product     = new PurchaseProduct();

            try
            {
                product.ProductId     = Convert.ToInt32(ProductId);
                product.PurchasePrice = Convert.ToDecimal(PurchasePrice);
                product.SellingPrice  = Convert.ToDecimal(SellingPrice);
                product.Quantity      = Convert.ToInt32(Quantity);

                transaction.ItemList.Add(product);
                transaction.PaymentList.Add(new PurchasePayment()
                {
                    PaymentAmount = Convert.ToDecimal(Amount),
                    Payment       = new Payment()
                    {
                        PaidAmount  = Convert.ToDecimal(Amount),
                        PaymentDate = DateTime.Today,
                        PaymentType = 1
                    }
                });
                //To do
                //transaction.PurchaseTaxTotal = //Compute tax from SelectedTaxRate
                transaction.PurchaseTaxTotal = Convert.ToDecimal(1.00);
                transaction.SupplierId       = SelectedSupplierId;
                transaction.PurchaseTxnTotal = Convert.ToDecimal(Amount);
                transaction.BillNumber       = BillNumber;
                transaction.GSTIN            = GSTIN;
                transaction.PurchaseDate     = DateTime.Today;
                _purchaseTransaction.Complete(transaction);
                RaiseNotification("Success",
                                  string.Format("Successfully added the purchase of the product {0}", ProductName));
            }
            catch (Exception ex)
            {
                log.Error(transaction, ex);
                RaiseNotification("Error", "Failed to add purchase.");
            }
            finally
            {
                ResetUI();
            }
        }
        public async Task ChangeLineItem(PurchaseTransaction purchaseTransaction, LineItem lineItem)
        {
            var transaction = await context.Purchases
                              .Include(p => p.LineItems)
                              .FirstOrDefaultAsync(p => p.Id == purchaseTransaction.Id);

            LineItem toBeRemoved = transaction.LineItems.Find(l => l.Id == lineItem.Id);

            purchaseTransaction.LineItems.Remove(toBeRemoved);
            await context.SaveChangesAsync();

            purchaseTransaction.LineItems.Add(lineItem);
            await context.SaveChangesAsync();
        }
예제 #17
0
        public static void EditTransactionInDatabase(PurchaseTransaction editedPurchaseTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();
                RecordEditedPurchaseTransactionLedgerTransactionsInDatabaseContext(context, editedPurchaseTransaction);
                SetPurchaseTransactionInDatabaseContextToEditedPurchaseTransactionProperties(context, editedPurchaseTransaction);
                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
예제 #18
0
        public static void EditTransactionInDatabase(PurchaseTransaction editedPurchaseTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();
                RecordEditedPurchaseTransactionLedgerTransactionsInDatabaseContext(context, editedPurchaseTransaction);
                SetPurchaseTransactionInDatabaseContextToEditedPurchaseTransactionProperties(context, editedPurchaseTransaction);
                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
예제 #19
0
 private void AssignSelectedPurchaseTransactionPropertiesToUI(PurchaseTransaction purchaseTransaction)
 {
     SelectedPurchaseLines.Clear();
     foreach (var lineVM in purchaseTransaction.PurchaseTransactionLines.Select(line => new PurchaseTransactionLineVM {
         Model = line
     }))
     {
         SelectedPurchaseLines.Add(lineVM);
     }
     PurchaseTransactionGrossTotal = purchaseTransaction.GrossTotal;
     PurchaseTransactionDiscount   = purchaseTransaction.Discount;
     PurchaseTransactionTax        = purchaseTransaction.Tax;
     PurchaseTransactionTotal      = purchaseTransaction.Total;
     Remaining = purchaseTransaction.Total - purchaseTransaction.Paid;
 }
예제 #20
0
        public string Purchase(double dPurchase, double dCashout, double dCheque, string sRef)
        {
//			using (VaultSession vs = new VaultSession("CHECKOUT1"))
            {
                sRef += DateTime.Now.ToOADate().ToString();
                TransactionResult ret = new TransactionResult();

                if (dPurchase > 0)
                {
                    PurchaseTransaction txp = new PurchaseTransaction(sRef, (decimal)(dPurchase));
                    if (dCashout > 0)
                    {
                        txp.CashOutAmount = (decimal)dCashout;
                    }
                    ret = vs.ExecuteTransaction(txp);

                    // Check to see if the result is Unknown - note that ExecuteTransaction
                    // will only ever return TransactionResult.Unknown if the session is
                    // reset or if the VaultSession.EnableAutoComplete property is false.
                    // If the POS Application does not call reset session and leaves
                    // auto-completion enabled then this test is not necessary.
                    while (ret == TransactionResult.Unknown)
                    {
                        ret = vs.CompleteTransaction(txp);
                    }
                }
                else if (dPurchase < 0)
                {
                    RefundTransaction txr = new RefundTransaction(sRef, (decimal)(0 - dPurchase));
                    ret = vs.ExecuteTransaction(txr);
                }
                else if (dCheque > 0)
                {
                    ChequeAuthTransaction txca = new ChequeAuthTransaction(sRef, (decimal)dCheque);
                    ret = vs.ExecuteTransaction(txca);
                }
                else
                {
                    return("INVALID AMOUNT");
                }
                if (ret == TransactionResult.Success)
                {
                    return("ACCEPTED");
                }
            }
            return("FAILED");
        }
예제 #21
0
        /// <summary>
        /// Gets the transactions by customer identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public IList <PurchaseTransaction> GetTransactionsByCustomerId(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException(nameof(id));
            }


            var purchaseTransactions = new List <PurchaseTransaction>();

            const string query = "SELECT * FROM PurchaseTransaction WHERE Customer_id = @id";

            var connection = new MySqlConnection(this.CONNECTION_STRING);

            using (var command = new MySqlCommand(query))
            {
                command.Connection = connection;
                command.Parameters.AddWithValue("@id", id);

                try
                {
                    command.Connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        var theTransaction = new PurchaseTransaction
                        {
                            Id = reader["id"].ToString(),
                            TransactionTime = reader["transactionTime"] as DateTime? ?? DateTime.MinValue,
                            CustomerId      = reader["Customer_id"] == DBNull.Value ? "NULL" : reader["Customer_id"].ToString(),
                            EmployeeId      = reader["Employee_id"] as string ?? string.Empty,
                        };


                        purchaseTransactions.Add(theTransaction);
                    }
                }
                finally
                {
                    command.Connection.Close();
                }
            }

            return(purchaseTransactions);
        }
예제 #22
0
        public static void MakePayment(PurchaseTransaction purchaseTransaction, decimal paymentAmount,
                                       decimal useCreditsAmount, string paymentMode)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                context.Entry(purchaseTransaction).State = EntityState.Modified;
                purchaseTransaction.Paid += paymentAmount + useCreditsAmount;
                purchaseTransaction.Supplier.PurchaseReturnCredits -= useCreditsAmount;

                RecordPaymentLedgerTransactionInDatabaseContext(context, purchaseTransaction, paymentAmount, paymentMode);

                context.SaveChanges();
                ts.Complete();
            }
        }
예제 #23
0
        public static void MakePayment(PurchaseTransaction purchaseTransaction, decimal paymentAmount,
            decimal useCreditsAmount, string paymentMode)
        {
            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                context.Entry(purchaseTransaction).State = EntityState.Modified;
                purchaseTransaction.Paid += paymentAmount + useCreditsAmount;
                purchaseTransaction.Supplier.PurchaseReturnCredits -= useCreditsAmount;

                RecordPaymentLedgerTransactionInDatabaseContext(context, purchaseTransaction, paymentAmount, paymentMode);

                context.SaveChanges();
                ts.Complete();
            }
        }
예제 #24
0
        public async Task Valid_Id_Returns_PurchaseTransaction()
        {
            var          id                  = Guid.NewGuid();
            var          store               = Store.Create(new StoreId(SequentialGuid.NewSequentialGuid()), "Kwik-E-Mart");
            var          lineItem            = new List <LineItemStripped>();
            PurchaseDate transactionDate     = new PurchaseDate(DateTime.Now);
            var          purchaseTransaction = PurchaseTransaction.CreateFull(id, store, lineItem, transactionDate);

            var mockPurchaseTransactionService = new Mock <IPurchaseTransactionService>();

            mockPurchaseTransactionService.Setup(s => s.GetDetailedPurchaseTransaction(id))
            .Returns(() => Task.FromResult(purchaseTransaction));

            var purchaseTransactionController = new PurchaseTransactionController(mockPurchaseTransactionService.Object);
            var result = await purchaseTransactionController.GetPurchaseTransaction(id);

            mockPurchaseTransactionService.Verify(mock => mock.GetDetailedPurchaseTransaction(id), Times.Once());
            Assert.NotNull(result);
        }
예제 #25
0
        private static void RecordEditedPurchaseTransactionTotalCOGSChangedLedgerTransactionInDatabaseContext(
            ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal totalCOGSChanged)
        {
            var purchaseTransactionTotalCOGSChangedLedgerTransaction = new LedgerTransaction();

            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment (COGS)");
            context.SaveChanges();

            if (totalCOGSChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Debit", totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Credit", totalCOGSChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Debit", -totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Credit", -totalCOGSChanged);
            }
            context.SaveChanges();
        }
예제 #26
0
        public bool Delete(PurchaseTransaction model)
        {
            dbContext.PurchaseTransactions.Remove(model);
            dbContext.RemoveRange(dbContext.moistureReaderLogs.Where(a => a.TransactionId == model.PurchaseId));
            dbContext.SaveChanges();

            var auditLog = initAuditLogDelete(model);

            if (auditLog != null)
            {
                auditLogRepository.Create(auditLog);
            }

            vehicleDeliveryRestrictionRepository.Delete(new VehicleDeliveryRestriction(model.VehicleNum, model.RawMaterialId)
            {
                DateTimeIn = model.DateTimeIn,
            });

            balingStationRepository.CheckAndCreateStockStatusReminder();
            return(true);
        }
예제 #27
0
        /// <summary>
        /// Gets the item from the database by identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public PurchaseTransaction GetById(string id)
        {
            const string query = "SELECT * " +
                                 "FROM PurchaseTransaction " +
                                 "WHERE id = @id";

            var connection = new MySqlConnection(this.CONNECTION_STRING);

            var transaction = new PurchaseTransaction();

            using (var command = new MySqlCommand(query))
            {
                command.Connection = connection;

                command.Parameters.AddWithValue("@id", id);

                try
                {
                    command.Connection.Open();

                    var reader = command.ExecuteReader();

                    while (reader.Read())
                    {
                        transaction.Id = ((int)reader["id"]).ToString();
                        transaction.TransactionTime = reader["transactionTime"] == DBNull.Value
                            ? DateTime.MinValue
                            : reader["transactionTime"] as DateTime? ?? DateTime.MinValue;
                        transaction.CustomerId = reader["Customer_id"] == DBNull.Value ? "0" : ((int)reader["Customer_id"]).ToString();
                        transaction.EmployeeId = reader["Employee_id"] == DBNull.Value ? "0" : ((int)reader["Employee_id"]).ToString();
                    }
                }
                finally
                {
                    command.Connection.Close();
                }
            }

            return(transaction);
        }
예제 #28
0
        /// <summary>
        /// Adds the purchase transaction.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        public void AddPurchaseTransaction(PurchaseTransaction transaction)
        {
            var id = this.purchaseRepository.AddOne(transaction);

            transaction.Id = id;

            try
            {
                foreach (var item in transaction.Items)
                {
                    item.PurchaseTransactionId = id;
                }

                this.purchaseItemRepository.AddList(transaction.Items);
            }
            catch (Exception)
            {
                this.deleteChangesFromDatabase(transaction.Items, id);

                throw;
            }
        }
        public int CreateStockPurchase(AddPurchaseTransactionVm addPurchaseTransactionVm)
        {
            var purchaseTransaction = new PurchaseTransaction()
            {
                BrokerageAccountId   = addPurchaseTransactionVm.BrokerageAccountId,
                Commission           = addPurchaseTransactionVm.Commission,
                SecurityId           = addPurchaseTransactionVm.SecurityId,
                ShareQuantity        = addPurchaseTransactionVm.ShareQuantity,
                UnitPrice            = addPurchaseTransactionVm.UnitPrice,
                TransactionDate      = addPurchaseTransactionVm.TransactionDate,
                ClosedShares         = 0,
                RemainingShares      = addPurchaseTransactionVm.ShareQuantity,
                PositionClosedStatus = false
            };

            DbOperationStatus opStatus = PurchaseTransactionRepository.InsertPurchaseTransaction(purchaseTransaction);

            if (opStatus.OperationSuccessStatus)
            {
                return(opStatus.AffectedIndices.First());
            }
            return(-1);
        }
        public DbOperationStatus InsertPurchaseTransaction(PurchaseTransaction purchaseTransaction)
        {
            var opStatus = new DbOperationStatus
            {
                OperationSuccessStatus = false,
                AffectedIndices        = new List <int>()
            };

            try
            {
                DataContext.Set <PurchaseTransaction>().Add(purchaseTransaction);
                opStatus.OperationSuccessStatus = DataContext.SaveChanges() > 0;
                if (opStatus.OperationSuccessStatus)
                {
                    opStatus.AffectedIndices.Add(purchaseTransaction.Id);
                }
            }
            catch (Exception ex)
            {
                opStatus = DbOperationStatus.CreateFromException("Error inserting " + purchaseTransaction.GetType(), ex);
            }
            return(opStatus);
        }
예제 #31
0
        public static void AddNewTransactionToDatabase(PurchaseTransaction purchaseTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                foreach (var line in purchaseTransaction.PurchaseTransactionLines)
                {
                    AttachPurchaseTransactionLineToDatabaseContext(context, line);
                    IncreaseLineItemStockInDatabaseContext(context, line);
                    context.SaveChanges();
                }

                AttachPurchaseTransactionPropertiesToDatabaseContext(context, purchaseTransaction);
                RecordPurchaseLedgerTransactionInDatabaseContext(context, purchaseTransaction);

                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
예제 #32
0
        public static void AddNewTransactionToDatabase(PurchaseTransaction purchaseTransaction)
        {
            IsLastSaveSuccessful = false;

            using (var ts = new TransactionScope())
            {
                var context = new ERPContext();

                foreach (var line in purchaseTransaction.PurchaseTransactionLines)
                {
                    AttachPurchaseTransactionLineToDatabaseContext(context, line);
                    IncreaseLineItemStockInDatabaseContext(context, line);
                    context.SaveChanges();
                }

                AttachPurchaseTransactionPropertiesToDatabaseContext(context, purchaseTransaction);
                RecordPurchaseLedgerTransactionInDatabaseContext(context, purchaseTransaction);

                ts.Complete();
            }

            IsLastSaveSuccessful = true;
        }
예제 #33
0
        /// <summary>
        /// Adds one item to the database.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public string AddOne(PurchaseTransaction item)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }

            var id = string.Empty;

            const string statement = "INSERT INTO PurchaseTransaction (transactionTime, Customer_id, Employee_id)" +
                                     " VALUES (@TransactionTime, @CustomerId, @EmployeeId)";

            var connection = new MySqlConnection(this.CONNECTION_STRING);

            using (var command = new MySqlCommand(statement))
            {
                command.Parameters.AddWithValue("@TransactionTime", item.TransactionTime);
                command.Parameters.AddWithValue("@CustomerId", item.CustomerId);
                command.Parameters.AddWithValue("@EmployeeId", item.EmployeeId);

                command.Connection = connection;

                try
                {
                    command.Connection.Open();
                    command.ExecuteNonQuery();
                    id = command.LastInsertedId.ToString();
                }
                finally
                {
                    command.Connection.Close();
                }
            }

            return(id);
        }
예제 #34
0
        private static void RecordEditedPurchaseTransactionLedgerTransactionsInDatabaseContext(ERPContext context, PurchaseTransaction editedPurchaseTransaction)
        {
            var transactionFromDatabase = context.PurchaseTransactions
                .Include("PurchaseTransactionLines")
                .Include("PurchaseTransactionLines.Item")
                .Include("PurchaseTransactionLines.Warehouse")
                .Single(e => e.PurchaseID.Equals(editedPurchaseTransaction.PurchaseID));

            if (transactionFromDatabase.Total != editedPurchaseTransaction.Total)
            {
                var valueChanged = editedPurchaseTransaction.Total - transactionFromDatabase.Total;
                RecordEditedPurchaseTransactionNetTotalChangedLedgerTransactionInDatabaseContext(context, editedPurchaseTransaction, valueChanged);
            }

            var transactionFromDatabaseTotalCOGS = CalculatePurchaseTransactionTotalCOGS(transactionFromDatabase);
            var editedtransactionTotalCOGS = CalculatePurchaseTransactionTotalCOGS(editedPurchaseTransaction);
            var totalCOGSChanged = editedtransactionTotalCOGS - transactionFromDatabaseTotalCOGS;
            if (totalCOGSChanged != 0)
                RecordEditedPurchaseTransactionTotalCOGSChangedLedgerTransactionInDatabaseContext(context, editedPurchaseTransaction, totalCOGSChanged);
        }
예제 #35
0
 private static void AddLineToStockAdjustmentPurchaseTransaction(StockAdjustmentTransactionLine line, PurchaseTransaction stockAdjustmentPurchaseTransaction)
 {
     var stockAdjustmentPurchaseLine = new PurchaseTransactionLine
     {
         PurchaseTransaction = stockAdjustmentPurchaseTransaction,
         Item = line.Item,
         Warehouse = line.Warehouse,
         PurchasePrice = 0,
         Discount = 0,
         Quantity = line.Quantity,
         Total = 0,
         SoldOrReturned = 0
     };
     stockAdjustmentPurchaseTransaction.PurchaseTransactionLines.Add(stockAdjustmentPurchaseLine);
 }
예제 #36
0
 private static void AttachPurchaseTransactionPropertiesToDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction)
 {
     purchaseTransaction.Supplier = context.Suppliers.Single(supplier => supplier.ID.Equals(purchaseTransaction.Supplier.ID));
     var currentUser = Application.Current.TryFindResource("CurrentUser") as User;
     if (currentUser != null)
         purchaseTransaction.User = context.Users.Single(user => user.Username.Equals(currentUser.Username));
     context.PurchaseTransactions.Add(purchaseTransaction);
     context.SaveChanges();
 }
예제 #37
0
 private void AssignSelectedPurchaseTransactionPropertiesToUI(PurchaseTransaction purchaseTransaction)
 {
     SelectedPurchaseLines.Clear();
     foreach (var lineVM in purchaseTransaction.PurchaseTransactionLines.Select(line => new PurchaseTransactionLineVM { Model = line }))
         SelectedPurchaseLines.Add(lineVM);   
     PurchaseTransactionGrossTotal = purchaseTransaction.GrossTotal;
     PurchaseTransactionDiscount = purchaseTransaction.Discount;
     PurchaseTransactionTax = purchaseTransaction.Tax;
     PurchaseTransactionTotal = purchaseTransaction.Total;
     Remaining = purchaseTransaction.Total - purchaseTransaction.Paid;
 }
예제 #38
0
        private static void RecordEditedPurchaseTransactionNetTotalChangedLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal valueChanged)
        {
            var purchaseTransactionNetTotalChangedLedgerTransaction = new LedgerTransaction();

            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment");
            context.SaveChanges();

            if (valueChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction, "Inventory",
                    "Debit", valueChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                    $"{editedPurchaseTransaction.Supplier.Name} Accounts Payable", "Credit", valueChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction,
                    $"{editedPurchaseTransaction.Supplier.Name} Accounts Payable", "Debit", -valueChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionNetTotalChangedLedgerTransaction, "Inventory",
                    "Credit", -valueChanged);
            }
            context.SaveChanges();
        }
예제 #39
0
 private static decimal CalculatePurchaseTransactionTotalCOGS(PurchaseTransaction purchaseTransaction)
 {
     var totalCOGS = 0m;
     foreach (var line in purchaseTransaction.PurchaseTransactionLines)
     {
         if (line.SoldOrReturned <= 0) continue;
         var lineNetTotal = line.PurchasePrice - line.Discount;
         if (lineNetTotal == 0) continue;
         var lineFractionOfTransactionDiscount = line.SoldOrReturned * lineNetTotal /
                                                 purchaseTransaction.GrossTotal * purchaseTransaction.Discount;
         var lineFractionOfTransactionTax = line.SoldOrReturned * lineNetTotal /
                                            purchaseTransaction.GrossTotal * purchaseTransaction.Tax;
         var lineCOGS = line.SoldOrReturned * lineNetTotal - lineFractionOfTransactionDiscount +
                        lineFractionOfTransactionTax;
         totalCOGS += lineCOGS;
     }
     return totalCOGS;
 }
예제 #40
0
        private static void RecordEditedPurchaseTransactionTotalCOGSChangedLedgerTransactionInDatabaseContext(
            ERPContext context, PurchaseTransaction editedPurchaseTransaction, decimal totalCOGSChanged)
        {
            var purchaseTransactionTotalCOGSChangedLedgerTransaction = new LedgerTransaction();
            LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, UtilityMethods.GetCurrentDate().Date, editedPurchaseTransaction.PurchaseID, "Purchase Transaction Adjustment (COGS)");
            context.SaveChanges();

            if (totalCOGSChanged > 0)
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Debit", totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Credit", totalCOGSChanged);
            }
            else
            {
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Inventory", "Debit", -totalCOGSChanged);
                LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseTransactionTotalCOGSChangedLedgerTransaction, "Cost of Goods Sold", "Credit", -totalCOGSChanged);
            }
            context.SaveChanges();
        }
예제 #41
0
        private static void SetPurchaseTransactionInDatabaseContextToEditedPurchaseTransactionProperties(ERPContext context, PurchaseTransaction editedPurchaseTransaction)
        {
            var transactionFromDatabase = context.PurchaseTransactions
                .Include("Supplier")
                .Include("PurchaseTransactionLines")
                .Include("PurchaseTransactionLines.Item")
                .Include("PurchaseTransactionLines.Warehouse")
                .Single(e => e.PurchaseID.Equals(editedPurchaseTransaction.PurchaseID));

            transactionFromDatabase.Date = editedPurchaseTransaction.Date;
            transactionFromDatabase.DueDate = editedPurchaseTransaction.DueDate;
            transactionFromDatabase.DOID = editedPurchaseTransaction.DOID;
            transactionFromDatabase.Note = editedPurchaseTransaction.Note;
            transactionFromDatabase.Tax = editedPurchaseTransaction.Tax;
            transactionFromDatabase.GrossTotal = editedPurchaseTransaction.GrossTotal;
            transactionFromDatabase.Discount = editedPurchaseTransaction.Discount;
            transactionFromDatabase.Total = editedPurchaseTransaction.Total;
            var currentUser = Application.Current.TryFindResource("CurrentUser") as User;
            if (currentUser != null)
                transactionFromDatabase.User = context.Users.Single(user => user.Username.Equals(currentUser.Username));

            foreach (var line in transactionFromDatabase.PurchaseTransactionLines.ToList())
            {
                context.PurchaseTransactionLines.Remove(line);
                context.SaveChanges();
            }

            foreach (var editedLine in editedPurchaseTransaction.PurchaseTransactionLines)
            {
                editedLine.PurchaseTransaction = transactionFromDatabase;
                editedLine.Item = context.Inventory.Single(item => item.ID.Equals(editedLine.Item.ID));
                editedLine.Warehouse = context.Warehouses.Single(warehouse => warehouse.ID.Equals(editedLine.Warehouse.ID));
                context.PurchaseTransactionLines.Add(editedLine);
                context.SaveChanges();
            }

            context.SaveChanges();
        }
예제 #42
0
        private static void RecordPaymentLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction, decimal paymentAmount, string paymentMode)
        {
            var accountsPayableName = purchaseTransaction.Supplier.Name + " Accounts Payable";
            var paymentLedgerTransaction = new LedgerTransaction();

            if (!LedgerTransactionHelper.AddTransactionToDatabase(context, paymentLedgerTransaction, UtilityMethods.GetCurrentDate().Date, purchaseTransaction.PurchaseID, "Purchase Payment")) return;
            context.SaveChanges();

            LedgerTransactionHelper.AddTransactionLineToDatabase(context, paymentLedgerTransaction, accountsPayableName, "Debit", paymentAmount);
            LedgerTransactionHelper.AddTransactionLineToDatabase(context, paymentLedgerTransaction, paymentMode, "Credit", paymentAmount);
            context.SaveChanges();
        }
예제 #43
0
 private static void RecordPurchaseLedgerTransactionInDatabaseContext(ERPContext context, PurchaseTransaction purchaseTransaction)
 {
     var purchaseLedgerTransaction = new LedgerTransaction();
     var accountsPayableName = purchaseTransaction.Supplier.Name + " Accounts Payable";
     if (!LedgerTransactionHelper.AddTransactionToDatabase(context, purchaseLedgerTransaction, UtilityMethods.GetCurrentDate().Date, purchaseTransaction.PurchaseID, "Purchase Transaction")) return;
     context.SaveChanges();
     LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseLedgerTransaction, "Inventory", "Debit", purchaseTransaction.Total);
     LedgerTransactionHelper.AddTransactionLineToDatabase(context, purchaseLedgerTransaction, accountsPayableName, "Credit", purchaseTransaction.Total);
     context.SaveChanges();
 }