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."));
            }
        }
Beispiel #2
0
        public HttpResponseMessage UnlockReceivingReceipt(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().CanUnlock)
                        {
                            var receivingReceipt = from d in db.TrnReceivingReceipts
                                                   where d.Id == Convert.ToInt32(id)
                                                   select d;

                            if (receivingReceipt.Any())
                            {
                                if (receivingReceipt.FirstOrDefault().IsLocked)
                                {
                                    var unlockReceivingReceipt = receivingReceipt.FirstOrDefault();
                                    unlockReceivingReceipt.IsLocked        = false;
                                    unlockReceivingReceipt.UpdatedById     = currentUserId;
                                    unlockReceivingReceipt.UpdatedDateTime = DateTime.Now;

                                    db.SubmitChanges();

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

                                    if (!unlockReceivingReceipt.IsLocked)
                                    {
                                        inventory.DeleteReceivingReceiptInventory(Convert.ToInt32(id));
                                        journal.DeleteReceivingReceiptJournal(Convert.ToInt32(id));
                                    }

                                    return(Request.CreateResponse(HttpStatusCode.OK));
                                }
                                else
                                {
                                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Unlocking Error. These receiving receipt details are already unlocked."));
                                }
                            }
                            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 unlock 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 UnlockReceivingReceipt(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().CanUnlock)
                        {
                            var receivingReceipt = from d in db.TrnReceivingReceipts
                                                   where d.Id == Convert.ToInt32(id)
                                                   select d;

                            if (receivingReceipt.Any())
                            {
                                if (!receivingReceipt.FirstOrDefault().IsCancelled)
                                {
                                    if (receivingReceipt.FirstOrDefault().IsLocked)
                                    {
                                        String oldObject = auditTrail.GetObjectString(receivingReceipt.FirstOrDefault());

                                        var unlockReceivingReceipt = receivingReceipt.FirstOrDefault();
                                        unlockReceivingReceipt.IsLocked        = false;
                                        unlockReceivingReceipt.UpdatedById     = currentUserId;
                                        unlockReceivingReceipt.UpdatedDateTime = DateTime.Now;
                                        db.SubmitChanges();

                                        if (!unlockReceivingReceipt.IsLocked)
                                        {
                                            UpdatePurchaseOrderStatus(Convert.ToInt32(id));

                                            inventory.DeleteReceivingReceiptInventory(Convert.ToInt32(id));
                                            journal.DeleteReceivingReceiptJournal(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, "Unlocking Error. These receiving receipt details are already unlocked."));
                                    }
                                }
                                else
                                {
                                    return(Request.CreateResponse(HttpStatusCode.BadRequest, "Unlocking Error. These receiving receipt details are already cancelled."));
                                }
                            }
                            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 unlock 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 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));
                                    }

                                    if (!currentUser.FirstOrDefault().MstCompany.IsRRCanReceiveOverPOQuantity)
                                    {
                                        Decimal pquantity = 0, rquantity = 0;

                                        Boolean isExceedQuantity = false;
                                        var     receivedItems    = from d in db.TrnReceivingReceiptItems
                                                                   where d.RRId == receivingReceipt.FirstOrDefault().Id
                                                                   select d;

                                        if (receivedItems.Any())
                                        {
                                            foreach (var receivedItem in receivedItems)
                                            {
                                                Decimal totalQuantityPurchasedItem = 0, totalQuantityReceivedItem = 0;

                                                var purchasedQuantityItem = from d in db.TrnPurchaseOrderItems
                                                                            where d.POId == receivedItem.POId &&
                                                                            d.ItemId == receivedItem.ItemId &&
                                                                            d.TrnPurchaseOrder.IsLocked == true
                                                                            select d;

                                                if (purchasedQuantityItem.Any())
                                                {
                                                    totalQuantityPurchasedItem = purchasedQuantityItem.Sum(d => d.Quantity);

                                                    var receivedQuantityItem = from d in db.TrnReceivingReceiptItems
                                                                               where d.POId == receivedItem.POId &&
                                                                               d.ItemId == receivedItem.ItemId &&
                                                                               d.TrnReceivingReceipt.IsLocked == true
                                                                               select d;

                                                    if (receivedQuantityItem.Any())
                                                    {
                                                        totalQuantityReceivedItem = receivedQuantityItem.Sum(d => d.Quantity);
                                                    }
                                                }

                                                if (totalQuantityReceivedItem > totalQuantityPurchasedItem)
                                                {
                                                    isExceedQuantity = true;

                                                    pquantity = totalQuantityPurchasedItem;
                                                    rquantity = totalQuantityReceivedItem;

                                                    break;
                                                }
                                            }
                                        }

                                        if (isExceedQuantity)
                                        {
                                            db.Refresh(RefreshMode.OverwriteCurrentValues, receivingReceipt);

                                            var unlockReceivingReceipt = receivingReceipt.FirstOrDefault();
                                            unlockReceivingReceipt.IsLocked        = false;
                                            unlockReceivingReceipt.UpdatedById     = currentUserId;
                                            unlockReceivingReceipt.UpdatedDateTime = DateTime.Now;
                                            db.SubmitChanges();

                                            if (!unlockReceivingReceipt.IsLocked)
                                            {
                                                UpdatePurchaseOrderStatus(Convert.ToInt32(id));

                                                accountsPayable.UpdateAccountsPayable(Convert.ToInt32(id));
                                                inventory.DeleteReceivingReceiptInventory(Convert.ToInt32(id));
                                                journal.DeleteReceivingReceiptJournal(Convert.ToInt32(id));
                                            }

                                            return(Request.CreateResponse(HttpStatusCode.BadRequest, "Locking Error. Cannot receive more than purchased item quantity." + " Purchased Qty: " + pquantity + ", Received Qty: " + rquantity));
                                        }
                                        else
                                        {
                                            String newObject = auditTrail.GetObjectString(receivingReceipt.FirstOrDefault());
                                            auditTrail.InsertAuditTrail(currentUser.FirstOrDefault().Id, GetType().Name, MethodBase.GetCurrentMethod().Name, oldObject, newObject);

                                            return(Request.CreateResponse(HttpStatusCode.OK));
                                        }
                                    }
                                    else
                                    {
                                        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."));
            }
        }