private TblDyeingOrderInvoiceHeader UpdateOrInsertDyeingOrderInvoiceHeader(TblDyeingOrderInvoiceHeader newRow, bool save, int index, out int outindex)
 {
     outindex = index;
     using (var context = new WorkFlowManagerDBEntities())
     {
         if (save)
         {
             var seqCode = SharedOperation.GetChainSetup("GlDyeingPostSequence");
             var seqProd = context.TblSequenceProductions.FirstOrDefault(w => w.Code == seqCode);
             newRow.Code = SharedOperation.HandelSequence(seqProd);
             context.TblDyeingOrderInvoiceHeaders.AddObject(newRow);
         }
         else
         {
             var oldRow = (from e in context.TblDyeingOrderInvoiceHeaders
                           where e.Iserial == newRow.Iserial
                           select e).SingleOrDefault();
             if (oldRow != null)
             {
                 SharedOperation.GenericUpdate(oldRow, newRow, context);
             }
         }
         context.SaveChanges();
         return(newRow);
     }
 }
Beispiel #2
0
        private TblPurchaseOrderHeaderRequest UpdateOrInsertTblPurchaseOrderHeaderRequest(TblPurchaseOrderHeaderRequest newRow, int index, int user, out int outindex)
        {
            outindex = index;
            using (var context = new WorkFlowManagerDBEntities())
            {
                var warehouse = context.TblWarehouses.FirstOrDefault(w => w.Iserial == newRow.TblWarehouse).Po;

                var seq = context.TblSequenceProductions.FirstOrDefault(w => w.Iserial == warehouse);

                var oldRow = (from e in context.TblPurchaseOrderHeaderRequests
                              where e.Iserial == newRow.Iserial
                              select e).SingleOrDefault();
                if (oldRow != null)
                {
                    newRow.CreatedBy    = oldRow.CreatedBy;
                    newRow.CreationDate = oldRow.CreationDate;
                    SharedOperation.GenericUpdate(oldRow, newRow, context);
                }
                else
                {
                    newRow.CreationDate = DateTime.Now;
                    newRow.CreatedBy    = user;
                    newRow.Code         = SharedOperation.HandelSequence(seq);
                    context.TblPurchaseOrderHeaderRequests.AddObject(newRow);
                }
                context.SaveChanges();

                return(newRow);
            }
        }
Beispiel #3
0
        private int InsertImportedItems(TblAdjustmentHeader header,
                                        List <ImportedItemDimensionModel> importedList, bool Counting, out bool IsCounting)
        {
            IsCounting = Counting;
            List <string> errors = new List <string>();

            using (var entities = new WorkFlowManagerDBEntities())
            {
                try
                {
                    header.Approved = false;
                    foreach (var item in importedList)
                    {
                        TblAdjustmentDetail detail = PrepareDetail(entities, header, item, errors);
                        if (detail != null)
                        {
                            header.TblAdjustmentDetails.Add(detail);
                        }
                    }
                    var warehouseRec = entities.TblWarehouses.FirstOrDefault(w => w.Iserial == header.WarehouseIserial);
                    var seq          = warehouseRec.AdjustIn;
                    var seqRow       = entities.TblSequenceProductions.FirstOrDefault(x => x.Iserial == seq);
                    header.Code         = SharedOperation.HandelSequence(seqRow);
                    header.TblWarehouse = null;

                    header.CreationDate   = DateTime.Now;
                    header.LastChangeDate = DateTime.Now;
                    header.LastChangeUser = header.CreatedBy;

                    entities.TblAdjustmentHeaders.AddObject(header);
                    entities.SaveChanges();
                    return(header.Iserial);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Beispiel #4
0
        private TblContractHeader UpdateOrInsertContractHeader(TblContractHeader newRow, int index, int userIserial, out int outindex, string company)
        {
            throw new Exception("Save Contracts On Stitch");

            outindex = index;
            using (var context = new WorkFlowManagerDBEntities())
            {
                try
                {
                    newRow.TblRetailOrderProductionType1 = null;
                    newRow.TblSubContractor1             = null;
                    newRow.TblLkpSeason1       = null;
                    newRow.TblLkpBrandSection1 = null;
                    var brandCode = newRow.BrandCode;
                    var report    = context.TblBrandContractReports.FirstOrDefault(bcr => bcr.BrandCode == brandCode);
                    if (report != null)
                    {
                        newRow.ContractReport = report.ReportName;
                    }
                    var oldRow = context.TblContractHeaders.FirstOrDefault(th => th.Iserial == newRow.Iserial);
                    newRow.Amount = newRow.TblContractDetails.Sum(r => r.Total);



                    var budgetAmount = CalculateBudget(newRow, context);

                    var contractsAmount = context.TblContractDetails
                                          .Include(nameof(TblContractDetail.TblContractHeader1)).Where(r =>
                                                                                                       r.TblContractHeader1.BrandCode == newRow.BrandCode && r.TblLkpBrandSection == newRow.TblLkpBrandSection &&
                                                                                                       r.TblContractHeader1.TblLkpSeason == newRow.TblLkpSeason).ToList()
                                          .Select(r => new Tuple <int?, decimal>(r.TblLkpBrandSection,
                                                                                 r.TblContractHeader1.TblRetailOrderProductionType == 1 ?
                                                                                 (r.Qty * r.Cost) : r.TblContractHeader1.TblRetailOrderProductionType == 2 ?
                                                                                 (r.Qty * (r.Cost - r.AccCost)) : r.TblContractHeader1.TblRetailOrderProductionType == 3 ?
                                                                                 (r.Qty * (r.Cost - r.AccCost - r.FabricCost)) : (r.Qty * r.Cost)
                                                                                 )).GroupBy(r => r.Item1).Select(r => new Tuple <int?, decimal>(r.Key, r.Sum(d => d.Item2))).ToList();

                    var tblContractDetail = new List <TblContractDetail>();
                    newRow.TblContractDetails.ToArray().ForEach(d => tblContractDetail.Add(d));
                    if (oldRow != null)// الهيدر موجود قبل كده
                    {
                        CheckBudget(newRow, oldRow, budgetAmount, contractsAmount);

                        if (!oldRow.Approved && newRow.Approved)// كده لسه معموله ابروف
                        {
                            newRow.ApproveDate = DateTime.Now;
                            newRow.ApprovedBy  = userIserial;
                        }
                        foreach (var item in newRow.TblContractDetails.ToArray())
                        {
                            // هشوف بقى الى اتعدل والجديد
                            int temp;
                            //headeriserial = item.TblContractHeader;
                            item.TblContractHeader1 = null;
                            item.TblContractHeader  = newRow.Iserial;
                            UpdateOrInsertContractDetail(item, userIserial, 1, out temp);
                            item.TblContractHeader1Reference = null;
                        }
                        foreach (var item in newRow.TblContractPaymentByPeriods.ToArray())
                        {
                            // هشوف بقى الى اتعدل والجديد
                            int temp;
                            item.TblContractHeader1 = null;
                            item.TblContractHeader  = newRow.Iserial;
                            UpdateOrInsertContractPaymentDetail(item, userIserial, 1, out temp);
                            item.TblContractHeader1Reference = null;
                        }
                        //context.Entry(oldRow).CurrentValues.SetValues(newRow);
                        var result = SharedOperation.GenericUpdate(oldRow, newRow, context);
                        if (result.Count() > 0)
                        {
                            newRow.LastChangeUser = userIserial;
                            newRow.LastChangeDate = DateTime.Now;
                        }
                    }
                    else// الهيدر ده جديد
                    {
                        CheckBudget(newRow, null, budgetAmount, contractsAmount);

                        var seqTo  = 443;//context.tblChainSetups.FirstOrDefault(s => s.sGlobalSettingCode == "ContractApproveEmailTo");
                        var seqRow = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == seqTo);
                        newRow.Code = SharedOperation.HandelSequence(seqRow);
                        if (newRow.Approved)// كده معموله ابروف
                        {
                            newRow.ApproveDate = DateTime.Now;
                            newRow.ApprovedBy  = userIserial;
                        }
                        newRow.TblContractDetails.ForEach(cd => {
                            cd.TblColor1 = null; cd.TblSalesOrderColor1 = null;
                            cd.CreatedBy = userIserial; cd.CreationDate = DateTime.Now;
                        });
                        newRow.TblContractPaymentByPeriods.ForEach(cd => {
                            cd.CreatedBy = userIserial; cd.CreationDate = DateTime.Now;
                        });

                        if (newRow.TblContractDetails.FirstOrDefault() != null)
                        {
                            newRow.TblLkpBrandSection = newRow.TblContractDetails.FirstOrDefault().TblLkpBrandSection;
                        }

                        //   newRow.TblLkpBrandSection = null;
                        newRow.CreatedBy      = userIserial;
                        newRow.CreationDate   = DateTime.Now;
                        newRow.LastChangeDate = DateTime.Now;
                        newRow.LastChangeUser = userIserial;

                        context.TblContractHeaders.AddObject(newRow);
                    }
                    context.SaveChanges();
                }
                catch (Exception ex) { throw ex; }
                TblContractHeader rowTemp = newRow.Clone();
                try
                {
                    if (newRow.Approved)
                    {
                        try
                        {
                            var emailTo      = context.tblChainSetups.FirstOrDefault(s => s.sGlobalSettingCode == "ContractApproveEmailTo");
                            var emailFrom    = context.tblChainSetups.FirstOrDefault(s => s.sGlobalSettingCode == "ContractApproveEmailFrom");
                            var emailBody    = context.tblChainSetups.FirstOrDefault(s => s.sGlobalSettingCode == "ContractApproveEmailBody");
                            var emailSubject = context.tblChainSetups.FirstOrDefault(s => s.sGlobalSettingCode == "ContractApproveEmailSubject");
                            if (emailTo != null && emailFrom != null && emailBody != null &&
                                emailSubject != null &&
                                //!emailTo.sSetupValue.Split(';').Any(e => !SharedOperation.IsValidEmail(e)) &&
                                SharedOperation.IsValidEmail(emailFrom.sSetupValue))
                            {
                                string storeMail = emailTo.sSetupValue;
                                SharedOperation.SendEmail(null, emailFrom.sSetupValue,
                                                          emailTo.sSetupValue.Split(';').ToList(), string.Format(emailSubject.sSetupValue,
                                                                                                                 newRow.Code), string.Format(emailBody.sSetupValue, newRow.Code));
                            }
                        }
                        catch (Exception ex) { }
                    }
                    foreach (var item in GetContractDetail(0, int.MaxValue, newRow.Iserial))
                    {
                        var tblContractDetail = item.Clone();
                        tblContractDetail.TblLkpBrandSection1 = item.TblLkpBrandSection1;
                        tblContractDetail.TblSalesOrderColor1 = item.TblSalesOrderColor1;
                        rowTemp.TblContractDetails.Add(tblContractDetail);
                    }
                    foreach (var item in GetContractPaymentDetail(0, int.MaxValue, newRow.Iserial))
                    {
                        var tblContractPaymentByPeriod = item.Clone();
                        rowTemp.TblContractPaymentByPeriods.Add(tblContractPaymentByPeriod);
                    }
                    using (var db = new ccnewEntities(SharedOperation.GetSqlConnectionString(company)))
                    {
                        rowTemp.Supplier = db.TBLsuppliers.FirstOrDefault(s => s.Iserial == newRow.SupplierIserial);
                        rowTemp.Currency = db.TblCurrencyTests.FirstOrDefault(c => c.Iserial == rowTemp.TblCurrency);
                    }
                }
                catch { }
                return(rowTemp);
            }
        }
Beispiel #5
0
        private TblAdjustmentHeader UpdateOrInsertAdjustmentHeader(TblAdjustmentHeader newRow, int index, int userIserial, out int outindex)// )
        {
            outindex = index;
            using (var context = new WorkFlowManagerDBEntities())
            {
                try
                {
                    var oldRow = context.TblAdjustmentHeaders.Include(nameof(TblAdjustmentHeader.TblAdjustmentDetails)).Include(nameof(
                                                                                                                                    TblAdjustmentHeader.TblWarehouse)).FirstOrDefault(th => th.Iserial == newRow.Iserial);
                    var tempwarhouse = newRow.TblWarehouse;
                    newRow.TblWarehouse = null;
                    foreach (var item in newRow.TblAdjustmentDetails)
                    {
                        item.AvailableQuantity  = item.ItemAdjustment.AvailableQuantity;
                        item.DifferenceQuantity = item.ItemAdjustment.DifferenceQuantity;
                        item.CountedQuantity    = item.ItemAdjustment.CountedQuantity;
                        item.Cost = item.ItemAdjustment.Cost;
                    }
                    if (oldRow != null)// الهيدر موجود قبل كده
                    {
                        //// هحذف الى اتحذف
                        //foreach (var item in oldRow.TblAdjustmentDetails)
                        //{
                        //    if (!newRow.TblAdjustmentDetails.Any(td => td.Iserial == item.Iserial))// مش موجود فى الجديد يبقى اتحذف
                        //        DeleteAdjustmentDetail(item);
                        //}
                        foreach (var item in newRow.TblAdjustmentDetails.ToArray())
                        {
                            // هشوف بقى الى اتعدل والجديد
                            int temp, headeriserial;//item.ItemAdjustment
                            headeriserial                = item.AdjustmentHeaderIserial;
                            item.TblAdjustmentHeader     = null;
                            item.AdjustmentHeaderIserial = headeriserial;
                            UpdateOrInsertAdjustmentDetail(item, 1, out temp);
                            item.TblAdjustmentHeader = newRow;
                        }
                        //context.Entry(oldRow).CurrentValues.SetValues(newRow);
                        var result = SharedOperation.GenericUpdate(oldRow, newRow, context);

                        if (result.Count() > 0)
                        {
                            newRow.LastChangeUser = userIserial;
                            newRow.LastChangeDate = DateTime.Now;
                        }
                    }
                    else// الهيدر ده جديد
                    {
                        var warehouse = context.TblWarehouses.FirstOrDefault(w => w.Iserial == newRow.WarehouseIserial);
                        var seq       = warehouse.AdjustIn;
                        var seqRow    = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == seq);
                        newRow.Code = SharedOperation.HandelSequence(seqRow);

                        newRow.CreatedBy      = userIserial;
                        newRow.CreationDate   = DateTime.Now;
                        newRow.LastChangeDate = DateTime.Now;
                        newRow.LastChangeUser = userIserial;

                        context.TblAdjustmentHeaders.AddObject(newRow);
                    }
                    context.SaveChanges();
                    //if (newRow.EntityState != System.Data.EntityState.Detached && newRow.EntityState != System.Data.EntityState.Added)
                    //    context.Detach(newRow);
                    //if (newRow.TblWarehouse == null)
                    //    newRow.TblWarehouse = context.TblWarehouses.AsNoTracking().FirstOrDefault(w => w.Iserial == newRow.WarehouseIserial);// tempwarhouse;
                    foreach (var item in newRow.TblAdjustmentDetails)
                    {
                        GetAdjustmentItemDetails(context, item);
                    }
                }
                catch (Exception ex) { throw ex; }
                return(newRow);
            }
        }
Beispiel #6
0
        internal void GetDailySalesCommision(
            int store, DateTime from, DateTime to, int userIserial, string company)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            int transactionType = 10;
            int journalint      = Convert.ToInt32(
                GetRetailChainSetupByCode("SalesCommissionJournalIserial", company).sSetupValue);   // Code = 1
            var commissionAccount =
                GetRetailChainSetupByCode("SalesCommissionAccount", company);
            var taxAccount =
                GetRetailChainSetupByCode("EarnTaxAccount", company);

            Entity salesCommissionEntity, taxEntity;
            List <TblLedgerHeader> oldLedgers;
            List <GetSalesDailyCommission_Result> query;

            using (var context = new ccnewEntities(SharedOperation.GetSqlConnectionString(company)))
            {
                context.CommandTimeout = 0;
                salesCommissionEntity  = context.Entities.FirstOrDefault(e => e.scope == 0 &&
                                                                         e.Code == commissionAccount.sSetupValue &&
                                                                         e.TblJournalAccountType == 15);
                taxEntity = context.Entities.FirstOrDefault(e => e.scope == 0 &&
                                                            e.Code == taxAccount.sSetupValue &&
                                                            e.TblJournalAccountType == 0);
                try
                {
                    query = context.GetSalesDailyCommission(store, from, to).ToList();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                //query = context.tblsalesdailycommisions.Where(r =>
                //   r.DocDate >= from && r.DocDate <= to);

                // var dquery = context.GetSalesDailyCommission(store, from, to).ToList().FirstOrDefault(x => x.tblstore == 173);
            }
            //var transactionOptions = new TransactionOptions
            //{
            //    IsolationLevel = IsolationLevel.ReadCommitted,
            //    Timeout = TimeSpan.FromSeconds(1200) //assume 10 min is the timeout time
            //};
            //using (var scope = new TransactionScope(TransactionScopeOption.Required, TimeSpan.FromSeconds(1200)))
            {
                using (var context = new ccnewEntities(SharedOperation.GetSqlConnectionString(company)))
                {
                    context.CommandTimeout = 0;
                    // Old Ledgers to be deleted
                    oldLedgers =
                        context.TblLedgerHeaders.Where(
                            x => x.TblTransactionType == transactionType && x.DocDate.Value >= from && x.DocDate.Value <= to).ToList();
                    // Delete old ledgers
                    foreach (var variable in oldLedgers)
                    {
                        context.TblLedgerHeaders.DeleteObject(variable);
                    }
                    context.SaveChanges();
                }
                foreach (var item in query.GroupBy(r => new { r.docdate }))
                // Parallel.ForEach(query.GroupBy(r => new { r.docdate }), item =>
                {
                    using (var context = new ccnewEntities(SharedOperation.GetSqlConnectionString(company)))
                    {
                        context.CommandTimeout = 0;
                        var description = string.Format("اثبات عمولات بيعية" + " {0}", item.Key.docdate.Value.ToString("dd/MM/yyyy"));
                        int sequence    = 25;
                        var seq         = context.TblSequences.FirstOrDefault(s => s.Iserial == sequence);

                        var newLedgerHeaderRow = new TblLedgerHeader
                        {
                            CreatedBy          = userIserial,
                            CreationDate       = DateTime.Now,
                            Description        = description,
                            DocDate            = item.Key.docdate,
                            TblJournal         = journalint,
                            TblTransactionType = transactionType,
                            TblJournalLink     = 0//item.Iserial
                        };
                        newLedgerHeaderRow.Code = SharedOperation.HandelSequence(seq, company, 0, 0, 0);
                        int tmp;
                        newLedgerHeaderRow = UpdateOrInsertTblLedgerHeaders(newLedgerHeaderRow, true, 0, out tmp, userIserial, company);//context,

                        decimal taxTotal = 0;
                        foreach (var innerItem in item)
                        {
                            var storeRec = context.TblStores
                                           .Include(nameof(TblStore.TblStoreCommission))
                                           .FirstOrDefault(s => s.iserial == innerItem.tblstore);

                            decimal taxPercent =
                                storeRec.TblStoreCommission.ManagerComm * (innerItem.MaxCommision ?? 0) / 100 * storeRec.TblStoreCommission.ManagerTax +
                                storeRec.TblStoreCommission.AssistantComm * (innerItem.MaxCommision ?? 0) / 100 * storeRec.TblStoreCommission.AssistantTax +
                                storeRec.TblStoreCommission.SalesManComm * (innerItem.MaxCommision ?? 0) / 100 * storeRec.TblStoreCommission.SalesManTax;
                            decimal commissionPercentTotal =
                                storeRec.TblStoreCommission.ManagerComm * (innerItem.MaxCommision ?? 0) / 100 +
                                storeRec.TblStoreCommission.AssistantComm * (innerItem.MaxCommision ?? 0) / 100 +
                                storeRec.TblStoreCommission.SalesManComm * (innerItem.MaxCommision ?? 0) / 100;
                            //decimal taxPercent =
                            //  storeRec.TblStoreCommission.ManagerComm  / 100 * storeRec.TblStoreCommission.ManagerTax +
                            //  storeRec.TblStoreCommission.AssistantComm  / 100 * storeRec.TblStoreCommission.AssistantTax +
                            //  storeRec.TblStoreCommission.SalesManComm  / 100 * storeRec.TblStoreCommission.SalesManTax;
                            //decimal commissionPercentTotal =
                            //    storeRec.TblStoreCommission.ManagerComm  / 100 +
                            //    storeRec.TblStoreCommission.AssistantComm  / 100 +
                            //    storeRec.TblStoreCommission.SalesManComm  / 100;
                            decimal commissionTotal = (innerItem.NetSalesAfterVAT ?? 0) * commissionPercentTotal;
                            if (commissionTotal == 0)
                            {
                                continue;
                            }
                            // Commission Entity
                            var commissionLedgerDetail = new TblLedgerMainDetail
                            {
                                Amount       = commissionTotal,
                                Description  = description,
                                ExchangeRate = 1,
                                TblCurrency  = 1,
                                TransDate    = innerItem.docdate,

                                TblJournalAccountType = 15,
                                EntityAccount         = salesCommissionEntity.Iserial,                                          //Entity Iserial
                                GlAccount             = salesCommissionEntity.AccountIserial,                                   // Account Iserial
                                TblLedgerHeader       = newLedgerHeaderRow.Iserial,
                                PaymentRef            = "",                                                                     //innerItem.Iserial.ToString(),
                                DrOrCr = true                                                                                   // true debit or false for credit
                            };
                            UpdateOrInsertTblLedgerMainDetails(commissionLedgerDetail, true, 0, out tmp, company, userIserial); //context,

                            decimal itemTax = (innerItem.NetSalesAfterVAT ?? 0) * taxPercent;

                            // Store Entity
                            var storeEntity = context.Entities.FirstOrDefault(e => e.scope == 0 &&
                                                                              e.Code == storeRec.code && e.TblJournalAccountType == 14);
                            if (storeEntity == null)
                            {
                                throw new Exception("store with code " + storeRec.code + " is not linked to Payable ");
                            }

                            var storeLedgerDetail = new TblLedgerMainDetail
                            {
                                Amount                = commissionTotal - itemTax,
                                Description           = description,
                                ExchangeRate          = 1,
                                TblCurrency           = 1,
                                TransDate             = innerItem.docdate,
                                TblJournalAccountType = 14,
                                EntityAccount         = storeEntity.Iserial,                                               //Entity Iserial
                                GlAccount             = storeEntity.AccountIserial,                                        // Account Iserial
                                TblLedgerHeader       = newLedgerHeaderRow.Iserial,
                                PaymentRef            = "",                                                                //innerItem.Iserial.ToString(),
                                DrOrCr                = false                                                              // true debit or false for credit
                            };
                            UpdateOrInsertTblLedgerMainDetails(storeLedgerDetail, true, 0, out tmp, company, userIserial); //context,

                            // Cost Center
                            var storeCostcenter = new TblGlRuleDetail();
                            storeCostcenter = FindCostCenterByType(storeCostcenter, 8, innerItem.tblstore ?? 0, company); //, context
                            CreateTblLedgerDetailCostCenter(company, commissionLedgerDetail.Amount ?? 0,
                                                            commissionLedgerDetail, storeCostcenter);                     //, context

                            taxTotal += itemTax;
                        }

                        // Tax Entity
                        var taxLedgerDetail = new TblLedgerMainDetail
                        {
                            Amount                = taxTotal,//item.Sum(r => r.Commision) * 0.05M,
                            Description           = description,
                            ExchangeRate          = 1,
                            TblCurrency           = 1,
                            TransDate             = item.Key.docdate,
                            TblJournalAccountType = 0,
                            EntityAccount         = taxEntity.Iserial,                                               //Entity Iserial
                            GlAccount             = taxEntity.AccountIserial,                                        // Account Iserial
                            TblLedgerHeader       = newLedgerHeaderRow.Iserial,
                            PaymentRef            = "0",                                                             //innerItem.Iserial.ToString(),
                            DrOrCr                = false                                                            // true debit or false for credit
                        };
                        UpdateOrInsertTblLedgerMainDetails(taxLedgerDetail, true, 0, out tmp, company, userIserial); //context,
                    }
                }//);
            }
            //scope.Complete();
            stopwatch.Stop();
            Console.Error.WriteLine("Sequential loop time in milliseconds: {0}",
                                    stopwatch.ElapsedMilliseconds);
        }
Beispiel #7
0
        private TblPurchaseReceiveHeader UpdateOrInsertTblPurchaseReceiveHeader(TblPurchaseReceiveHeader newRow, int index, out int outindex, string createdBy, int userIserial)
        {
            outindex = index;
            var totallist = new List <TblPurchaseReceiveDetail>();

            using (var context = new WorkFlowManagerDBEntities())
            {
                var newrowRet = new TblPurchaseReceiveHeader();
                var oldRow    = (from e in context.TblPurchaseReceiveHeaders.Include("TblPurchaseReceiveDetails")
                                 where e.Iserial == newRow.Iserial
                                 select e).SingleOrDefault();
                if (oldRow != null)
                {
                    newRow.CreatedBy       = oldRow.CreatedBy;
                    newRow.CreationDate    = oldRow.CreationDate;
                    newRow.LastUpdatedBy   = createdBy;
                    newRow.LastUpdatedDate = DateTime.Now;
                    SharedOperation.GenericUpdate(oldRow, newRow, context);
                    var OlDheader = context.TblPurchaseOrderHeaderRequests.FirstOrDefault(w => w.Iserial == oldRow.TblPurchaseOrderHeaderRequest);
                    if (OlDheader.AxPurchase == null)
                    {
                        foreach (var VARIABLE in oldRow.TblPurchaseReceiveDetails)
                        {
                            totallist.Add(VARIABLE);
                        }
                    }
                }
                else
                {
                    var warehouse = context.TblWarehouses.FirstOrDefault(w => w.Iserial == newRow.TblWarehouse);

                    foreach (var VARIABLE in newRow.TblPurchaseReceiveDetails)
                    {
                        totallist.Add(VARIABLE);
                    }
                    newRow.TblPurchaseReceiveDetails.Clear();

                    if (totallist.Any(w => w.Qty > 0))
                    {
                        foreach (var variable in totallist.Where(x => x.Qty > 0))
                        {
                            newRow.TblPurchaseReceiveDetails.Add(variable);
                        }

                        var seqRow = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == warehouse.Receive);
                        newRow.DocCode       = SharedOperation.HandelSequence(seqRow);
                        newRow.CreatedBy     = createdBy;
                        newRow.CreationDate  = DateTime.Now;
                        newRow.TblInventType = 1;

                        context.TblPurchaseReceiveHeaders.AddObject(newRow);
                    }
                    if (totallist.Any(w => w.Qty < 0))
                    {
                        newrowRet = new TblPurchaseReceiveHeader
                        {
                            DocDate      = newRow.DocDate,
                            RefNo        = newRow.RefNo,
                            Notes        = newRow.Notes,
                            TblWarehouse = newRow.TblWarehouse,
                            Vendor       = newRow.Vendor,
                            TblPurchaseOrderHeaderRequest = newRow.TblPurchaseOrderHeaderRequest,
                            Iserial = 0,
                        };
                        newrowRet.TblPurchaseReceiveDetails.Clear();
                        foreach (var variable in totallist.Where(x => x.Qty < 0))
                        {
                            newrowRet.TblPurchaseReceiveDetails.Add(variable);
                        }

                        var seqRow = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == warehouse.RetReceive);
                        newrowRet.DocCode       = SharedOperation.HandelSequence(seqRow);
                        newrowRet.CreatedBy     = createdBy;
                        newrowRet.CreationDate  = DateTime.Now;
                        newrowRet.TblInventType = 2;
                        context.TblPurchaseReceiveHeaders.AddObject(newrowRet);
                    }
                }
                context.SaveChanges();

                //if (true)
                //{

                //}

                //var ListOfRec = (from e in context.TblPurchaseReceiveDetails
                //                 where e.TblPurchaseReceiveHeader == newRow.Iserial
                //                 select e).ToList();
                //newRow.TblPurchaseReceiveDetails = new System.Data.Objects.DataClasses.EntityCollection<TblPurchaseReceiveDetail>();
                //foreach (var item in ListOfRec)
                //{

                //    newRow.TblPurchaseReceiveDetails.Add(item);
                //}

                //foreach (var VARIABLE in newRow.TblPurchaseReceiveDetails)
                //{
                //    totallist.Add(VARIABLE);
                //}
                if (totallist.Any(w => w.Qty > 0))
                {
                    PoPlanPurchase(newRow.Iserial, userIserial);

                    ReceivepackingSlip(newRow.Iserial, userIserial);
                }
                if (totallist.Any(w => w.Qty < 0))
                {
                    PoPlanPurchase(newrowRet.Iserial, userIserial);
                    //var header = context.TblPurchaseReceiveHeaders.Include("TblPurchaseOrderHeaderRequest1").Include("TblPurchaseReceiveDetails.TblPurchaseOrderDetailRequest1").FirstOrDefault(w => w.Iserial == newrowRet.Iserial);
                    ReceivepackingSlip(newrowRet.Iserial, userIserial);
                }
                if (totallist.Any(w => w.Qty > 0))
                {
                    var purchaserec = context.TblPurchaseReceiveHeaders.Include("TblPurchaseReceiveDetails").FirstOrDefault(w => w.Iserial == newRow.Iserial);

                    foreach (var item in purchaserec.TblPurchaseReceiveDetails.ToList())
                    {
                        var purchaseOrderDetailRequest = context.TblPurchaseOrderDetailRequests.FirstOrDefault(w => w.Iserial == item.TblPurchaseOrderDetailRequest);
                        purchaseOrderDetailRequest.BatchNo    = "";
                        purchaseOrderDetailRequest.ReceiveNow = 0;
                    }
                }
                if (totallist.Any(w => w.Qty < 0))
                {
                    var purchaserec = context.TblPurchaseReceiveHeaders.Include("TblPurchaseReceiveDetails").FirstOrDefault(w => w.Iserial == newrowRet.Iserial);
                    foreach (var item in purchaserec.TblPurchaseReceiveDetails.ToList())
                    {
                        var purchaseOrderDetailRequest = context.TblPurchaseOrderDetailRequests.FirstOrDefault(w => w.Iserial == item.TblPurchaseOrderDetailRequest);
                        purchaseOrderDetailRequest.BatchNo    = "";
                        purchaseOrderDetailRequest.ReceiveNow = 0;
                    }
                }
                return(newRow);
            }
        }
        private TblGlCashTransactionHeader UpdateOrInsertTblGlCashTransactionHeader(
            TblGlCashTransactionHeader newRow, bool save, int index, int user, bool approve, out int outindex,
            string company)
        {
            using (var scope = new TransactionScope())
            {
                #region Code
                //bool ww = DateTime.Now > DateTime.Now.AddDays(1);

                outindex = index;
                using (var entity = new ccnewEntities(GetSqlConnectionString(company)))
                {
                    var GlCashsetting = entity.TblGlCashTypeSettings.Include(nameof(TblGlCashTypeSetting.TblJournal1)).FirstOrDefault(x => x.Iserial == newRow.TblGlCashTypeSetting);
                    if (save)
                    {
                        try
                        {
                            var firstrow       = newRow.TblGlCashTransactionDetails.FirstOrDefault();
                            var entitySelected =
                                entity.Entities.FirstOrDefault(
                                    x => x.TblJournalAccountType == firstrow.TblJournalAccountType &&
                                    x.Iserial == firstrow.EntityAccount);
                            // newRow.Description = entitySelected.Ename;
                        }
                        catch (Exception)
                        {
                        }

                        newRow.CreationDate = DateTime.Now;
                        newRow.CreatedBy    = user;
                        //var setting =
                        //    entity.TblGlCashTypeSettings.FirstOrDefault(
                        //        x => x.Iserial == newRow.TblGlCashTypeSetting).TblSequence;
                        var journal = entity.TblSequences.FirstOrDefault(x => x.Iserial == GlCashsetting.TblSequence);
                        // var journal = entity.TblSequences.FirstOrDefault(x => x.Iserial == GlCashsetting.TblSequence);
                        int temp = 0;
                        newRow.Code = SharedOperation.HandelSequence(newRow.Code, journal, "TblLedgerHeader", company, 0,
                                                                     newRow.DocDate.Value.Month, newRow.DocDate.Value.Year, out temp);
                        newRow.CreationDate = DateTime.Now;
                        entity.TblGlCashTransactionHeaders.AddObject(newRow);
                    }
                    else
                    {
                        var oldRow = (from e in entity.TblGlCashTransactionHeaders
                                      where e.Iserial == newRow.Iserial
                                      select e).SingleOrDefault();
                        if (oldRow != null)
                        {
                            foreach (var newDetailRow in newRow.TblGlCashTransactionDetails.ToList())
                            {
                                if (newDetailRow.Iserial == 0)
                                {
                                    newDetailRow.TblGlCashTransactionHeader1 = null;
                                    newDetailRow.TblGlCashTransactionHeader  = oldRow.Iserial;
                                    entity.TblGlCashTransactionDetails.AddObject(newDetailRow);
                                }
                                else
                                {
                                    var oldRowDetail = (from e in entity.TblGlCashTransactionDetails
                                                        where e.Iserial == newDetailRow.Iserial
                                                        select e).SingleOrDefault();
                                    if (oldRowDetail != null)
                                    {
                                        foreach (var item in newDetailRow.TblGlCashTransactionDetailCostCenters.ToList())
                                        {
                                            if (item.Iserial == 0)
                                            {
                                                item.TblGlCashTransactionDetail1 = null;
                                                item.TblGlCashTransactionDetail  = newDetailRow.Iserial;
                                                entity.TblGlCashTransactionDetailCostCenters.AddObject(item);
                                            }
                                        }

                                        GenericUpdate(oldRowDetail, newDetailRow, entity);
                                    }
                                }
                            }
                            GenericUpdate(oldRow, newRow, entity);
                        }
                    }
                    entity.SaveChanges();
                    if (approve)
                    {
                        var ledgerheader = entity.TblLedgerHeaders.Any(
                            x => x.TblJournalLink == newRow.Iserial && x.TblTransactionType == 11);
                        if (!ledgerheader)
                        {
                            try
                            {
                                PostTblGlCashTransactionHeader(newRow.Iserial, user, company, newRow.Code);
                            }
                            catch (Exception)
                            {
                                var ledgerToDelete = entity.TblLedgerHeaders.Where(
                                    x => x.TblJournalLink == newRow.Iserial && x.TblTransactionType == 11).ToList();
                                foreach (var ledgerRow in ledgerToDelete)
                                {
                                    entity.TblLedgerHeaders.DeleteObject(ledgerRow);
                                }
                                throw;
                            }
                            newRow.Approved = true;
                        }
                    }

                    try
                    {
                        entity.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        if (ExceptionContainsErrorCode(ex, 2627))
                        {
                            entity.Detach(newRow);
                            UpdateOrInsertTblGlCashTransactionHeader(newRow, save, index, user, approve, out outindex, company);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }

                #endregion Code
                scope.Complete();
                return(newRow);
            }
        }
Beispiel #9
0
        private TblTransferHeader UpdateOrInsertTransferHeader(TblTransferHeader newRow, int index, int userIserial, out int outindex)// )
        {
            outindex = index;
            using (var context = new WorkFlowManagerDBEntities())
            {
                try
                {
                    var oldRow = context.TblTransferHeaders.Include(nameof(TblTransferHeader.TblTransferDetails)).FirstOrDefault(th => th.Iserial == newRow.Iserial);
                    newRow.TblWarehouseFrom = null;
                    newRow.TblWarehouseTo   = null;
                    if (oldRow != null)// الهيدر موجود قبل كده
                    {
                        newRow.LastChangeUser = userIserial;
                        newRow.LastChangeDate = DateTime.Now;
                        if (!oldRow.Approved && newRow.Approved)// كده لسه معموله ابروف
                        {
                            var warehouseTo = context.TblWarehouses.FirstOrDefault(w => w.Iserial == newRow.WarehouseTo);
                            var seqTo       = warehouseTo.TransferIn;
                            var seqRow      = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == seqTo);
                            newRow.CodeTo      = SharedOperation.HandelSequence(seqRow);
                            newRow.ApproveDate = DateTime.Now;
                            newRow.ApprovedBy  = userIserial;
                        }
                        //// هحذف الى اتحذف
                        //foreach (var item in oldRow.TblTransferDetails)
                        //{
                        //    if (!newRow.TblTransferDetails.Any(td => td.Iserial == item.Iserial))// مش موجود فى الجديد يبقى اتحذف
                        //        DeleteTransferDetail(item);
                        //}
                        foreach (var item in newRow.TblTransferDetails.ToArray())
                        {
                            // هشوف بقى الى اتعدل والجديد
                            int temp, headeriserial;//item.ItemTransfer
                            headeriserial          = item.TransferHeader;
                            item.TblTransferHeader = null;
                            item.TransferHeader    = headeriserial;
                            UpdateOrInsertTransferDetail(item, 1, out temp);
                            item.TblTransferHeader = newRow;
                        }
                        //context.Entry(oldRow).CurrentValues.SetValues(newRow);
                        SharedOperation.GenericUpdate(oldRow, newRow, context);
                    }
                    else// الهيدر ده جديد
                    {
                        var warehouseFrom = context.TblWarehouses.FirstOrDefault(w => w.Iserial == newRow.WarehouseFrom);
                        var seq           = warehouseFrom.TransferOut;
                        var seqRow        = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == seq);
                        newRow.CodeFrom = SharedOperation.HandelSequence(seqRow);
                        if (newRow.Approved)// كده معموله ابروف
                        {
                            var warehouseTo = context.TblWarehouses.FirstOrDefault(w => w.Iserial == newRow.WarehouseTo);
                            var seqTo       = warehouseTo.TransferIn;
                            var seqRowTo    = context.TblSequenceProductions.FirstOrDefault(x => x.Iserial == seqTo);
                            newRow.CodeTo      = SharedOperation.HandelSequence(seqRowTo);
                            newRow.ApproveDate = DateTime.Now;
                            newRow.ApprovedBy  = userIserial;
                        }
                        else
                        {
                            newRow.CodeTo = newRow.CodeFrom;
                        }
                        newRow.CreatedBy      = userIserial;
                        newRow.CreationDate   = DateTime.Now;
                        newRow.LastChangeDate = DateTime.Now;
                        newRow.LastChangeUser = userIserial;

                        context.TblTransferHeaders.AddObject(newRow);
                    }
                    context.SaveChanges();
                    foreach (var item in newRow.TblTransferDetails)
                    {
                        GetTransferItemDetails(context, item);
                    }
                }
                catch (Exception ex) { throw ex; }
                return(newRow);
            }
        }