public static void GrantToManagerAccessToCashflow(tbl_Cashflow cashflow, Entities db)
 {
     if (cashflow.ManagerID.HasValue)
     {
         if (db.tbl_CashflowRight.Count(x => x.RecordID == cashflow.ID && x.AdminUnitID == cashflow.ManagerID) == 0)
         {
             Guid managerAdminUnitID = db.tbl_AdminUnit.FirstOrDefault(x => x.UserContactID == cashflow.ManagerID).ID;
             tbl_CashflowRight rights = new tbl_CashflowRight
             {
                 AdminUnitID = managerAdminUnitID,
                 CanChangeAccess = 1,
                 CanDelete = 0,
                 CanRead = 1,
                 CanWrite = 1,
                 ID = Guid.NewGuid(),
                 RecordID = cashflow.ID
             };
             db.tbl_CashflowRight.Add(rights);
         }
     }
 }
        public tbl_Cashflow CreateCashflow(Entities db, Transfer t)
        {
            tbl_Cashflow c = new tbl_Cashflow();
            
            c.UID1C = t.UID1C;

            //TMP
            c.MailSent = 1;

            c.Obj1cDocNumIn = t.НомерДокВходящий;
            c.ModifiedByID = Helper.GetSupervisorID();
            c.ModifiedOn = DateTime.Now;
            c.CreatedByID = Helper.GetSupervisorID();
            c.CreatedOn = DateTime.Now;

            string cID = Helper.getDs_CompanyID(t.Company);
            c.CompanyID = new Guid(cID);
            // 01 НОМЕР
            c.CFNumber = Helper.GetNextNumber(db);

            // 02 НАЗНАЧЕНИЕ
            c.Subject = t.НазначениеПлатежа;
            if(t.ВидДвижения != null)
            {
                if(t.ВидДвижения.Наименование.Length>0)
                c.Subject += " (" + t.ВидДвижения.Наименование + ")";
            }
            if(c.Subject.Length > 249)
            {
                c.Subject = c.Subject.Substring(0, 246) + "...";
            }

            // 03 ОТ            
            c.DocDate = DateTime.Parse(t.ДатаДок);

            // 04 ТИП
            CashflowType cashflowType;
            if (t.Приход > 0)
                cashflowType = CashflowType.Income;
            else
                cashflowType = CashflowType.Expense;
            c.TypeID = Helper.GetCashflowTypeID(cashflowType);

            // 05 СТАТЬЯ NULL
            c.ClauseID = DbHelper.GetCashflowClauseID(db, t.ВидДвижения, t.Company);

            // 06 КАТЕГОРИЯ NULL
            // 07 ОТВЕТСТВЕННЫЙ
            c.OwnerID = Helper.GetOwnerID();

            // 08 СОСТОЯНИЕ
            c.StatusID = new Guid(Constants.CashflowStateFinishedID);

            // 09 ИНЦИДЕНТ NULL
            // 10 ВОЗДЕЙСТВИЕ NULL
            // 11 PL - (UseAsPandL - P&L) NULL

            // 12 КАССА 
            c.CashAccountID = new Guid(Constants.CashflowKassaID);
            // 13 ПЛАНИРУЕМАЯ ДАТА
            c.EstimatedDate = DateTime.Parse(t.ДатаДок);

            // 14 ФАКТИЧЕСКАЯ ДАТА
            c.ActualDate = DateTime.Parse(t.ДатаДок);

            // 15 ТИП РАСХОДА-ДОХОДА NULL
            // 16 ПЕРИОД
            c.PeriodID = Helper.GetPeriodID(db, c.ActualDate.Value);

            // 00 Контрагент
            string comments = "";
            Guid? AccountID = DbHelper.GetAccountID(db, t);
            if (!AccountID.HasValue)
            {
                comments += "Контрагент не найден: " + Helper.GetAccountNameCode(t) + ".\r\n";
            }
            
            // 19 УЧИТЫВАТЬ ПРИ ВЗАИМОРАСЧЁТАХ NULL
            // 20 ДЕБИТОР-КРЕДИТОР NULL
            // 21 АВТОМАТИЧЕСКИ РАССЧИТЫВАТЬ СУММУ
            c.AutocalcAmount = 1;

            // 22 ВАЛЮТ            
            c.CurrencyID = DbHelper.ConvertToCurrencyID(t.Валюта);

            // 23 СУММА
            if (cashflowType == CashflowType.Income)
                c.Amount = (decimal)t.Приход;
            else
                c.Amount = -1 * (decimal)t.Расход;
            
            // 24 ВНУТРЕННИЙ КУРС
            c.CurrencyRate = (decimal)t.Курс;

            // 25 СУММА В БАЗОВОЙ ВАЛЮТЕ NULL
            //c.BasicAmount = (int)(c.Amount / c.CurrencyRate);
            // 26 КОНТАКТ NULL
            // 27 СЧЁТ NULL
            // 28 ДОГОВОР
            Guid? ContractID = DbHelper.GetContractID(db, t);
            if (ContractID.HasValue)
            {
                c.ContractID = ContractID;
            }
            else
            {
                string ContractName = DbHelper.GetContractName(t);
                if(!String.IsNullOrEmpty(ContractName))
                comments += "Договор не найден: " + ContractName  + ".";
            }            
            // 29 ПРОДАЖА - получаем из договора
            if (ContractID.HasValue)
            {
                c.OpportunityID = DbHelper.GetOpportunityIDFromContract(db, ContractID);
            }

            // 30 МЕНЕДЖЕР - получаем из договора
            if (ContractID.HasValue)
            {
                c.ManagerID = DbHelper.GetManagerIDFromContract(db, ContractID);
            }
            else
                if (AccountID.HasValue)
                {
                    c.ManagerID = DbHelper.GetManagerIDFromAccount(db, AccountID);
                }
                else
                {
                    c.ManagerID = DbHelper.GetDefaultManagerID();
                }

            // 31 если найден договор, но не найден контрагент
            if (ContractID.HasValue && !AccountID.HasValue)
            {
                AccountID = DbHelper.GetAccountIDFromContract(db, ContractID);
            }

            // 17 ПЛАТЕЛЬЩИК
            // 18 ПОЛУЧАТЕЛЬ
            if (cashflowType == CashflowType.Income)
            {
                c.PayerID = AccountID;
                c.RecipientID = DbHelper.GetCompanyID(t.Company);
            }
            else
            {
                c.PayerID = DbHelper.GetCompanyID(t.Company);
                c.RecipientID = AccountID;
            }

            c.DebtorCreditorID = c.PayerID;
            // если назначение содержит номер счёта
            string PayDetails = t.НазначениеПлатежа;
            string InvoiceString = "счет ";
            if (PayDetails.Contains(InvoiceString))
            {
                int NumStart = PayDetails.IndexOf(InvoiceString) + 5;
                string substr1 = PayDetails.Substring(NumStart);
                int NumEnd = substr1.IndexOf(' ');
                string InvoiceNumber = "";
                if (NumEnd >= 0)
                    InvoiceNumber = substr1.Substring(0, NumEnd);
                // найти счёт
                // фильтр по номеру счёта                
                List<tbl_Invoice> invoices = db.tbl_Invoice.Where(i => i.InvoiceNumber == InvoiceNumber).ToList();
                // фильтр по дате счёта (год)?
                invoices = invoices.Where(i => i.InvoiceDate.Year == DateTime.Now.Year).ToList();
                // фильтр по контрагенту
                if (AccountID.HasValue)
                {
                    invoices = invoices.Where(i => i.CustomerID == AccountID).ToList();
                }
                if (invoices.Count > 0)
                {
                    tbl_Invoice i = invoices.First();
                    c.InvoiceID = i.ID;
                }
            }
            if (comments.Length > 249)
            {
                comments = comments.Substring(0, 246) + "...";
            }
            c.Comments = comments;            

            //t.КоррСчёт - пока не использовать
            c.ID = Guid.NewGuid();

            return c;
        }
 /// <summary>
 /// Create a new tbl_Cashflow object.
 /// </summary>
 /// <param name="id">Initial value of the ID property.</param>
 /// <param name="subject">Initial value of the Subject property.</param>
 /// <param name="autocalcAmount">Initial value of the AutocalcAmount property.</param>
 /// <param name="mailSent">Initial value of the MailSent property.</param>
 public static tbl_Cashflow Createtbl_Cashflow(global::System.Guid id, global::System.String subject, global::System.Int32 autocalcAmount, global::System.Int32 mailSent)
 {
     tbl_Cashflow tbl_Cashflow = new tbl_Cashflow();
     tbl_Cashflow.ID = id;
     tbl_Cashflow.Subject = subject;
     tbl_Cashflow.AutocalcAmount = autocalcAmount;
     tbl_Cashflow.MailSent = mailSent;
     return tbl_Cashflow;
 }
 /// <summary>
 /// Deprecated Method for adding a new object to the tbl_Cashflow EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddTotbl_Cashflow(tbl_Cashflow tbl_Cashflow)
 {
     base.AddObject("tbl_Cashflow", tbl_Cashflow);
 }
 public static string getHash(tbl_Cashflow c)
 {
     string[] keys = { ((long)c.Amount).ToString(), c.PayerID.ToString(), c.RecipientID.ToString() /*, c.Obj1cDocNumIn*/ };
     return Helper.CalculateMD5Hash(keys);
 }
 public static string getHashWithoutDocNum(tbl_Cashflow c)
 {
     string[] keys = { c.Amount.ToString(), c.PayerID.ToString(), c.RecipientID.ToString() };
     return Helper.CalculateMD5Hash(keys);
 }
        public tbl_Cashflow toTsCashflow(tbl_Cashflow p, Entities db)
        {
            tbl_Cashflow c = new tbl_Cashflow();

            string comments = "";
            c.Amount = decimal.Parse(this.Amount);
            c.Obj1cDocNumIn = this.Number;

            c.Subject = "Детализация: " + this.Contract;
            c.OpportunityID = p.OpportunityID;
            c.ManagerID = p.ManagerID;
            c.OwnerID = p.OwnerID;

            c.ActualDate = p.ActualDate;
            c.AutocalcAmount = p.AutocalcAmount;
            c.CampaignID = p.CampaignID;
            c.CashAccountID = p.CashAccountID;
            c.CategoryID = p.CategoryID;
            c.CFNumber = p.CFNumber;
            c.ClauseID = p.ClauseID;
            c.CompanyID = p.CompanyID;
            c.ContactID = p.ContactID;
            c.CreatedByID = p.CreatedByID;
            c.CreatedOn = DateTime.Now;
            c.CurrencyID = p.CurrencyID;
            c.CurrencyRate = p.CurrencyRate;
            c.DebtorCreditorID = p.DebtorCreditorID;
            c.Description = p.Description;
            c.DocDate = p.DocDate;
            c.EstimatedDate = p.EstimatedDate;
            c.ExpactablePayDate = p.ExpactablePayDate;
            c.ExpenseTypeID = p.ExpenseTypeID;
            c.ID = Guid.NewGuid();
            c.IncidentID = p.IncidentID;
            //c.LinkID = p.LinkID;
            c.MailSent = p.MailSent;
            c.ModifiedByID = p.ModifiedByID;
            c.ModifiedOn = DateTime.Now;
            c.PayerID = p.PayerID;
            c.PeriodID = p.PeriodID;
            c.ProjectID = p.ProjectID;
            c.RecipientID = p.RecipientID;
            c.ServiceAgreementID = p.ServiceAgreementID;
            c.StatusID = p.StatusID;
            c.TypeID = p.TypeID;
            c.UseAsCashflow = p.UseAsCashflow;
            c.UseAsPandL = p.UseAsPandL;

            //c.ContractID
            //c.InvoiceID
            string contractNumber = Helper.ParseContractNumber(this.Contract);
            Guid? ContractID = DbHelper.GetContractID(db, contractNumber);
            if (ContractID.HasValue)
            {
                c.ContractID = ContractID;
            }
            else
            {
                comments += "Договор не найден: " + this.Contract + ".";
            }

            // 29 ПРОДАЖА - получаем из договора
            if (ContractID.HasValue)
            {
                c.OpportunityID = DbHelper.GetOpportunityIDFromContract(db, ContractID);
            }

            // 30 МЕНЕДЖЕР - получаем из договора
            if (ContractID.HasValue)
            {
                c.ManagerID = DbHelper.GetManagerIDFromContract(db, ContractID);
            }
            else
                if (c.PayerID.HasValue)
                {
                    c.ManagerID = DbHelper.GetManagerIDFromAccount(db, c.PayerID);
                }
                else
                {
                    c.ManagerID = DbHelper.GetDefaultManagerID();
                }
            string InvoiceString = "счет ";
            string PayDetails = this.Contract;
            if (PayDetails.Contains(InvoiceString))
            {
                int NumStart = PayDetails.IndexOf(InvoiceString) + 5;
                string substr1 = PayDetails.Substring(NumStart);
                int NumEnd = substr1.IndexOf(' ');
                string InvoiceNumber = "";
                if (NumEnd >= 0)
                    InvoiceNumber = substr1.Substring(0, NumEnd);
                // найти счёт
                // фильтр по номеру счёта                
                List<tbl_Invoice> invoices = db.tbl_Invoice.Where(i => i.InvoiceNumber == InvoiceNumber).ToList();
                // фильтр по дате счёта (год)?
                invoices = invoices.Where(i => i.InvoiceDate.Year == DateTime.Now.Year).ToList();
                // фильтр по контрагенту
                if (c.PayerID.HasValue)
                {
                    invoices = invoices.Where(i => i.CustomerID == c.PayerID).ToList();
                }
                if (invoices.Count > 0)
                {
                    tbl_Invoice i = invoices.First();
                    c.InvoiceID = i.ID;
                }
            }
            c.Comments = comments;
            c.UID1C = c.CFNumber;
            // todo
            //c.BasicAmount = p.BasicAmount;            
            return c;
        }