Пример #1
0
        public async Task <IActionResult> Edit(string id, [Bind("vendorInvoiceId,invoiceNumber,originalInvoiceNumber,invoiceDate,invoiceReference,dueDate,myCompanyId,vendorId,note,termsAndCondition,subTotal,taxAmount,discount,shipping,grandTotal,isPaid,HasChild,createdAt")] VendorInvoice vendorInvoice)
        {
            if (id != vendorInvoice.vendorInvoiceId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(vendorInvoice);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!VendorInvoiceExists(vendorInvoice.vendorInvoiceId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["myCompanyId"] = new SelectList(_context.MyCompany, "myCompanyId", "companyName", vendorInvoice.myCompanyId);
            ViewData["vendorId"]    = new SelectList(_context.Vendor, "vendorId", "vendorName", vendorInvoice.vendorId);
            return(View(vendorInvoice));
        }
        private bool isInputValid()
        {
            if (itxt_InvoiceNo.isEmpty())
            {
                return(itxt_InvoiceNo.isValueError("Invalid Invoice No"));
            }
            else if (VendorInvoice.isInvoiceNoExist(_vendorInvoice.ID, itxt_InvoiceNo.ValueText))
            {
                return(itxt_InvoiceNo.isValueError("Invoice No already exists"));
            }

            if (_fakturPajak != null) //edit assigned FP
            {
                if (itxt_FakturPajak_No.isEmpty())
                {
                    return(itxt_FakturPajak_No.isValueError("Please provide No"));
                }
                else if (FakturPajak.isNoExist(_fakturPajak.Id, itxt_FakturPajak_No.ValueText))
                {
                    return(itxt_FakturPajak_No.isValueError("FP No already exists"));
                }
            }
            else if (!itxt_FakturPajak_No.isEmpty()) //add new FP
            {
                if (FakturPajak.isNoExist(null, itxt_FakturPajak_No.ValueText))
                {
                    return(itxt_FakturPajak_No.isValueError("FP No already exists"));
                }
            }

            return(true);
        }
Пример #3
0
 private void gridvendorinvoice_CellContentClick(object sender, DataGridViewCellEventArgs e)
 {
     if (Tools.isCorrectColumn(sender, e, typeof(DataGridViewLinkColumn), col_gridvendorinvoice_PayableAmount.Name))
     {
         var form = new Invoices.Payment_Form(typeof(VendorInvoice), new Guid(gridvendorinvoice.Rows[e.RowIndex].Cells[col_gridvendorinvoice_id.Name].Value.ToString()));
         Tools.displayForm(form);
         if (form.DialogResult == DialogResult.OK)
         {
             populateGridVendorInvoices();
         }
     }
     else if (Util.isColumnMatch(sender, e, col_gridVendorInvoice_TogglePayment))
     {
         decimal value = Util.wrapNullable <decimal>(Util.getClickedRowValue(sender, e, col_gridVendorInvoice_PaymentAmount));
         if (value != 0)
         {
             value = 0;
         }
         else
         {
             value = Util.wrapNullable <decimal>(Util.getClickedRowValue(sender, e, col_gridvendorinvoice_PayableAmount));
         }
         Util.setRowValue(sender, e, col_gridVendorInvoice_PaymentAmount, value);
     }
     else if (Util.isColumnMatch(sender, e, col_gridVendorInvoice_PaidAmount))
     {
         VendorInvoicePayments_Form form = (VendorInvoicePayments_Form)Util.displayMDIChild(new VendorInvoicePayments_Form());
         form.searchVendorInvoiceNo(Util.getClickedRowValue(sender, e, col_gridvendorinvoice_invoiceno).ToString());
     }
     else if (Util.isColumnMatch(sender, e, col_gridVendorInvoices_Approved))
     {
         VendorInvoice.update_Approved(Util.getClickedRowValue <Guid>(sender, e, col_gridvendorinvoice_id), !Util.getCheckboxValue(sender, e));
         populateGridVendorInvoices();
     }
 }
Пример #4
0
        private void setupControls()
        {
            Settings.setGeneralSettings(this);

            Grade.populateDropDownList(cbGrades, false, true);
            ProductWidth.populateDropDownList(cbProductWidths, false, true);
            LengthUnit.populateDropDownList(cbLengthUnits, false, true);
            FabricColor.populateDropDownList(cbColors, false, true);
            VendorInvoice.populateDropDownList(cbVendorInvoices, true);

            //set window title
            switch (_formMode)
            {
            case FormMode.New:
                this.Text       = "ADD NEW INVENTORY";
                lblCode.Visible = false;
                txtCode.Visible = false;
                break;

            case FormMode.Update:
                this.Text = "UPDATE INVENTORY";
                break;
            }

            if (GlobalData.UserAccount.role == Roles.User)
            {
                lblBuyPrice.Visible = false;
                txtBuyPrice.Visible = false;
                this.Height        -= 60;
            }
        }
Пример #5
0
        public void populateGridVendorInvoices()
        {
            DataView dvw;

            gridvendorinvoice.AutoGenerateColumns = false; //the line in setupControls() is not working??
            if (_startingMode == FormModes.Browse)
            {
                dvw = VendorInvoice.get_by_BrowsingForFakturPajak_Vendors_Id((Guid)_BrowsingForFakturPajak_Vendors_Id, chkShowOnlyLast6Months.Checked).DefaultView;
            }
            else if (_createVendorInvoicePayment)
            {
                dvw = VendorInvoice.get(null, null, (Guid)iddl_Vendors.SelectedValue, chkShowOnlyIncomplete.Checked, chkShowOnlyVendorUsesFakturPajak.Checked, chkShowOnlyLast6Months.Checked, null, null, false).DefaultView;
            }
            else
            {
                dvw = VendorInvoice.get(null, null, null, chkShowOnlyIncomplete.Checked, chkShowOnlyVendorUsesFakturPajak.Checked, chkShowOnlyLast6Months.Checked, null, null, false).DefaultView;
            }

            string[] fieldNames = { VendorInvoice.COL_VendorName, VendorInvoice.COL_VendorName };
            dvw.RowFilter = Util.compileQuickSearchFilter(itxt_QuickSearch.ValueText, fieldNames);
            Util.setGridviewDataSource(gridvendorinvoice, dvw);

            createVendorInvoicePaymentMode(_createVendorInvoicePayment);
            calculateGrandTotalPayableAmount();

            pbLog.Enabled = gridvendorinvoice.Rows.Count > 0;
        }
Пример #6
0
        internal static async Task CreateVendorInvoiceRecord(int id, string regNumber, string cHECK, string iNVOICE_NUMBER, DateTime?dATE_PAID, int superServiceOrderId)
        {
            Console.WriteLine($"Adding Vendor Invoice Record for {regNumber}");
            Trace.WriteLine($"{regNumber}, , Adding Vendor Invoice Record ");

            using (var context = new JobDbContext(connectionString))
            {
                var vendorInvoice = new VendorInvoice
                {
                    SuperServiceOrderId = superServiceOrderId,
                    VendorInvoiceNumber = iNVOICE_NUMBER,
                    LastPaidDate        = dATE_PAID.GetValueOrDefault(),
                    GPDocNum            = "Migration",
                    LastPaidCheckNumber = cHECK,
                    VendorInvoiceDate   = dATE_PAID.GetValueOrDefault(DateTime.UtcNow)
                };

                context.VendorInvoice.Add(vendorInvoice);
                context.SaveChanges();

                var piEntity = context.PayableItem.Find(id);
                piEntity.VendorInvoiceId = vendorInvoice.Id;
                context.SaveChanges();
            }
        }
        public async Task <IActionResult> PutVendorInvoice([FromRoute] int id, [FromBody] VendorInvoice vendorInvoice)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != vendorInvoice.VendorInvoiceId)
            {
                return(BadRequest());
            }

            _context.Entry(vendorInvoice).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!VendorInvoiceExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(AcceptedAtAction("GetVendorInvoice", vendorInvoice));
        }
 private void GridVendorInvoices_CellContentClick(object sender, DataGridViewCellEventArgs e)
 {
     if (Util.isColumnMatch(sender, e, col_gridVendorInvoices_removeFakturPajaks_Id))
     {
         VendorInvoice.update_FakturPajaks_Id((Guid)Util.getSelectedRowValue(sender, col_gridvendorinvoice_id), null);
         populateGridVendorInvoices(true);
     }
 }
Пример #9
0
 private void btnAddVendorInvoice_Click(object sender, EventArgs e)
 {
     if (Tools.displayForm(new InventoryForm.VendorInvoices_Add_Form()))
     {
         VendorInvoice.populateDropDownList(cbVendorInvoices, true);
         cbVendorInvoices.SelectedIndex = 0;
     }
 }
 private void btnSubmit_Click(object sender, EventArgs e)
 {
     if (isInputValid())
     {
         VendorInvoice.add(itxt_VendorInvoices_No.ValueText, (Guid)iddl_Vendors.SelectedValue);
         this.DialogResult = DialogResult.OK;
         this.Close();
     }
 }
Пример #11
0
        public async Task <IActionResult> PostVendorInvoiceLine([FromBody] VendorInvoiceLine vendorInvoiceLine)
        {
            Item item = await _context.Item.Include(x => x.tax).SingleOrDefaultAsync(x => x.itemId.Equals(vendorInvoiceLine.itemId));

            vendorInvoiceLine.taxId = item.taxId;


            if (vendorInvoiceLine.vendorInvoiceLineId == string.Empty)
            {
                vendorInvoiceLine.vendorInvoiceLineId = Guid.NewGuid().ToString();

                if (vendorInvoiceLine.price.Equals(0m))
                {
                    vendorInvoiceLine.price = item.price;
                }
                vendorInvoiceLine.amount      = (decimal)vendorInvoiceLine.quantity * vendorInvoiceLine.price;
                vendorInvoiceLine.taxAmount   = (decimal)(item.tax.taxRate / 100.0) * vendorInvoiceLine.amount;
                vendorInvoiceLine.totalAmount = vendorInvoiceLine.amount + vendorInvoiceLine.taxAmount;
                _context.VendorInvoiceLine.Add(vendorInvoiceLine);

                VendorInvoice vi = await _context.VendorInvoice.Include(x => x.vendorInvoiceLine).SingleOrDefaultAsync(x => x.vendorInvoiceId.Equals(vendorInvoiceLine.vendorInvoiceId));

                vi.subTotal   = vi.vendorInvoiceLine.Sum(x => x.amount);
                vi.taxAmount  = vi.vendorInvoiceLine.Sum(x => x.taxAmount);
                vi.grandTotal = vi.subTotal + vi.taxAmount - vi.discount + vi.shipping;
                _context.VendorInvoice.Update(vi);

                _context.VendorInvoiceLine.Add(vendorInvoiceLine);
                await _context.SaveChangesAsync();

                return(Json(new { success = true, message = "Add new data success." }));
            }
            else
            {
                if (vendorInvoiceLine.price.Equals(0m))
                {
                    vendorInvoiceLine.price = item.price;
                }
                vendorInvoiceLine.amount      = (decimal)vendorInvoiceLine.quantity * vendorInvoiceLine.price;
                vendorInvoiceLine.taxAmount   = (decimal)(item.tax.taxRate / 100.0) * vendorInvoiceLine.amount;
                vendorInvoiceLine.totalAmount = vendorInvoiceLine.amount + vendorInvoiceLine.taxAmount;
                _context.Update(vendorInvoiceLine);

                VendorInvoice vi = await _context.VendorInvoice.Include(x => x.vendorInvoiceLine).SingleOrDefaultAsync(x => x.vendorInvoiceId.Equals(vendorInvoiceLine.vendorInvoiceId));

                vi.subTotal   = vi.vendorInvoiceLine.Sum(x => x.amount);
                vi.taxAmount  = vi.vendorInvoiceLine.Sum(x => x.taxAmount);
                vi.grandTotal = vi.subTotal + vi.taxAmount - vi.discount + vi.shipping;
                _context.VendorInvoice.Update(vi);

                _context.Update(vendorInvoiceLine);
                await _context.SaveChangesAsync();

                return(Json(new { success = true, message = "Edit data success." }));
            }
        }
Пример #12
0
        // GET: VendorInvoice/Create
        public IActionResult Create()
        {
            ViewData["myCompanyId"] = new SelectList(_context.MyCompany, "myCompanyId", "companyName");
            ViewData["vendorId"]    = new SelectList(_context.Vendor, "vendorId", "vendorName");
            VendorInvoice obj = new VendorInvoice();

            obj.invoiceDate = DateTime.UtcNow.Date;
            obj.dueDate     = obj.invoiceDate.AddMonths(1).Date;
            return(View(obj));
        }
        private void populateGridVendorInvoices(bool repopulateGridFakturPajak)
        {
            DataTable data = VendorInvoice.get_by_FakturPajaks_Id(selectedRowID());

            Util.setGridviewDataSource(gridVendorInvoices, false, false, data);
            tpVendorInvoices.Text = string.Format("{0}: {1:N2}", TABTITLE_VendorInvoices, Util.compute(data, "SUM", VendorInvoice.COL_DB_Amount, ""));
            if (repopulateGridFakturPajak)
            {
                populateGridViewDataSource(true);
            }
        }
Пример #14
0
        private VendorInvoice GetInvoice(VendorInvoice invoice)
        {
            var newInvoice = new VendorInvoice
            {
                Amount      = invoice.Amount,
                Comments    = invoice.Comments,
                InvoiceDate = invoice.InvoiceDate
            };

            return(newInvoice);
        }
Пример #15
0
        public static CreateVendorInvoiceResponse ToCreateVendorInvoiceResponse(VendorInvoice entity)
        {
            int vendorId = 0;

            var response = new CreateVendorInvoiceResponse()
            {
                SuperServiceName = entity.SuperServiceOrder.SuperService?.SuperServiceName,
                DisplayId        = entity.SuperServiceOrder.DisplayId
            };

            //TODO: FIX ME BY FIXING THE LINQ QUERY>GetJobsForSearchIndexAsync
            switch (entity.BillFromType.ToUpper())
            {
            case EntityType.ACCOUNT_ENTITY:
                vendorId = entity.BillFromAccountEntityId.GetValueOrDefault();

                response.BillFromType       = EntityType.ACCOUNT_ENTITY;
                response.BillFromId         = entity.BillFromAccountEntityId;
                response.BillFromName       = entity.BillFromAccountEntity?.Name;
                response.VendorAccountingId = entity.BillFromAccountEntity?.AccountingId;
                response.VendorShortAddress = entity.BillFromAccountEntity.ShortAddress;

                break;

            case EntityType.VENDOR:
                vendorId = entity.BillFromVendorId.GetValueOrDefault();

                response.BillFromType       = EntityType.VENDOR;
                response.BillFromId         = entity.BillFromVendorId;
                response.BillFromName       = entity.BillFromVendor?.Name;
                response.VendorAccountingId = entity.BillFromVendor?.Accounting_SI_Code;
                response.VendorShortAddress = entity.BillFromVendor?.ShortAddress;

                break;

            case EntityType.TRANSFEREE:
                vendorId = entity.BillFromTransfereeId.GetValueOrDefault();
                response.BillFromType       = EntityType.TRANSFEREE;
                response.BillFromId         = entity.BillFromTransfereeId;
                response.BillFromName       = string.Concat(entity.BillFromTransferee?.FirstName, " ", entity.BillFromTransferee?.LastName);
                response.VendorAccountingId = entity.BillFromTransferee?.AccountingId.ToString();
                response.VendorShortAddress = ToShortAddress(entity.SuperServiceOrder.Job.OriginAddress);
                break;
            }

            response.ServiceOrderId = entity.SuperServiceOrder.Job.ServiceOrder
                                      .FirstOrDefault(s => s.SuperServiceOrderId == entity.SuperServiceOrderId && (
                                                          s.ServiceId == ServiceId.AIR_JC ||
                                                          s.ServiceId == ServiceId.OCEAN_JC ||
                                                          s.ServiceId == ServiceId.ROAD_JC ||
                                                          s.ServiceId == ServiceId.STORAGE_JC)).Id;

            return(response);
        }
        public VendorInvoices_Edit_Form(Guid id)
        {
            InitializeComponent();

            _vendorInvoice = new VendorInvoice(id);
            if (_vendorInvoice.FakturPajaks_Id != null)
            {
                _fakturPajak = new FakturPajak(_vendorInvoice.FakturPajaks_Id);
            }
            btnRemoveFakturPajakFromVendorInvoice.Enabled = (_vendorInvoice.FakturPajaks_Id != null);
        }
        public async Task <IActionResult> PostVendorInvoice([FromBody] VendorInvoice vendorInvoice)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.Invoices.Add(vendorInvoice);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetVendorInvoice", new { id = vendorInvoice.VendorInvoiceId }, vendorInvoice));
        }
Пример #18
0
        public async Task <IActionResult> Create([Bind("vendorInvoiceId,invoiceNumber,originalInvoiceNumber,invoiceDate,invoiceReference,dueDate,myCompanyId,vendorId,note,termsAndCondition,subTotal,taxAmount,discount,shipping,grandTotal,isPaid,HasChild,createdAt")] VendorInvoice vendorInvoice)
        {
            if (ModelState.IsValid)
            {
                _context.Add(vendorInvoice);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["myCompanyId"] = new SelectList(_context.MyCompany, "myCompanyId", "companyName", vendorInvoice.myCompanyId);
            ViewData["vendorId"]    = new SelectList(_context.Vendor, "vendorId", "vendorName", vendorInvoice.vendorId);
            return(View(vendorInvoice));
        }
Пример #19
0
        /*******************************************************************************************************/
        #region CONSTRUCTOR METHODS

        public Payment_Form(Type type, Guid id)
        {
            InitializeComponent();

            if (type == typeof(VendorInvoice))
            {
                _vendorInvoice = new VendorInvoice(id);
                _paymentMode   = PaymentMode.VendorInvoice;
            }
            else if (type == typeof(Sale))
            {
                _sale        = new Sale(id);
                _paymentMode = PaymentMode.SaleInvoice;
            }
        }
        private bool isInputValid()
        {
            if (itxt_VendorInvoices_No.isEmpty())
            {
                return(itxt_VendorInvoices_No.isValueError("Invalid Invoice number"));
            }
            else if (!iddl_Vendors.isValidSelectedValue())
            {
                return(iddl_Vendors.SelectedValueError("Invalid Vendor"));
            }
            else if (VendorInvoice.isInvoiceNoExist(null, itxt_VendorInvoices_No.ValueText))
            {
                return(itxt_VendorInvoices_No.isValueError("Invoice number already exists"));
            }

            return(true);
        }
Пример #21
0
        public async Task <IActionResult> GetVendorInvoiceById(Int64 VendorInvoiceId)
        {
            VendorInvoice Items = new VendorInvoice();

            try
            {
                Items = await _context.VendorInvoice.Where(q => q.VendorInvoiceId == VendorInvoiceId).FirstOrDefaultAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(BadRequest($"Ocurrio un error:{ex.Message}"));
            }


            return(await Task.Run(() => Ok(Items)));
        }
 private void BtnRemoveFakturPajakFromVendorInvoice_Click(object sender, EventArgs e)
 {
     if (Util.displayMessageBoxYesNo("Remove FP connection to this Invoice? FP is NOT deleted"))
     {
         VendorInvoice.update_FakturPajaks_Id(_vendorInvoice.ID, null);
         _vendorInvoice = new VendorInvoice(_vendorInvoice.ID);
         if (_vendorInvoice.FakturPajaks_Id == null)
         {
             _fakturPajak = null;
         }
         else
         {
             _fakturPajak = new FakturPajak(_vendorInvoice.FakturPajaks_Id);
         }
         btnRemoveFakturPajakFromVendorInvoice.Enabled = (_vendorInvoice.FakturPajaks_Id != null);
         populateFakturPajak();
     }
 }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (isInputValid())
            {
                VendorInvoice.update(_vendorInvoice.ID, (DateTime)idtp_Timestamp.ValueAsStartDateFilter, itxt_InvoiceNo.ValueText, in_Amount.ValueDecimal, in_TOP.ValueInt, itxt_Notes.ValueText);

                if (_fakturPajak != null) //edit assigned FP
                {
                    FakturPajak.update(_fakturPajak.Id, (DateTime)idtp_Timestamp.ValueAsStartDateFilter, null, _vendorInvoice.Vendors_Id, itxt_FakturPajak_No.ValueText, in_FakturPajak_DPP.ValueDecimal, in_FakturPajak_PPN.ValueDecimal, itxt_FakturPajak_Notes.ValueText);
                }
                else if (!itxt_FakturPajak_No.isEmpty()) //add new FP
                {
                    Guid FakturPajaks_Id = FakturPajak.add((DateTime)idtp_Timestamp.ValueAsStartDateFilter, null, _vendorInvoice.Vendors_Id, itxt_FakturPajak_No.ValueText, in_FakturPajak_DPP.ValueDecimal, in_FakturPajak_PPN.ValueDecimal, itxt_FakturPajak_Notes.ValueText);
                    VendorInvoice.update_FakturPajaks_Id(_vendorInvoice.ID, FakturPajaks_Id);
                }

                this.Close();
            }
        }
Пример #24
0
        public async Task <IActionResult> Delete([FromBody] VendorInvoice _VendorInvoice)
        {
            VendorInvoice _VendorInvoiceq = new VendorInvoice();

            try
            {
                _VendorInvoiceq = _context.VendorInvoice
                                  .Where(x => x.VendorInvoiceId == (Int64)_VendorInvoice.VendorInvoiceId)
                                  .FirstOrDefault();

                _context.VendorInvoice.Remove(_VendorInvoiceq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}")));
            }

            return(await Task.Run(() => Ok(_VendorInvoiceq)));
        }
 private void BtnAddVendorInvoices_Click(object sender, EventArgs e)
 {
     if (_lastSelectedFakturPajaks_Id == null)
     {
         Util.displayMessageBoxError("Double click faktur pajak");
     }
     else
     {
         if (!Util.selectedItemIsNotNull(dgv, col_dgv_Vendors_Id))
         {
             Util.displayMessageBoxError("Invalid Vendor");
         }
         else
         {
             InventoryForm.VendorInvoices_Form form = new InventoryForm.VendorInvoices_Form(FormModes.Browse, (Guid)Util.getSelectedRowValue(dgv, col_dgv_Vendors_Id));
             Util.displayForm(null, form);
             if (form.DialogResult == DialogResult.OK)
             {
                 VendorInvoice.update_FakturPajaks_Id(form.BrowsedItemSelectionId, _lastSelectedFakturPajaks_Id);
                 populateGridVendorInvoices(true);
             }
         }
     }
 }
Пример #26
0
        public async Task <ActionResult <VendorInvoice> > Update([FromBody] VendorInvoice _VendorInvoice)
        {
            VendorInvoice _VendorInvoiceq = _VendorInvoice;

            try
            {
                _VendorInvoiceq = await(from c in _context.VendorInvoice
                                        .Where(q => q.VendorInvoiceId == _VendorInvoice.VendorInvoiceId)
                                        select c
                                        ).FirstOrDefaultAsync();

                _context.Entry(_VendorInvoiceq).CurrentValues.SetValues((_VendorInvoice));

                //_context.VendorInvoice.Update(_VendorInvoiceq);
                await _context.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                return(await Task.Run(() => BadRequest($"Ocurrio un error:{ex.Message}")));
            }

            return(await Task.Run(() => Ok(_VendorInvoiceq)));
        }
Пример #27
0
        public async Task <ActionResult <VendorInvoice> > Insert([FromBody] VendorInvoice pVendorInvoice)
        {
            VendorInvoice _VendorInvoiceq = new VendorInvoice();

            _VendorInvoiceq = pVendorInvoice;
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    _VendorInvoiceq.PurchaseOrderId = null;
                    //_VendorInvoiceq.Sucursal = await _context.Branch.Where(q => q.BranchId == _VendorInvoiceq.BranchId).Select(q => q.BranchCode).FirstOrDefaultAsync();
                    Numalet let;
                    let = new Numalet();
                    let.SeparadorDecimalSalida  = "Lempiras";
                    let.MascaraSalidaDecimal    = "00/100 ";
                    let.ApocoparUnoParteEntera  = true;
                    _VendorInvoiceq.TotalLetras = let.ToCustomCardinal((_VendorInvoiceq.Total)).ToUpper();

                    _context.VendorInvoice.Add(_VendorInvoiceq);
                    //await _context.SaveChangesAsync();

                    JournalEntry _je = new JournalEntry
                    {
                        Date         = _VendorInvoiceq.VendorInvoiceDate,
                        Memo         = "Factura de Compra a Proveedores",
                        DatePosted   = _VendorInvoiceq.VendorInvoiceDate,
                        ModifiedDate = DateTime.Now,
                        CreatedDate  = DateTime.Now,
                        ModifiedUser = _VendorInvoiceq.UsuarioModificacion,
                        CreatedUser  = _VendorInvoiceq.UsuarioCreacion,
                        DocumentId   = _VendorInvoiceq.VendorInvoiceId,
                    };

                    Accounting account = await _context.Accounting.Where(acc => acc.AccountId == _VendorInvoiceq.AccountId).FirstOrDefaultAsync();

                    _je.JournalEntryLines.Add(new JournalEntryLine
                    {
                        AccountId = Convert.ToInt32(_VendorInvoiceq.AccountId),
                        //Description = _VendorInvoiceq.Account.AccountName,
                        Description  = account.AccountName,
                        Credit       = 0,
                        Debit        = _VendorInvoiceq.Total,
                        CreatedDate  = DateTime.Now,
                        ModifiedDate = DateTime.Now,
                        CreatedUser  = _VendorInvoiceq.UsuarioCreacion,
                        ModifiedUser = _VendorInvoiceq.UsuarioModificacion,
                        Memo         = "",
                    });
                    foreach (var item in _VendorInvoiceq.VendorInvoiceLine)
                    {
                        account = await _context.Accounting.Where(acc => acc.AccountId == _VendorInvoiceq.AccountId).FirstOrDefaultAsync();

                        item.VendorInvoiceId = _VendorInvoiceq.VendorInvoiceId;
                        _context.VendorInvoiceLine.Add(item);
                        _je.JournalEntryLines.Add(new JournalEntryLine
                        {
                            AccountId    = Convert.ToInt32(item.AccountId),
                            Description  = account.AccountName,
                            Credit       = item.Total,
                            Debit        = 0,
                            CreatedDate  = DateTime.Now,
                            ModifiedDate = DateTime.Now,
                            CreatedUser  = _VendorInvoiceq.UsuarioCreacion,
                            ModifiedUser = _VendorInvoiceq.UsuarioModificacion,
                            Memo         = "",
                        });
                    }

                    await _context.SaveChangesAsync();

                    double sumacreditos = 0, sumadebitos = 0;
                    if (sumacreditos != sumadebitos)
                    {
                        transaction.Rollback();
                        _logger.LogError($"Ocurrio un error: No coinciden debitos :{sumadebitos} y creditos{sumacreditos}");
                        return(BadRequest($"Ocurrio un error: No coinciden debitos :{sumadebitos} y creditos{sumacreditos}"));
                    }

                    _je.TotalCredit = sumacreditos;
                    _je.TotalDebit  = sumadebitos;
                    _context.JournalEntry.Add(_je);

                    await _context.SaveChangesAsync();

                    BitacoraWrite _write = new BitacoraWrite(_context, new Bitacora
                    {
                        IdOperacion  = 4,    ///////Falta definir los Id de las Operaciones
                        DocType      = "VendorInvoice",
                        ClaseInicial =
                            Newtonsoft.Json.JsonConvert.SerializeObject(_VendorInvoiceq, new JsonSerializerSettings {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        }),
                        ResultadoSerializado = Newtonsoft.Json.JsonConvert.SerializeObject(_VendorInvoiceq, new JsonSerializerSettings {
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        }),
                        Accion              = "Insert",
                        FechaCreacion       = DateTime.Now,
                        FechaModificacion   = DateTime.Now,
                        UsuarioCreacion     = _VendorInvoiceq.UsuarioCreacion,
                        UsuarioModificacion = _VendorInvoiceq.UsuarioModificacion,
                        UsuarioEjecucion    = _VendorInvoiceq.UsuarioModificacion,
                    });
                    await _context.SaveChangesAsync();

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    _logger.LogError($"Ocurrio un error: { ex.ToString() }");
                    throw ex;
                }
            }


            return(await Task.Run(() => Ok(_VendorInvoiceq)));
        }