public HttpResponseMessage AddFolderMonitoringReceivingReceipt(List <Entities.FolderMonitoringTrnReceivingReceipt> folderMonitoringTrnReceivingReceiptObjects)
        {
            try
            {
                if (folderMonitoringTrnReceivingReceiptObjects.Any())
                {
                    foreach (var folderMonitoringTrnReceivingReceiptObject in folderMonitoringTrnReceivingReceiptObjects)
                    {
                        Boolean isBranchExist          = false,
                                 isSupplierExist       = false,
                                 isTermExist           = false,
                                 isUserExist           = false,
                                 isReceivedBranchExist = false;

                        Int32 POId = 0;

                        var branch = from d in db.MstBranches where d.BranchCode.Equals(folderMonitoringTrnReceivingReceiptObject.BranchCode) select d;
                        if (branch.Any())
                        {
                            isBranchExist = true;
                        }

                        var supplier = from d in db.MstArticles where d.ArticleTypeId == 3 && d.ManualArticleCode.Equals(folderMonitoringTrnReceivingReceiptObject.SupplierCode) && d.IsLocked == true select d;
                        if (supplier.Any())
                        {
                            isSupplierExist = true;
                        }

                        var term = from d in db.MstTerms where d.Term.Equals(folderMonitoringTrnReceivingReceiptObject.Term) select d;
                        if (term.Any())
                        {
                            isTermExist = true;
                        }

                        var user = from d in db.MstUsers where d.UserName.Equals(folderMonitoringTrnReceivingReceiptObject.UserCode) select d;
                        if (user.Any())
                        {
                            isUserExist = true;
                        }

                        if (isBranchExist)
                        {
                            var purchaseOrder = from d in db.TrnPurchaseOrders where d.BranchId == branch.FirstOrDefault().Id&& d.PONumber.Equals(folderMonitoringTrnReceivingReceiptObject.PONumber) && d.IsLocked == true select d;
                            if (purchaseOrder.Any())
                            {
                                POId = purchaseOrder.FirstOrDefault().Id;
                            }
                            else
                            {
                                if (isSupplierExist)
                                {
                                    var defaultPONumber   = "0000000001";
                                    var lastPurchaseOrder = from d in db.TrnPurchaseOrders.OrderByDescending(d => d.Id) where d.BranchId == branch.FirstOrDefault().Id select d;
                                    if (lastPurchaseOrder.Any())
                                    {
                                        var PONumber = Convert.ToInt32(lastPurchaseOrder.FirstOrDefault().PONumber) + 0000000001;
                                        defaultPONumber = FillLeadingZeroes(PONumber, 10);
                                    }

                                    Data.TrnPurchaseOrder newPurchaseOrder = new Data.TrnPurchaseOrder
                                    {
                                        BranchId            = branch.FirstOrDefault().Id,
                                        PONumber            = defaultPONumber,
                                        PODate              = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.PODate),
                                        SupplierId          = supplier.FirstOrDefault().Id,
                                        TermId              = term.FirstOrDefault().Id,
                                        ManualRequestNumber = "NA",
                                        ManualPONumber      = folderMonitoringTrnReceivingReceiptObject.DocumentReference,
                                        DateNeeded          = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.PODateNeeded),
                                        Remarks             = folderMonitoringTrnReceivingReceiptObject.Remarks,
                                        IsClose             = false,
                                        RequestedById       = user.FirstOrDefault().Id,
                                        PreparedById        = user.FirstOrDefault().Id,
                                        CheckedById         = user.FirstOrDefault().Id,
                                        ApprovedById        = user.FirstOrDefault().Id,
                                        Status              = null,
                                        IsCancelled         = false,
                                        IsPrinted           = false,
                                        IsLocked            = true,
                                        CreatedById         = user.FirstOrDefault().Id,
                                        CreatedDateTime     = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.CreatedDateTime),
                                        UpdatedById         = user.FirstOrDefault().Id,
                                        UpdatedDateTime     = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.CreatedDateTime)
                                    };

                                    db.TrnPurchaseOrders.InsertOnSubmit(newPurchaseOrder);
                                    db.SubmitChanges();

                                    POId = newPurchaseOrder.Id;

                                    var item = from d in db.MstArticles where d.ArticleTypeId == 1 && d.ManualArticleCode.Equals(folderMonitoringTrnReceivingReceiptObject.ItemCode) && d.IsLocked == true select d;
                                    if (item.Any())
                                    {
                                        var conversionUnit = from d in db.MstArticleUnits
                                                             where d.ArticleId == item.FirstOrDefault().Id &&
                                                             d.MstUnit.Unit.Equals(folderMonitoringTrnReceivingReceiptObject.Unit)
                                                             select d;

                                        if (conversionUnit.Any())
                                        {
                                            Decimal baseQuantity = folderMonitoringTrnReceivingReceiptObject.Quantity * 1;
                                            if (conversionUnit.FirstOrDefault().Multiplier > 0)
                                            {
                                                baseQuantity = folderMonitoringTrnReceivingReceiptObject.Quantity * (1 / conversionUnit.FirstOrDefault().Multiplier);
                                            }

                                            Decimal baseCost = folderMonitoringTrnReceivingReceiptObject.Amount;
                                            if (baseQuantity > 0)
                                            {
                                                baseCost = folderMonitoringTrnReceivingReceiptObject.Amount / baseQuantity;
                                            }

                                            Data.TrnPurchaseOrderItem newPurchaseOrderItem = new Data.TrnPurchaseOrderItem
                                            {
                                                POId         = POId,
                                                ItemId       = item.FirstOrDefault().Id,
                                                Particulars  = folderMonitoringTrnReceivingReceiptObject.Particulars,
                                                UnitId       = conversionUnit.FirstOrDefault().UnitId,
                                                Quantity     = folderMonitoringTrnReceivingReceiptObject.Quantity,
                                                Cost         = folderMonitoringTrnReceivingReceiptObject.Cost,
                                                Amount       = folderMonitoringTrnReceivingReceiptObject.Amount,
                                                BaseUnitId   = item.FirstOrDefault().UnitId,
                                                BaseQuantity = baseQuantity,
                                                BaseCost     = baseCost
                                            };

                                            db.TrnPurchaseOrderItems.InsertOnSubmit(newPurchaseOrderItem);
                                            db.SubmitChanges();
                                        }
                                    }
                                }
                            }
                        }

                        var receivedBranch = from d in db.MstBranches where d.BranchCode.Equals(folderMonitoringTrnReceivingReceiptObject.ReceivedBranchCode) select d;
                        if (receivedBranch.Any())
                        {
                            isReceivedBranchExist = true;
                        }

                        if (isBranchExist && isSupplierExist && isTermExist && isUserExist && isReceivedBranchExist)
                        {
                            var purchaseOrderItem = from d in db.TrnPurchaseOrderItems
                                                    where d.POId == POId &&
                                                    d.TrnPurchaseOrder.IsLocked == true &&
                                                    d.MstArticle.ManualArticleCode.Equals(folderMonitoringTrnReceivingReceiptObject.ItemCode) &&
                                                    d.MstArticle.IsInventory == true
                                                    select d;

                            if (purchaseOrderItem.Any())
                            {
                                Int32 RRId = 0;

                                var currentReceivingReceipt = from d in db.TrnReceivingReceipts where d.BranchId == branch.FirstOrDefault().Id&& d.ManualRRNumber.Equals(folderMonitoringTrnReceivingReceiptObject.ManualRRNumber) && d.IsLocked == true select d;
                                if (currentReceivingReceipt.Any())
                                {
                                    RRId = currentReceivingReceipt.FirstOrDefault().Id;

                                    var unlockReceivingReceipt = currentReceivingReceipt.FirstOrDefault();
                                    unlockReceivingReceipt.IsLocked        = false;
                                    unlockReceivingReceipt.UpdatedById     = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.UpdatedById;
                                    unlockReceivingReceipt.UpdatedDateTime = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.UpdatedDateTime;
                                    db.SubmitChanges();

                                    inventory.DeleteReceivingReceiptInventory(RRId);
                                    journal.DeleteReceivingReceiptJournal(RRId);
                                }
                                else
                                {
                                    var defaultRRNumber      = "0000000001";
                                    var lastReceivingReceipt = from d in db.TrnReceivingReceipts.OrderByDescending(d => d.Id) where d.BranchId == branch.FirstOrDefault().Id select d;
                                    if (lastReceivingReceipt.Any())
                                    {
                                        var RRNumber = Convert.ToInt32(lastReceivingReceipt.FirstOrDefault().RRNumber) + 0000000001;
                                        defaultRRNumber = FillLeadingZeroes(RRNumber, 10);
                                    }

                                    Data.TrnReceivingReceipt newReceivingReceipt = new Data.TrnReceivingReceipt
                                    {
                                        BranchId          = branch.FirstOrDefault().Id,
                                        RRNumber          = defaultRRNumber,
                                        RRDate            = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.RRDate),
                                        DocumentReference = folderMonitoringTrnReceivingReceiptObject.DocumentReference,
                                        SupplierId        = supplier.FirstOrDefault().Id,
                                        TermId            = term.FirstOrDefault().Id,
                                        Remarks           = folderMonitoringTrnReceivingReceiptObject.Remarks,
                                        ManualRRNumber    = folderMonitoringTrnReceivingReceiptObject.ManualRRNumber,
                                        Amount            = 0,
                                        WTaxAmount        = 0,
                                        PaidAmount        = 0,
                                        AdjustmentAmount  = 0,
                                        BalanceAmount     = 0,
                                        ReceivedById      = user.FirstOrDefault().Id,
                                        PreparedById      = user.FirstOrDefault().Id,
                                        CheckedById       = user.FirstOrDefault().Id,
                                        ApprovedById      = user.FirstOrDefault().Id,
                                        Status            = null,
                                        IsCancelled       = false,
                                        IsPrinted         = false,
                                        IsLocked          = false,
                                        CreatedById       = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.CreatedById,
                                        CreatedDateTime   = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.CreatedDateTime,
                                        UpdatedById       = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.UpdatedById,
                                        UpdatedDateTime   = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.UpdatedDateTime
                                    };

                                    db.TrnReceivingReceipts.InsertOnSubmit(newReceivingReceipt);
                                    db.SubmitChanges();

                                    RRId = newReceivingReceipt.Id;
                                }

                                var unitConversion = from d in purchaseOrderItem.FirstOrDefault().MstArticle.MstArticleUnits where d.UnitId == purchaseOrderItem.FirstOrDefault().MstArticle.UnitId select d;
                                if (unitConversion.Any())
                                {
                                    Decimal baseQuantity = folderMonitoringTrnReceivingReceiptObject.Quantity * 1;
                                    if (unitConversion.FirstOrDefault().Multiplier > 0)
                                    {
                                        baseQuantity = folderMonitoringTrnReceivingReceiptObject.Quantity * (1 / unitConversion.FirstOrDefault().Multiplier);
                                    }

                                    Decimal amount     = folderMonitoringTrnReceivingReceiptObject.Quantity * folderMonitoringTrnReceivingReceiptObject.Cost;
                                    Decimal VATAmount  = ComputeVATAmount(purchaseOrderItem.FirstOrDefault().MstArticle.MstTaxType1.IsInclusive, folderMonitoringTrnReceivingReceiptObject.Quantity * folderMonitoringTrnReceivingReceiptObject.Cost, purchaseOrderItem.FirstOrDefault().MstArticle.MstTaxType1.TaxRate);
                                    Decimal WTAXAmount = ComputeWTAXAmount(purchaseOrderItem.FirstOrDefault().MstArticle.MstTaxType2.IsInclusive, folderMonitoringTrnReceivingReceiptObject.Quantity * folderMonitoringTrnReceivingReceiptObject.Cost, purchaseOrderItem.FirstOrDefault().MstArticle.MstTaxType2.TaxRate);

                                    Decimal baseCost = 0;
                                    if (baseQuantity > 0)
                                    {
                                        baseCost = (amount - VATAmount + WTAXAmount) / baseQuantity;
                                    }

                                    Data.TrnReceivingReceiptItem newReceivingReceiptItem = new Data.TrnReceivingReceiptItem
                                    {
                                        RRId           = RRId,
                                        POId           = POId,
                                        ItemId         = purchaseOrderItem.FirstOrDefault().ItemId,
                                        Particulars    = folderMonitoringTrnReceivingReceiptObject.Particulars,
                                        UnitId         = purchaseOrderItem.FirstOrDefault().UnitId,
                                        Quantity       = folderMonitoringTrnReceivingReceiptObject.Quantity,
                                        Cost           = folderMonitoringTrnReceivingReceiptObject.Cost,
                                        Amount         = folderMonitoringTrnReceivingReceiptObject.Amount,
                                        VATId          = purchaseOrderItem.FirstOrDefault().MstArticle.InputTaxId,
                                        VATPercentage  = purchaseOrderItem.FirstOrDefault().MstArticle.MstTaxType1.TaxRate,
                                        VATAmount      = VATAmount,
                                        WTAXId         = purchaseOrderItem.FirstOrDefault().MstArticle.WTaxTypeId,
                                        WTAXPercentage = purchaseOrderItem.FirstOrDefault().MstArticle.MstTaxType2.TaxRate,
                                        WTAXAmount     = WTAXAmount,
                                        BranchId       = receivedBranch.FirstOrDefault().Id,
                                        BaseUnitId     = purchaseOrderItem.FirstOrDefault().MstArticle.UnitId,
                                        BaseQuantity   = baseQuantity,
                                        BaseCost       = baseCost
                                    };

                                    db.TrnReceivingReceiptItems.InsertOnSubmit(newReceivingReceiptItem);
                                    db.SubmitChanges();

                                    var receivingReceipt = from d in db.TrnReceivingReceipts where d.Id == RRId && d.IsLocked == false select d;
                                    if (receivingReceipt.Any())
                                    {
                                        Decimal receivingReceiptAmount = 0, receivingReceiptWTAXAmount = 0;
                                        var     receivingReceiptItems = from d in db.TrnReceivingReceiptItems where d.RRId == RRId select d;
                                        if (receivingReceiptItems.Any())
                                        {
                                            receivingReceiptAmount = receivingReceiptItems.Sum(d => d.Amount); receivingReceiptWTAXAmount = receivingReceiptItems.Sum(d => d.WTAXAmount);
                                        }

                                        var lockReceivingReceipt = receivingReceipt.FirstOrDefault();
                                        lockReceivingReceipt.Amount          = receivingReceiptAmount;
                                        lockReceivingReceipt.WTaxAmount      = receivingReceiptWTAXAmount;
                                        lockReceivingReceipt.IsLocked        = true;
                                        lockReceivingReceipt.UpdatedById     = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.UpdatedById;
                                        lockReceivingReceipt.UpdatedDateTime = purchaseOrderItem.FirstOrDefault().TrnPurchaseOrder.UpdatedDateTime;
                                        db.SubmitChanges();

                                        accountsPayable.UpdateAccountsPayable(RRId);
                                        inventory.InsertReceivingReceiptInventory(RRId);
                                        journal.InsertReceivingReceiptJournal(RRId);
                                    }
                                }
                            }
                        }
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound, "No data found."));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Something's went wrong from the server."));
            }
        }
예제 #2
0
        public HttpResponseMessage LockReceivingReceipt(Entities.TrnReceivingReceipt objReceivingReceipt, String id)
        {
            try
            {
                var currentUser = from d in db.MstUsers
                                  where d.UserId == User.Identity.GetUserId()
                                  select d;

                if (currentUser.Any())
                {
                    var currentUserId = currentUser.FirstOrDefault().Id;

                    var userForms = from d in db.MstUserForms
                                    where d.UserId == currentUserId &&
                                    d.SysForm.FormName.Equals("ReceivingReceiptDetail")
                                    select d;

                    if (userForms.Any())
                    {
                        if (userForms.FirstOrDefault().CanLock)
                        {
                            var receivingReceipt = from d in db.TrnReceivingReceipts
                                                   where d.Id == Convert.ToInt32(id)
                                                   select d;

                            if (receivingReceipt.Any())
                            {
                                if (!receivingReceipt.FirstOrDefault().IsLocked)
                                {
                                    Decimal paidAmount       = 0;
                                    Decimal adjustmentAmount = 0;

                                    var disbursementLines = from d in db.TrnDisbursementLines
                                                            where d.RRId == Convert.ToInt32(id) &&
                                                            d.TrnDisbursement.IsLocked == true
                                                            select d;

                                    if (disbursementLines.Any())
                                    {
                                        paidAmount = disbursementLines.Sum(d => d.Amount);
                                    }

                                    var journalVoucherLines = from d in db.TrnJournalVoucherLines
                                                              where d.APRRId == Convert.ToInt32(id) &&
                                                              d.TrnJournalVoucher.IsLocked == true
                                                              select d;

                                    if (journalVoucherLines.Any())
                                    {
                                        Decimal debitAmount  = journalVoucherLines.Sum(d => d.DebitAmount);
                                        Decimal creditAmount = journalVoucherLines.Sum(d => d.CreditAmount);

                                        adjustmentAmount = creditAmount - debitAmount;
                                    }

                                    var lockReceivingReceipt = receivingReceipt.FirstOrDefault();
                                    lockReceivingReceipt.RRDate            = Convert.ToDateTime(objReceivingReceipt.RRDate);
                                    lockReceivingReceipt.DocumentReference = objReceivingReceipt.DocumentReference;
                                    lockReceivingReceipt.SupplierId        = objReceivingReceipt.SupplierId;
                                    lockReceivingReceipt.TermId            = objReceivingReceipt.TermId;
                                    lockReceivingReceipt.Remarks           = objReceivingReceipt.Remarks;
                                    lockReceivingReceipt.ManualRRNumber    = objReceivingReceipt.ManualRRNumber;
                                    lockReceivingReceipt.Amount            = GetReceivingReceiptAmount(Convert.ToInt32(id));
                                    lockReceivingReceipt.WTaxAmount        = 0;
                                    lockReceivingReceipt.PaidAmount        = paidAmount;
                                    lockReceivingReceipt.AdjustmentAmount  = adjustmentAmount;
                                    lockReceivingReceipt.BalanceAmount     = (GetReceivingReceiptAmount(Convert.ToInt32(id)) - paidAmount) + adjustmentAmount;
                                    lockReceivingReceipt.ReceivedById      = objReceivingReceipt.ReceivedById;
                                    lockReceivingReceipt.CheckedById       = objReceivingReceipt.CheckedById;
                                    lockReceivingReceipt.ApprovedById      = objReceivingReceipt.ApprovedById;
                                    lockReceivingReceipt.IsLocked          = true;
                                    lockReceivingReceipt.UpdatedById       = currentUserId;
                                    lockReceivingReceipt.UpdatedDateTime   = DateTime.Now;

                                    db.SubmitChanges();

                                    // =====================
                                    // Inventory and Journal
                                    // =====================
                                    Business.Inventory inventory = new Business.Inventory();
                                    Business.Journal   journal   = new Business.Journal();

                                    if (lockReceivingReceipt.IsLocked)
                                    {
                                        inventory.InsertReceivingReceiptInventory(Convert.ToInt32(id));
                                        journal.InsertReceivingReceiptJournal(Convert.ToInt32(id));
                                    }

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                                else
                                {
                                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Locking Error. These receiving receipt details are already locked."));
                                }
                            }
                            else
                            {
                                return(Request.CreateResponse(HttpStatusCode.NotFound, "Data not found. These receiving receipt details are not found in the server."));
                            }
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.BadRequest, "Sorry. You have no rights to lock receiving receipt."));
                        }
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, "Sorry. You have no access for this receiving receipt page."));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Theres no current user logged in."));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Something's went wrong from the server."));
            }
        }
        public HttpResponseMessage AddFolderMonitoringReceivingReceipt(List <Entities.FolderMonitoringTrnReceivingReceipt> folderMonitoringTrnReceivingReceiptObjects)
        {
            try
            {
                if (folderMonitoringTrnReceivingReceiptObjects.Any())
                {
                    String returnMessage = "";

                    List <Entities.FolderMonitoringTrnReceivingReceiptHeader> newFolderMonitoringTrnReceivingReceiptHeaders = new List <Entities.FolderMonitoringTrnReceivingReceiptHeader>();
                    List <Entities.FolderMonitoringTrnReceivingReceiptItem>   newFolderMonitoringTrnReceivingReceiptItems   = new List <Entities.FolderMonitoringTrnReceivingReceiptItem>();

                    Boolean isDataValid = false;

                    foreach (var folderMonitoringTrnReceivingReceiptObject in folderMonitoringTrnReceivingReceiptObjects)
                    {
                        Boolean isBranchExist          = false,
                                 isSupplierExist       = false,
                                 isUserExist           = false,
                                 isItemExist           = false,
                                 isUnitExist           = false,
                                 isReceivedBranchExist = false;

                        var branch = from d in db.MstBranches where d.BranchCode.Equals(folderMonitoringTrnReceivingReceiptObject.BranchCode) select d;
                        if (branch.Any())
                        {
                            isBranchExist = true;
                        }

                        var supplier = from d in db.MstArticles where d.ArticleTypeId == 3 && d.ManualArticleCode.Equals(folderMonitoringTrnReceivingReceiptObject.SupplierCode) && d.IsLocked == true select d;
                        if (supplier.Any())
                        {
                            isSupplierExist = true;
                        }

                        var user = from d in db.MstUsers where d.UserName.Equals(folderMonitoringTrnReceivingReceiptObject.UserCode) select d;
                        if (user.Any())
                        {
                            isUserExist = true;
                        }

                        var item = from d in db.MstArticles where d.ArticleTypeId == 1 && d.ManualArticleCode.Equals(folderMonitoringTrnReceivingReceiptObject.ItemCode) && d.IsLocked == true select d;
                        if (item.Any())
                        {
                            isItemExist = true;
                        }

                        var unit = from d in db.MstUnits where d.Unit.Equals(folderMonitoringTrnReceivingReceiptObject.Unit) select d;
                        if (unit.Any())
                        {
                            isUnitExist = true;
                        }

                        var receivedBranch = from d in db.MstBranches where d.BranchCode.Equals(folderMonitoringTrnReceivingReceiptObject.ReceivedBranchCode) select d;
                        if (receivedBranch.Any())
                        {
                            isReceivedBranchExist = true;
                        }

                        if (!isBranchExist)
                        {
                            returnMessage = "Invalid Branch Code: " + folderMonitoringTrnReceivingReceiptObject.BranchCode; isDataValid = false; break;
                        }
                        else if (!isSupplierExist)
                        {
                            returnMessage = "Invalid Supplier Code: " + folderMonitoringTrnReceivingReceiptObject.SupplierCode; isDataValid = false; break;
                        }
                        else if (!isUserExist)
                        {
                            returnMessage = "Invalid User Code: " + folderMonitoringTrnReceivingReceiptObject.UserCode; isDataValid = false; break;
                        }
                        else if (!isItemExist)
                        {
                            returnMessage = "Invalid Item Code: " + folderMonitoringTrnReceivingReceiptObject.ItemCode; isDataValid = false; break;
                        }
                        else if (!isUnitExist)
                        {
                            returnMessage = "Invalid Unit: " + folderMonitoringTrnReceivingReceiptObject.Unit; isDataValid = false; break;
                        }
                        else if (!isReceivedBranchExist)
                        {
                            returnMessage = "Invalid Received Branch Code: " + folderMonitoringTrnReceivingReceiptObject.ReceivedBranchCode; isDataValid = false; break;
                        }
                        else
                        {
                            var currentReceivingReceipt = from d in db.TrnReceivingReceipts
                                                          where d.BranchId == branch.FirstOrDefault().Id &&
                                                          d.ManualRRNumber.Equals(folderMonitoringTrnReceivingReceiptObject.ManualRRNumber) &&
                                                          d.IsLocked == true
                                                          select d;

                            if (currentReceivingReceipt.Any())
                            {
                                returnMessage = "This Manual RR No. " + folderMonitoringTrnReceivingReceiptObject.ManualRRNumber + " is already exist!";
                                isDataValid   = false;

                                break;
                            }
                            else
                            {
                                var unitConversion = from d in db.MstArticleUnits
                                                     where d.ArticleId == item.FirstOrDefault().Id &&
                                                     d.UnitId == unit.FirstOrDefault().Id
                                                     select d;

                                if (unitConversion.Any())
                                {
                                    Decimal baseQuantity = folderMonitoringTrnReceivingReceiptObject.Quantity * 1;
                                    if (unitConversion.FirstOrDefault().Multiplier > 0)
                                    {
                                        baseQuantity = folderMonitoringTrnReceivingReceiptObject.Quantity * (1 / unitConversion.FirstOrDefault().Multiplier);
                                    }

                                    Decimal amount     = folderMonitoringTrnReceivingReceiptObject.Quantity * folderMonitoringTrnReceivingReceiptObject.Cost;
                                    Decimal VATAmount  = ComputeVATAmount(item.FirstOrDefault().MstTaxType1.IsInclusive, folderMonitoringTrnReceivingReceiptObject.Quantity * folderMonitoringTrnReceivingReceiptObject.Cost, item.FirstOrDefault().MstTaxType1.TaxRate);
                                    Decimal WTAXAmount = ComputeWTAXAmount(item.FirstOrDefault().MstTaxType2.IsInclusive, folderMonitoringTrnReceivingReceiptObject.Quantity * folderMonitoringTrnReceivingReceiptObject.Cost, item.FirstOrDefault().MstTaxType2.TaxRate);

                                    Decimal baseCost = 0;
                                    if (baseQuantity > 0)
                                    {
                                        baseCost = (amount - VATAmount + WTAXAmount) / baseQuantity;
                                    }

                                    var folderMonitoringTrnReceivingReceiptHeader = from d in newFolderMonitoringTrnReceivingReceiptHeaders
                                                                                    where d.BranchId == branch.FirstOrDefault().Id &&
                                                                                    d.ManualRRNumber.Equals(folderMonitoringTrnReceivingReceiptObject.ManualRRNumber)
                                                                                    select d;

                                    if (folderMonitoringTrnReceivingReceiptHeader.Any())
                                    {
                                        var currentFolderMonitoringTrnReceivingReceiptHeader = folderMonitoringTrnReceivingReceiptHeader.FirstOrDefault();
                                        currentFolderMonitoringTrnReceivingReceiptHeader.ListFolderMonitoringTrnReceivingReceiptItems.Add(new Entities.FolderMonitoringTrnReceivingReceiptItem()
                                        {
                                            ManualRRNumber = folderMonitoringTrnReceivingReceiptObject.ManualRRNumber,
                                            POId           = 0,
                                            ManualPONumber = folderMonitoringTrnReceivingReceiptObject.ManualPONumber,
                                            PODate         = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.PODate),
                                            PODateNeeded   = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.PODateNeeded),
                                            ItemId         = item.FirstOrDefault().Id,
                                            Particulars    = folderMonitoringTrnReceivingReceiptObject.Particulars,
                                            UnitId         = unitConversion.FirstOrDefault().UnitId,
                                            Quantity       = folderMonitoringTrnReceivingReceiptObject.Quantity,
                                            Cost           = folderMonitoringTrnReceivingReceiptObject.Cost,
                                            Amount         = folderMonitoringTrnReceivingReceiptObject.Amount,
                                            VATId          = item.FirstOrDefault().InputTaxId,
                                            VATPercentage  = item.FirstOrDefault().MstTaxType1.TaxRate,
                                            VATAmount      = VATAmount,
                                            WTAXId         = item.FirstOrDefault().WTaxTypeId,
                                            WTAXPercentage = item.FirstOrDefault().MstTaxType2.TaxRate,
                                            WTAXAmount     = WTAXAmount,
                                            BranchId       = receivedBranch.FirstOrDefault().Id,
                                            BaseUnitId     = item.FirstOrDefault().UnitId,
                                            BaseQuantity   = baseQuantity,
                                            BaseCost       = baseCost
                                        });
                                    }
                                    else
                                    {
                                        newFolderMonitoringTrnReceivingReceiptItems = new List <Entities.FolderMonitoringTrnReceivingReceiptItem>
                                        {
                                            new Entities.FolderMonitoringTrnReceivingReceiptItem()
                                            {
                                                ManualRRNumber = folderMonitoringTrnReceivingReceiptObject.ManualRRNumber,
                                                POId           = 0,
                                                ManualPONumber = folderMonitoringTrnReceivingReceiptObject.ManualPONumber,
                                                PODate         = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.PODate),
                                                PODateNeeded   = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.PODateNeeded),
                                                ItemId         = item.FirstOrDefault().Id,
                                                Particulars    = folderMonitoringTrnReceivingReceiptObject.Particulars,
                                                UnitId         = unitConversion.FirstOrDefault().UnitId,
                                                Quantity       = folderMonitoringTrnReceivingReceiptObject.Quantity,
                                                Cost           = folderMonitoringTrnReceivingReceiptObject.Cost,
                                                Amount         = folderMonitoringTrnReceivingReceiptObject.Amount,
                                                VATId          = item.FirstOrDefault().InputTaxId,
                                                VATPercentage  = item.FirstOrDefault().MstTaxType1.TaxRate,
                                                VATAmount      = VATAmount,
                                                WTAXId         = item.FirstOrDefault().WTaxTypeId,
                                                WTAXPercentage = item.FirstOrDefault().MstTaxType2.TaxRate,
                                                WTAXAmount     = WTAXAmount,
                                                BranchId       = receivedBranch.FirstOrDefault().Id,
                                                BaseUnitId     = item.FirstOrDefault().UnitId,
                                                BaseQuantity   = baseQuantity,
                                                BaseCost       = baseCost
                                            }
                                        };

                                        if (newFolderMonitoringTrnReceivingReceiptItems.Any())
                                        {
                                            newFolderMonitoringTrnReceivingReceiptHeaders.Add(new Entities.FolderMonitoringTrnReceivingReceiptHeader()
                                            {
                                                BranchId          = branch.FirstOrDefault().Id,
                                                RRNumber          = "0000000000",
                                                RRDate            = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.RRDate),
                                                DocumentReference = folderMonitoringTrnReceivingReceiptObject.DocumentReference,
                                                SupplierId        = supplier.FirstOrDefault().Id,
                                                TermId            = supplier.FirstOrDefault().MstTerm.Id,
                                                Remarks           = folderMonitoringTrnReceivingReceiptObject.Remarks,
                                                ManualRRNumber    = folderMonitoringTrnReceivingReceiptObject.ManualRRNumber,
                                                Amount            = 0,
                                                WTaxAmount        = 0,
                                                PaidAmount        = 0,
                                                AdjustmentAmount  = 0,
                                                BalanceAmount     = 0,
                                                ReceivedById      = user.FirstOrDefault().Id,
                                                PreparedById      = user.FirstOrDefault().Id,
                                                CheckedById       = user.FirstOrDefault().Id,
                                                ApprovedById      = user.FirstOrDefault().Id,
                                                Status            = null,
                                                IsCancelled       = false,
                                                IsPrinted         = false,
                                                IsLocked          = false,
                                                CreatedById       = user.FirstOrDefault().Id,
                                                CreatedDateTime   = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.CreatedDateTime),
                                                UpdatedById       = user.FirstOrDefault().Id,
                                                UpdatedDateTime   = Convert.ToDateTime(folderMonitoringTrnReceivingReceiptObject.CreatedDateTime),
                                                ListFolderMonitoringTrnReceivingReceiptItems = newFolderMonitoringTrnReceivingReceiptItems
                                            });
                                        }
                                    }
                                }
                                else
                                {
                                    returnMessage = "This item code: " + folderMonitoringTrnReceivingReceiptObject.ItemCode + " has invalid unit conversion. Unit: " + folderMonitoringTrnReceivingReceiptObject.Unit;
                                    isDataValid   = false;

                                    break;
                                }

                                isDataValid = true;
                            }
                        }
                    }

                    if (isDataValid)
                    {
                        if (newFolderMonitoringTrnReceivingReceiptHeaders.Any())
                        {
                            foreach (var newFolderMonitoringTrnReceivingReceiptHeader in newFolderMonitoringTrnReceivingReceiptHeaders)
                            {
                                Int32 RRId = 0;

                                var defaultRRNumber      = "0000000001";
                                var lastReceivingReceipt = from d in db.TrnReceivingReceipts.OrderByDescending(d => d.Id) where d.BranchId == newFolderMonitoringTrnReceivingReceiptHeader.BranchId select d;
                                if (lastReceivingReceipt.Any())
                                {
                                    var RRNumber = Convert.ToInt32(lastReceivingReceipt.FirstOrDefault().RRNumber) + 0000000001;
                                    defaultRRNumber = FillLeadingZeroes(RRNumber, 10);
                                }

                                Data.TrnReceivingReceipt newReceivingReceipt = new Data.TrnReceivingReceipt
                                {
                                    BranchId          = newFolderMonitoringTrnReceivingReceiptHeader.BranchId,
                                    RRNumber          = defaultRRNumber,
                                    RRDate            = newFolderMonitoringTrnReceivingReceiptHeader.RRDate,
                                    DocumentReference = newFolderMonitoringTrnReceivingReceiptHeader.DocumentReference,
                                    SupplierId        = newFolderMonitoringTrnReceivingReceiptHeader.SupplierId,
                                    TermId            = newFolderMonitoringTrnReceivingReceiptHeader.TermId,
                                    Remarks           = newFolderMonitoringTrnReceivingReceiptHeader.Remarks,
                                    ManualRRNumber    = newFolderMonitoringTrnReceivingReceiptHeader.ManualRRNumber,
                                    Amount            = newFolderMonitoringTrnReceivingReceiptHeader.Amount,
                                    WTaxAmount        = newFolderMonitoringTrnReceivingReceiptHeader.WTaxAmount,
                                    PaidAmount        = newFolderMonitoringTrnReceivingReceiptHeader.PaidAmount,
                                    AdjustmentAmount  = newFolderMonitoringTrnReceivingReceiptHeader.AdjustmentAmount,
                                    BalanceAmount     = newFolderMonitoringTrnReceivingReceiptHeader.BalanceAmount,
                                    ReceivedById      = newFolderMonitoringTrnReceivingReceiptHeader.ReceivedById,
                                    PreparedById      = newFolderMonitoringTrnReceivingReceiptHeader.PreparedById,
                                    CheckedById       = newFolderMonitoringTrnReceivingReceiptHeader.CheckedById,
                                    ApprovedById      = newFolderMonitoringTrnReceivingReceiptHeader.ApprovedById,
                                    Status            = newFolderMonitoringTrnReceivingReceiptHeader.Status,
                                    IsCancelled       = newFolderMonitoringTrnReceivingReceiptHeader.IsCancelled,
                                    IsPrinted         = newFolderMonitoringTrnReceivingReceiptHeader.IsPrinted,
                                    IsLocked          = newFolderMonitoringTrnReceivingReceiptHeader.IsLocked,
                                    CreatedById       = newFolderMonitoringTrnReceivingReceiptHeader.CreatedById,
                                    CreatedDateTime   = newFolderMonitoringTrnReceivingReceiptHeader.CreatedDateTime,
                                    UpdatedById       = newFolderMonitoringTrnReceivingReceiptHeader.UpdatedById,
                                    UpdatedDateTime   = newFolderMonitoringTrnReceivingReceiptHeader.UpdatedDateTime
                                };

                                db.TrnReceivingReceipts.InsertOnSubmit(newReceivingReceipt);
                                db.SubmitChanges();

                                RRId = newReceivingReceipt.Id;

                                if (newFolderMonitoringTrnReceivingReceiptHeader.ListFolderMonitoringTrnReceivingReceiptItems.Any())
                                {
                                    foreach (var listFolderMonitoringTrnReceivingReceiptItem in newFolderMonitoringTrnReceivingReceiptHeader.ListFolderMonitoringTrnReceivingReceiptItems)
                                    {
                                        Int32 POId = 0;

                                        var purchaseOrder = from d in db.TrnPurchaseOrders
                                                            where d.BranchId == newFolderMonitoringTrnReceivingReceiptHeader.BranchId &&
                                                            d.PODate == listFolderMonitoringTrnReceivingReceiptItem.PODate &&
                                                            d.ManualPONumber.Equals(listFolderMonitoringTrnReceivingReceiptItem.ManualPONumber) &&
                                                            d.IsLocked == true
                                                            select d;

                                        if (purchaseOrder.Any())
                                        {
                                            POId = purchaseOrder.FirstOrDefault().Id;
                                        }
                                        else
                                        {
                                            var defaultPONumber   = "0000000001";
                                            var lastPurchaseOrder = from d in db.TrnPurchaseOrders.OrderByDescending(d => d.Id) where d.BranchId == newFolderMonitoringTrnReceivingReceiptHeader.BranchId select d;
                                            if (lastPurchaseOrder.Any())
                                            {
                                                var PONumber = Convert.ToInt32(lastPurchaseOrder.FirstOrDefault().PONumber) + 0000000001;
                                                defaultPONumber = FillLeadingZeroes(PONumber, 10);
                                            }

                                            Data.TrnPurchaseOrder newPurchaseOrder = new Data.TrnPurchaseOrder
                                            {
                                                BranchId            = newFolderMonitoringTrnReceivingReceiptHeader.BranchId,
                                                PONumber            = defaultPONumber,
                                                PODate              = Convert.ToDateTime(listFolderMonitoringTrnReceivingReceiptItem.PODate),
                                                SupplierId          = newFolderMonitoringTrnReceivingReceiptHeader.SupplierId,
                                                TermId              = newFolderMonitoringTrnReceivingReceiptHeader.TermId,
                                                ManualRequestNumber = "NA",
                                                ManualPONumber      = listFolderMonitoringTrnReceivingReceiptItem.ManualPONumber,
                                                DateNeeded          = Convert.ToDateTime(listFolderMonitoringTrnReceivingReceiptItem.PODateNeeded),
                                                Remarks             = newFolderMonitoringTrnReceivingReceiptHeader.Remarks,
                                                IsClose             = false,
                                                RequestedById       = newFolderMonitoringTrnReceivingReceiptHeader.PreparedById,
                                                PreparedById        = newFolderMonitoringTrnReceivingReceiptHeader.PreparedById,
                                                CheckedById         = newFolderMonitoringTrnReceivingReceiptHeader.CheckedById,
                                                ApprovedById        = newFolderMonitoringTrnReceivingReceiptHeader.ApprovedById,
                                                Status              = null,
                                                IsCancelled         = false,
                                                IsPrinted           = false,
                                                IsLocked            = true,
                                                CreatedById         = newFolderMonitoringTrnReceivingReceiptHeader.CreatedById,
                                                CreatedDateTime     = newFolderMonitoringTrnReceivingReceiptHeader.CreatedDateTime,
                                                UpdatedById         = newFolderMonitoringTrnReceivingReceiptHeader.UpdatedById,
                                                UpdatedDateTime     = newFolderMonitoringTrnReceivingReceiptHeader.CreatedDateTime
                                            };

                                            db.TrnPurchaseOrders.InsertOnSubmit(newPurchaseOrder);
                                            db.SubmitChanges();

                                            POId = newPurchaseOrder.Id;
                                        }

                                        Data.TrnPurchaseOrderItem newPurchaseOrderItem = new Data.TrnPurchaseOrderItem
                                        {
                                            POId         = POId,
                                            ItemId       = listFolderMonitoringTrnReceivingReceiptItem.ItemId,
                                            Particulars  = listFolderMonitoringTrnReceivingReceiptItem.Particulars,
                                            UnitId       = listFolderMonitoringTrnReceivingReceiptItem.UnitId,
                                            Quantity     = listFolderMonitoringTrnReceivingReceiptItem.Quantity,
                                            Cost         = listFolderMonitoringTrnReceivingReceiptItem.Cost,
                                            Amount       = listFolderMonitoringTrnReceivingReceiptItem.Amount,
                                            BaseUnitId   = listFolderMonitoringTrnReceivingReceiptItem.BaseUnitId,
                                            BaseQuantity = listFolderMonitoringTrnReceivingReceiptItem.BaseQuantity,
                                            BaseCost     = listFolderMonitoringTrnReceivingReceiptItem.BaseCost
                                        };

                                        db.TrnPurchaseOrderItems.InsertOnSubmit(newPurchaseOrderItem);

                                        var item = from d in db.MstArticles
                                                   where d.Id == listFolderMonitoringTrnReceivingReceiptItem.ItemId &&
                                                   d.IsLocked == true
                                                   select d;

                                        if (item.Any())
                                        {
                                            var updateItem = item.FirstOrDefault();
                                            updateItem.Cost = newPurchaseOrderItem.Cost;
                                            db.SubmitChanges();
                                        }

                                        Data.TrnReceivingReceiptItem newReceivingReceiptItem = new Data.TrnReceivingReceiptItem
                                        {
                                            RRId           = RRId,
                                            POId           = POId,
                                            ItemId         = listFolderMonitoringTrnReceivingReceiptItem.ItemId,
                                            Particulars    = listFolderMonitoringTrnReceivingReceiptItem.Particulars,
                                            UnitId         = listFolderMonitoringTrnReceivingReceiptItem.UnitId,
                                            Quantity       = listFolderMonitoringTrnReceivingReceiptItem.Quantity,
                                            Cost           = listFolderMonitoringTrnReceivingReceiptItem.Cost,
                                            Amount         = listFolderMonitoringTrnReceivingReceiptItem.Amount,
                                            VATId          = listFolderMonitoringTrnReceivingReceiptItem.VATId,
                                            VATPercentage  = listFolderMonitoringTrnReceivingReceiptItem.VATPercentage,
                                            VATAmount      = listFolderMonitoringTrnReceivingReceiptItem.VATAmount,
                                            WTAXId         = listFolderMonitoringTrnReceivingReceiptItem.WTAXId,
                                            WTAXPercentage = listFolderMonitoringTrnReceivingReceiptItem.WTAXPercentage,
                                            WTAXAmount     = listFolderMonitoringTrnReceivingReceiptItem.WTAXAmount,
                                            BranchId       = listFolderMonitoringTrnReceivingReceiptItem.BranchId,
                                            BaseUnitId     = listFolderMonitoringTrnReceivingReceiptItem.BaseUnitId,
                                            BaseQuantity   = listFolderMonitoringTrnReceivingReceiptItem.BaseQuantity,
                                            BaseCost       = listFolderMonitoringTrnReceivingReceiptItem.BaseCost
                                        };

                                        db.TrnReceivingReceiptItems.InsertOnSubmit(newReceivingReceiptItem);
                                    }

                                    db.SubmitChanges();
                                }

                                var receivingReceipt = from d in db.TrnReceivingReceipts
                                                       where d.Id == RRId
                                                       select d;

                                if (receivingReceipt.Any())
                                {
                                    Decimal amount = 0;
                                    var     receivingReceiptItems = from d in db.TrnReceivingReceiptItems where d.RRId == RRId select d;
                                    if (receivingReceiptItems.Any())
                                    {
                                        amount = receivingReceiptItems.Sum(d => d.Amount);
                                    }

                                    var lockReceivingReceipt = receivingReceipt.FirstOrDefault();
                                    lockReceivingReceipt.Amount   = amount;
                                    lockReceivingReceipt.IsLocked = true;
                                    db.SubmitChanges();

                                    accountsPayable.UpdateAccountsPayable(RRId);
                                    inventory.InsertReceivingReceiptInventory(RRId);
                                    journal.InsertReceivingReceiptJournal(RRId);
                                }
                            }
                        }
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK, returnMessage));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound, "Data Source is Invalid or Empty."));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Backend Error: " + ex.Message));
            }
        }
        public HttpResponseMessage updateReceivingReceipt(String id, Models.TrnReceivingReceipt receivingReceipt)
        {
            try
            {
                var userId = (from d in db.MstUsers where d.UserId == User.Identity.GetUserId() select d.Id).SingleOrDefault();

                var receivingReceipts = from d in db.TrnReceivingReceipts where d.Id == Convert.ToInt32(id) select d;
                if (receivingReceipts.Any())
                {
                    //  get disbursement line for CVId
                    var disbursementLineCVId = from d in db.TrnDisbursementLines where d.RRId == Convert.ToInt32(id) select d;

                    Decimal PaidAmount = 0;

                    if (disbursementLineCVId.Any())
                    {
                        Boolean disbursementHeaderIsLocked = (from d in db.TrnDisbursements where d.Id == disbursementLineCVId.First().CVId select d.IsLocked).SingleOrDefault();

                        // get disbursement line for paid amaount
                        var disbursementLines = from d in db.TrnDisbursementLines where d.RRId == Convert.ToInt32(id) select d;
                        if (disbursementLines.Any())
                        {
                            if (disbursementHeaderIsLocked == true)
                            {
                                PaidAmount = disbursementLines.Sum(d => d.Amount);
                            }
                            else
                            {
                                PaidAmount = 0;
                            }
                        }
                        else
                        {
                            PaidAmount = 0;
                        }
                    }

                    var updatereceivingReceipt = receivingReceipts.FirstOrDefault();
                    updatereceivingReceipt.BranchId          = receivingReceipt.BranchId;
                    updatereceivingReceipt.RRDate            = Convert.ToDateTime(receivingReceipt.RRDate);
                    updatereceivingReceipt.RRNumber          = receivingReceipt.RRNumber;
                    updatereceivingReceipt.SupplierId        = receivingReceipt.SupplierId;
                    updatereceivingReceipt.TermId            = receivingReceipt.TermId;
                    updatereceivingReceipt.DocumentReference = receivingReceipt.DocumentReference;
                    updatereceivingReceipt.ManualRRNumber    = receivingReceipt.ManualRRNumber;
                    updatereceivingReceipt.Remarks           = receivingReceipt.Remarks;
                    updatereceivingReceipt.Amount            = getAmountReceivingReceiptItem(Convert.ToInt32(id));
                    updatereceivingReceipt.WTaxAmount        = 0;
                    updatereceivingReceipt.PaidAmount        = PaidAmount;
                    updatereceivingReceipt.AdjustmentAmount  = 0;
                    updatereceivingReceipt.BalanceAmount     = getAmountReceivingReceiptItem(Convert.ToInt32(id)) - PaidAmount;
                    updatereceivingReceipt.ReceivedById      = receivingReceipt.ReceivedById;
                    updatereceivingReceipt.PreparedById      = receivingReceipt.PreparedById;
                    updatereceivingReceipt.CheckedById       = receivingReceipt.CheckedById;
                    updatereceivingReceipt.ApprovedById      = receivingReceipt.ApprovedById;
                    updatereceivingReceipt.IsLocked          = true;
                    updatereceivingReceipt.UpdatedById       = userId;
                    updatereceivingReceipt.UpdatedDateTime   = DateTime.Now;

                    db.SubmitChanges();

                    if (updatereceivingReceipt.IsLocked == true)
                    {
                        inventory.InsertReceivingReceiptInventory(Convert.ToInt32(id));
                        journal.InsertReceivingReceiptJournal(Convert.ToInt32(id));
                    }
                    else
                    {
                        inventory.DeleteReceivingReceiptInventory(Convert.ToInt32(id));
                        journal.DeleteReceivingReceiptJournal(Convert.ToInt32(id));
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK));
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                }
            }
            catch
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
        public HttpResponseMessage LockReceivingReceipt(Entities.TrnReceivingReceipt objReceivingReceipt, String id)
        {
            try
            {
                var currentUser = from d in db.MstUsers
                                  where d.UserId == User.Identity.GetUserId()
                                  select d;

                if (currentUser.Any())
                {
                    var currentUserId = currentUser.FirstOrDefault().Id;

                    var userForms = from d in db.MstUserForms
                                    where d.UserId == currentUserId &&
                                    d.SysForm.FormName.Equals("ReceivingReceiptDetail")
                                    select d;

                    if (userForms.Any())
                    {
                        if (userForms.FirstOrDefault().CanLock)
                        {
                            var receivingReceipt = from d in db.TrnReceivingReceipts
                                                   where d.Id == Convert.ToInt32(id)
                                                   select d;

                            if (receivingReceipt.Any())
                            {
                                int countInvalidPO = 0;
                                var invalidPOs     = from d in db.TrnReceivingReceiptItems
                                                     where d.RRId == receivingReceipt.FirstOrDefault().Id &&
                                                     d.TrnPurchaseOrder.IsLocked == false &&
                                                     d.TrnPurchaseOrder.IsCancelled == true
                                                     select d;

                                if (invalidPOs.Any())
                                {
                                    countInvalidPO = invalidPOs.Count();
                                }

                                if (!receivingReceipt.FirstOrDefault().IsLocked&& countInvalidPO == 0)
                                {
                                    String oldObject = auditTrail.GetObjectString(receivingReceipt.FirstOrDefault());

                                    Decimal amount = 0, WTAXAmount = 0;
                                    var     receivingReceiptItems = from d in db.TrnReceivingReceiptItems where d.RRId == Convert.ToInt32(id) select d;
                                    if (receivingReceiptItems.Any())
                                    {
                                        amount = receivingReceiptItems.Sum(d => d.Amount); WTAXAmount = receivingReceiptItems.Sum(d => d.WTAXAmount);
                                    }

                                    var lockReceivingReceipt      = receivingReceipt.FirstOrDefault();
                                    lockReceivingReceipt.RRDate            = Convert.ToDateTime(objReceivingReceipt.RRDate);
                                    lockReceivingReceipt.DocumentReference = objReceivingReceipt.DocumentReference;
                                    lockReceivingReceipt.SupplierId        = objReceivingReceipt.SupplierId;
                                    lockReceivingReceipt.TermId            = objReceivingReceipt.TermId;
                                    lockReceivingReceipt.Remarks           = objReceivingReceipt.Remarks;
                                    lockReceivingReceipt.ManualRRNumber    = objReceivingReceipt.ManualRRNumber;
                                    lockReceivingReceipt.Amount            = amount;
                                    lockReceivingReceipt.WTaxAmount        = WTAXAmount;
                                    lockReceivingReceipt.ReceivedById      = objReceivingReceipt.ReceivedById;
                                    lockReceivingReceipt.CheckedById       = objReceivingReceipt.CheckedById;
                                    lockReceivingReceipt.ApprovedById      = objReceivingReceipt.ApprovedById;
                                    lockReceivingReceipt.Status            = objReceivingReceipt.Status;
                                    lockReceivingReceipt.IsLocked          = true;
                                    lockReceivingReceipt.UpdatedById       = currentUserId;
                                    lockReceivingReceipt.UpdatedDateTime   = DateTime.Now;
                                    db.SubmitChanges();

                                    if (lockReceivingReceipt.IsLocked)
                                    {
                                        UpdatePurchaseOrderStatus(Convert.ToInt32(id));

                                        accountsPayable.UpdateAccountsPayable(Convert.ToInt32(id));
                                        inventory.InsertReceivingReceiptInventory(Convert.ToInt32(id));
                                        journal.InsertReceivingReceiptJournal(Convert.ToInt32(id));
                                    }

                                    String newObject = auditTrail.GetObjectString(receivingReceipt.FirstOrDefault());
                                    auditTrail.InsertAuditTrail(currentUser.FirstOrDefault().Id, GetType().Name, MethodBase.GetCurrentMethod().Name, oldObject, newObject);

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                                else
                                {
                                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Locking Error. These receiving receipt details are already locked or PO is invalid.."));
                                }
                            }
                            else
                            {
                                return(Request.CreateResponse(HttpStatusCode.NotFound, "Data not found. These receiving receipt details are not found in the server."));
                            }
                        }
                        else
                        {
                            return(Request.CreateResponse(HttpStatusCode.BadRequest, "Sorry. You have no rights to lock receiving receipt."));
                        }
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, "Sorry. You have no access for this receiving receipt page."));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Theres no current user logged in."));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Something's went wrong from the server."));
            }
        }