예제 #1
0
        private async void ImportFile()
        {
            busyIndicator.IsBusy = true;

            List <DebtorTransDirectDebit> listDebTransPaym = new List <DebtorTransDirectDebit>();
            int index = 0;

            foreach (var rec in (IEnumerable <DebtorTransDirectDebit>)dgDebtorTranOpenGrid.ItemsSource)
            {
                int rowHandle = dgDebtorTranOpenGrid.GetRowHandleByListIndex(index);
                index++;
                listDebTransPaym.Add(rec);
            }

            var pairFile = new PropValuePair[]
            {
                PropValuePair.GenereteWhereElements(nameof(DebtorPaymentFileClient._Output), typeof(int), 0),
                PropValuePair.GenereteWhereElements(nameof(DebtorPaymentFileClient.IsOk), typeof(int), 0),
            };

            var debtorPaymFile = await api.Query <DebtorPaymentFileClient>(pairFile);

            var dialogInfo = Common.GetReturnFiles(api, listDebTransPaym, DebtorCache, MandateCache, PaymentFormatCache, debtorPaymFile);

            busyIndicator.IsBusy = false;

            UnicontaMessageBox.Show(dialogInfo, Uniconta.ClientTools.Localization.lookup("Message"));
        }
예제 #2
0
 public void test()
 {
     var api = UCInitializer.GetBaseAPI;
     var crit = new List<PropValuePair>();
     var pair = PropValuePair.GenereteWhereElements("KeyName", typeof(string), "Danske Bank");
     crit.Add(pair);
     var taskQryBankStatment = api.Query<BankStatementClient>(null, crit);
     taskQryBankStatment.Wait();
     var col = taskQryBankStatment.Result;
     if (col.Count() == 1)
     {
         var crit2 = new List<PropValuePair>();
         var pair1 = PropValuePair.GenereteWhereElements("BankId", typeof(int), "917755");
         crit2.Add(pair1);
         var pair2 = PropValuePair.GenereteOrderByElement("Date", true);
         crit2.Add(pair2);
         var taskQryBankStatmentLine = api.Query<BankStatementLineClient>(col, crit2);
         taskQryBankStatment.Wait();
         var col1 = taskQryBankStatmentLine.Result;
         foreach (var rec1 in col1)
         {
             //BankStatementLineClient nyrac = rec1.clo
             rec1._Text += " Test";
             var task = api.Update(rec1);
             task.Wait();
             var res = task.Result;
         }
     }
 }
예제 #3
0
        private void OpretNyeKonti_Click(object sender, EventArgs e)
        {
            var api = UCInitializer.GetBaseAPI;

            foreach (var recNyKontoplan in this.karNyKontoplanBindingSource.DataSource as KarNyKontoplan)
            {
                recKontoplan recKontoplan = null;
                if (recNyKontoplan.SkalOprettes)
                {
                    try
                    {
                        recKontoplan = (from x in Program.karKontoplan where x.Kontonr == recNyKontoplan.Kontonr select x).First();

                        var crit = new List <PropValuePair>();
                        var pair = PropValuePair.GenereteWhereElements("Account", typeof(String), recNyKontoplan.NytKontonr);
                        crit.Add(pair);
                        var taskQueryGLAccount = api.Query <GLAccountClient>(crit);
                        taskQueryGLAccount.Wait();
                        var col = taskQueryGLAccount.Result;
                        if (col.Count() == 0)
                        {
                            GLAccountClient recGLAccount = new GLAccountClient()
                            {
                                Account = recNyKontoplan.NytKontonr,
                                Name    = recNyKontoplan.Kontonavn,
                            };
                            if (recKontoplan.Type == "Drift")
                            {
                                if (recKontoplan.DK == "1")
                                {
                                    recGLAccount.AccountTypeEnum = Uniconta.DataModel.GLAccountTypes.Revenue;
                                }
                                else
                                {
                                    recGLAccount.AccountTypeEnum = Uniconta.DataModel.GLAccountTypes.Expense;
                                }
                            }
                            else
                            {
                                if (recKontoplan.DK == "0")
                                {
                                    recGLAccount.AccountTypeEnum = Uniconta.DataModel.GLAccountTypes.Asset;
                                }
                                else
                                {
                                    recGLAccount.AccountTypeEnum = Uniconta.DataModel.GLAccountTypes.Liability;
                                }
                            }

                            var taskInsertGLAccount = api.Insert(recGLAccount);
                            taskInsertGLAccount.Wait();
                            var err = taskInsertGLAccount.Result;
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
        public async override Task InitQuery()
        {
            if (debtorOrderLine._Item == null)
            {
                return;
            }

            busyIndicator.IsBusy = true;
            var pair = new PropValuePair[]
            {
                PropValuePair.GenereteWhereElements("Item", debtorOrderLine._Item, CompareOperator.Equal)
            };
            var lst = await api.Query <CreditorOrderLineClient>(pair);

            var orderRefLine = this.orderRefLine;

            foreach (var line in lst)
            {
                if (line._MarkingId == orderRefLine)
                {
                    line._marked = true;
                    break;
                }
            }
            dgCreditorOrderLineGrid.SetSource(lst);
            busyIndicator.IsBusy = false;
            dgCreditorOrderLineGrid.Visibility = Visibility.Visible;
        }
        async void CreateFiltersForData(string[] filterFld, int[] filterDateValues, double[] qtyValues, DateTime[] dates, string projectBudgetGrp)
        {
            var filterFldName  = filterFld[0];
            var filterFldValue = filterFld[1];

            inputs = new List <PropValuePair>();
            inputs.Add(PropValuePair.GenereteWhereElements(filterFldName, typeof(string), filterFldValue));

            if (BudgetGroupCache == null)
            {
                BudgetGroupCache = await api.LoadCache(typeof(Uniconta.DataModel.ProjectBudgetGroup));
            }
            inputsMaster = new List <UnicontaBaseEntity>();
            var budgetGrp = (ProjectBudgetGroup)BudgetGroupCache.Get(projectBudgetGrp);

            if (budgetGrp != null)
            {
                inputsMaster.Add((ProjectBudgetGroup)BudgetGroupCache.Get(projectBudgetGrp));
            }

            monthNumber = filterDateValues[0];
            quarterNo   = filterDateValues[1];
            year        = filterDateValues[2];
            normQty     = qtyValues[0];
            budgetQty   = qtyValues[1];
            fromDate    = dates[0];
            toDate      = dates[1];
        }
예제 #6
0
        public AllNotesPage(CrudAPI api, SQLCache AccountListCache) : base(api, null)
        {
            this.DataContext      = this;
            this.AccountListCache = AccountListCache;
            var arr = AccountListCache.GetKeyStrRecords;

            if (arr.Length > 0)
            {
                var AccountRange = string.Format("{0}..{1}", arr[0].KeyStr, arr[arr.Length - 1].KeyStr);
                glAccountDefaultFilter = new Uniconta.ClientTools.Controls.Filter[] { new Uniconta.ClientTools.Controls.Filter()
                                                                                      {
                                                                                          name = "Account", value = AccountRange
                                                                                      } };
                glAccountFilterValues = new List <PropValuePair>()
                {
                    PropValuePair.GenereteWhereElements("Account", typeof(string), AccountRange)
                };
            }
            InitializeComponent();
            SetRibbonControl(localMenu, dgGLAccount);
            dgGLAccount.BusyIndicator = busyIndicator;
            localMenu.OnItemClicked  += localMenu_OnItemClicked;
            GetMenuItem();
            ((TableView)childDgUserNotes.View).RowStyle = Application.Current.Resources["StyleRow"] as Style;
        }
예제 #7
0
            public Criterias Add(string pKey, long pValue)
            {
                ValuePairs.Add(PropValuePair.GenereteWhereElements(pKey, typeof(long), Convert.ToString(pValue)));
                Criterias that = this;

                return(that);
            }
예제 #8
0
            public Criterias Add(string pKey, string pValue)
            {
                ValuePairs.Add(PropValuePair.GenereteWhereElements(pKey, typeof(string), pValue));
                Criterias that = this;

                return(that);
            }
예제 #9
0
 void setItem(string item)
 {
     if (item != null)
     {
         MasterItem    = item;
         propValuePair = new PropValuePair[] { PropValuePair.GenereteWhereElements("ItemPart", typeof(string), item) };
     }
 }
        async private void BindGrid()
        {
            busyIndicator.IsBusy = true;
            dgVouchersGrid.UpdateMaster(new DocumentNoRef());
            await dgVouchersGrid.Filter(new [] { PropValuePair.GenereteWhereElements("Envelope", typeof(bool), "0") });

            busyIndicator.IsBusy = false;
        }
예제 #11
0
        public void export()
        {
            DateTime ExportFromDate = DateTime.Now.AddDays(-3);
            var      crit           = new List <PropValuePair>();
            var      pair           = PropValuePair.GenereteWhereElements("KeyName", typeof(string), "Danske Bank");

            crit.Add(pair);
            var taskQryBankStatment = m_api.Query <BankStatementClient>(crit);

            taskQryBankStatment.Wait();
            var col = taskQryBankStatment.Result;

            if (col.Count() == 1)
            {
                ExportFromDate = col[0].LastTransaction;
                var DaysSlip = col[0].DaysSlip;
                ExportFromDate = ExportFromDate.AddDays(-DaysSlip);
            }

            //ExportFromDate = DateTime.Now.AddDays(-70); //<-------------------Fjernes

            using (StringWriter sr = new StringWriter())
            {
                var qry = from w in m_dbData3060.tblbankkontos
                          where w.bankkontoid == m_bankkontoid && (w.skjul == null || w.skjul == false) && w.dato >= ExportFromDate
                          orderby w.dato
                          select w;

                int antal = qry.Count();

                string ln = @"pid;dato;tekst;beløb;saldo";
                sr.WriteLine(ln);

                foreach (var b in qry)
                {
                    ln  = "";
                    ln += @"""" + b.pid.ToString() + @"""" + ";";
                    ln += (b.dato == null) ? ";" : @"""" + ((DateTime)b.dato).ToString("dd.MM.yyyy") + @"""" + ";";
                    ln += (b.tekst == null) ? ";" : @"""" + b.tekst.Replace(";", " ") + @"""" + ";";
                    ln += (b.belob == null) ? ";" : @"""" + ((decimal)(b.belob)).ToString("0.00") + @"""" + ";";
                    ln += (b.saldo == null) ? ";" : @"""" + ((decimal)(b.saldo)).ToString("0.00") + @"""";
                    sr.WriteLine(ln);
                }

                //byte[] attachment = Encoding.Default.GetBytes(sr.ToString());
                byte[]         attachment = Encoding.GetEncoding(1251).GetBytes(sr.ToString());
                VouchersClient vc         = new VouchersClient()
                {
                    Text              = "DanskeErhverv",
                    Content           = "Bankkontoudtog",
                    Fileextension     = FileextensionsTypes.CSV,
                    VoucherAttachment = attachment,
                };
                var taskInsertVouchers = m_api.Insert(vc);
                taskInsertVouchers.Wait();
                var err = taskInsertVouchers.Result;
            }
        }
예제 #12
0
        public void open()
        {
            var            api = UCInitializer.GetBaseAPI;
            recNyKontoplan rec;
            FileStream     ts             = new FileStream(m_path, FileMode.Open, FileAccess.Read, FileShare.None);
            string         ln             = null;
            Regex          regexKontoplan = new Regex(@"""(.*?)"";|([^;]*);|(.*)$");

            using (StreamReader sr = new StreamReader(ts, Encoding.Default))
            {
                while ((ln = sr.ReadLine()) != null)
                {
                    int      i     = 0;
                    int      iMax  = 4;
                    string[] value = new string[iMax];
                    foreach (Match m in regexKontoplan.Matches(ln))
                    {
                        for (int j = 1; j <= 3; j++)
                        {
                            if (m.Groups[j].Success)
                            {
                                if (i < iMax)
                                {
                                    value[i++] = m.Groups[j].ToString();
                                    break;
                                }
                            }
                        }
                    }

                    Boolean wSkalOprettes = false;

                    if (value[1] != "x")
                    {
                        var crit = new List <PropValuePair>();
                        var pair = PropValuePair.GenereteWhereElements("Account", typeof(String), value[1]);
                        crit.Add(pair);
                        var task = api.Query <GLAccountClient>(crit);
                        task.Wait();
                        var col = task.Result;
                        if (col.Count() == 0)
                        {
                            wSkalOprettes = true;
                        }
                    }

                    rec = new recNyKontoplan
                    {
                        Kontonr      = Microsoft.VisualBasic.Information.IsNumeric(value[0]) ? int.Parse(value[0]) : (int?)null,
                        NytKontonr   = value[1],
                        Kontonavn    = value[2],
                        SkalOprettes = wSkalOprettes
                    };
                    this.Add(rec);
                }
            }
        }
        void BindGrid()
        {
            var propValuePair = new List <PropValuePair>()
            {
                PropValuePair.GenereteWhereElements("TableId", typeof(int), Convert.ToString(tableId))
            };

            Filter(propValuePair);
        }
        public void export()
        {
            DateTime ExportFromDate = DateTime.Now.AddDays(-3);
            var      api            = UCInitializer.GetBaseAPI;
            var      crit           = new List <PropValuePair>();
            var      pair           = PropValuePair.GenereteWhereElements("KeyName", typeof(string), "Danske Bank");

            crit.Add(pair);
            var taskQryBankStatment = api.Query <BankStatementClient>(null, crit);

            taskQryBankStatment.Wait();
            var col = taskQryBankStatment.Result;

            if (col.Count() == 1)
            {
                ExportFromDate = col[0].LastTransaction;
                var DaysSlip = col[0].DaysSlip;
                ExportFromDate.AddDays(-DaysSlip);
            }

            using (StringWriter sr = new StringWriter())
            {
                var qry = from w in Program.dbDataTransSumma.tblbankkontos
                          where w.bankkontoid == m_bankkontoid && (w.skjul == null || w.skjul == false) && w.dato >= ExportFromDate
                          orderby w.dato
                          select w;

                int antal = qry.Count();

                string ln = @"pid;dato;tekst;beløb;saldo";
                sr.WriteLine(ln);

                foreach (var b in qry)
                {
                    ln  = "";
                    ln += b.pid.ToString() + ";";
                    ln += (b.dato == null) ? ";" : ((DateTime)b.dato).ToString("dd.MM.yyyy") + ";";
                    ln += (b.tekst == null) ? ";" : b.tekst + ";";
                    ln += (b.belob == null) ? ";" : ((decimal)(b.belob)).ToString("0.00") + @";";
                    ln += (b.saldo == null) ? ";" : ((decimal)(b.saldo)).ToString("0.00");
                    sr.WriteLine(ln);
                }
                byte[]         attachment = Encoding.Default.GetBytes(sr.ToString());
                VouchersClient vc         = new VouchersClient()
                {
                    Text              = string.Format("Danske Bank Kontoudtog {0}", DateTime.Now),
                    Content           = "Bankkontoudtog",
                    DocumentDate      = DateTime.Now,
                    Fileextension     = FileextensionsTypes.CSV,
                    VoucherAttachment = attachment,
                };
                var taskInsertVouchers = api.Insert(vc);
                taskInsertVouchers.Wait();
                var err = taskInsertVouchers.Result;
            }
        }
예제 #15
0
        private Task Filter(IEnumerable <PropValuePair> propValuePair)
        {
            if (!string.IsNullOrWhiteSpace(Account))
            {
                propValuePair = new List <PropValuePair>()
                {
                    PropValuePair.GenereteWhereElements("Account", Account, CompareOperator.Equal)
                }
            }
            ;

            return(dgCreateOrderGrid.Filter(propValuePair));
        }
예제 #16
0
        async public Task <int> InsertVouchersClients(recKladder rec)
        {
            string mask_bilag = m_BilagPath + @"\Bilag {0}.pdf";
            var    api        = UCInitializer.GetBaseAPI;
            string hash       = null;

            byte[]   attachment = null;
            DateTime file_date  = DateTime.Now;

            try
            {
                string file_bilag        = string.Format(mask_bilag, rec.Bilag);
                var    fileinfo          = new FileInfo(file_bilag);
                int    file_bilag_length = (int)fileinfo.Length;
                file_date  = fileinfo.CreationTime;
                attachment = new byte[file_bilag_length];
                FileStream ts = new FileStream(file_bilag, FileMode.Open, FileAccess.Read, FileShare.None);
                ts.Read(attachment, 0, file_bilag_length);
                ts.Close();

                using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
                {
                    hash = Convert.ToBase64String(sha1.ComputeHash(attachment));
                }
                var crit = new List <PropValuePair>();
                var pair = PropValuePair.GenereteWhereElements("PostingInstruction", typeof(String), hash);
                crit.Add(pair);
                var collection = await api.Query <VouchersClient>(null, crit);

                if (collection.Count() > 0)
                {
                    return(collection[0].PrimaryKeyId);
                }
            }
            catch
            {
                return(0);
            }

            VouchersClient vc = new VouchersClient()
            {
                Text               = string.Format("Bilag {0}", rec.Bilag),
                DocumentDate       = file_date,
                Fileextension      = FileextensionsTypes.PDF,
                VoucherAttachment  = attachment,
                PostingInstruction = hash
            };
            var err = await api.Insert(vc);

            return(vc.PrimaryKeyId);
        }
예제 #17
0
        async private void JournalPosted(ProjectTransClient selectedItem)
        {
            var pairPostedJour = new PropValuePair[]
            {
                PropValuePair.GenereteWhereElements(nameof(ProjectJournalPostedClient.GLJournalPostedId), typeof(int), NumberConvert.ToString(selectedItem._JournalPostedId))
            };
            var result = await api.Query <ProjectJournalPostedClient>(pairPostedJour);

            if (result != null && result.Length == 1)
            {
                CWProjPostedClientFormView cwPostedClient = new CWProjPostedClientFormView(result[0]);
                cwPostedClient.Show();
            }
        }
        private void liURL_LookupButtonClicked(object sender)
        {
            var lookupUrlEditor = sender as LookupEditor;

            if (!isUrlLookupSet)
            {
                lookupUrlEditor.PopupContentTemplate  = (Application.Current).Resources["LookUpUrlDocumentClientPopupContent"] as ControlTemplate;
                lookupUrlEditor.ValueMember           = "RowId";
                lookupUrlEditor.SelectedIndexChanged += LookupUrlEditor_SelectedIndexChanged;
                isUrlLookupSet = true;
                var filter = PropValuePair.GenereteWhereElements("DocumentType", FileextensionsTypes.WWW, CompareOperator.Equal);
                lookupUrlEditor.ItemsSource = api.Query <UserDocsClient>(editrow, new PropValuePair[] { filter }).GetAwaiter().GetResult();
            }
        }
예제 #19
0
        public void InsertFinansJournal(MimeMessage message, int DocumentRef, clsParam objParam)
        {
            var From = message.From.ToString();

            From = ExtractEmails(From);
            var Date    = message.Date.DateTime;
            var Subject = objParam.Tekst;

            if (string.IsNullOrEmpty(Subject))
            {
                Subject = message.Subject;
            }

            var crit = new List <PropValuePair>();
            var pair = PropValuePair.GenereteWhereElements("KeyStr", typeof(String), "Dag");

            crit.Add(pair);
            var task = m_api.Query <GLDailyJournalClient>(null, crit);

            task.Wait();
            var col        = task.Result;
            var rec_Master = col.FirstOrDefault();

            GLDailyJournalLineClient jl = new GLDailyJournalLineClient()
            {
                Date              = Date,
                Text              = Subject,
                DocumentRef       = DocumentRef,
                AccountType       = objParam.Kontotype,
                Account           = objParam.Konto,
                Vat               = objParam.Moms_Konto,
                OffsetAccountType = objParam.Modkontotype,
                OffsetAccount     = objParam.Modkonto,
                OffsetVat         = objParam.Moms_Modkonto,
                Debit             = objParam.Debit,
                Credit            = objParam.Kredit,
            };

            jl.SetMaster(rec_Master);
            var task2 = m_api.Insert(jl);

            task2.Wait();
            var err = task2.Result;

            if (err != ErrorCodes.Succes)
            {
                int xx = 1;
            }
        }
예제 #20
0
        public async Task Query()
        {
            List <PropValuePair> filter = new List <PropValuePair>();
            var wherefilter             = PropValuePair.GenereteWhereElements("Journal", typeof(string), "Dag");

            filter.Add(wherefilter);
            invJournal = (await Configuration.CrudApi.Query <GLDailyJournal>(null, filter)).FirstOrDefault();
            kasse      = await Configuration.CrudApi.Query <Kasseopsaetning>();

            type = await Configuration.CrudApi.Query <Typekonfiguration>();

            GLAccountCache = await Configuration.CrudApi.CompanyEntity.LoadCache(typeof(GLAccount), Configuration.CrudApi);

            //her gør vi en query for at få den til at forstå hvilke tabeller den skal arbejde med på uniconta siden
        }
예제 #21
0
        async void LoadData()
        {
            var inputs = new List <PropValuePair>()
            {
                PropValuePair.GenereteWhereElements("Employee", typeof(string), employee)
            };

            busyIndicator.IsBusy = true;
            var projLst = await api.Query <ProjectTransClient>(inputs) as IEnumerable <ProjectTransClient>;

            var lst = projLst?.Where(x => x.Date.Month == monthNumber).ToArray();

            dgEmpProjectTrans.SetSource(lst);
            busyIndicator.IsBusy         = false;
            dgEmpProjectTrans.Visibility = Visibility.Visible;
        }
        async public override Task InitQuery()
        {
            var debtorOrderLine = this.debtorOrderLine;
            var dctype          = debtorOrderLine.__DCType();

            busyIndicator.IsBusy = true;
            var pair = new List <PropValuePair>()
            {
                PropValuePair.GenereteWhereElements("Item", debtorOrderLine._Item, CompareOperator.Equal),
                PropValuePair.GenereteWhereElements("Qty", 0d, dctype == 2 || debtorOrderLine._Qty > 0d ? CompareOperator.GreaterThan : CompareOperator.LessThan),
                PropValuePair.GenereteWhereElements("Date", DateTime.Now.Date.AddYears(-1), CompareOperator.GreaterThanOrEqual),
            };

            if (dctype == 2 || debtorOrderLine._Qty < 0) // creditnota
            {
                pair.Add(PropValuePair.GenereteWhereElements("MovementType", Convert.ToString(dctype), CompareOperator.Equal));
                string dc;
                if (dctype == 2)
                {
                    dc = ((CreditorOrderLineClient)debtorOrderLine).Order?._DCAccount;
                }
                else
                {
                    dc = ((DebtorOrderLineClient)debtorOrderLine).Order?._DCAccount;
                }
                if (dc != null)
                {
                    pair.Add(PropValuePair.GenereteWhereElements("DCAccount", dc, CompareOperator.Equal));
                }
            }

            var lst = await api.Query <InvTransMarkedLocalGrid>(pair);

            var costRefTrans = this.costRefTrans;

            foreach (var line in lst)
            {
                if (line._MarkingId == costRefTrans)
                {
                    line._marked = true;
                    break;
                }
            }
            dgInvTransGrid.SetSource(lst);
            busyIndicator.IsBusy      = false;
            dgInvTransGrid.Visibility = Visibility.Visible;
        }
예제 #23
0
        public async override Task InitQuery()
        {
            await Filter();

            for (int i = 2; i < 9; i++)
            {
                var source = dgExchangeRate.ItemsSource as IList;
                if (source == null || source.Count == 0)
                {
                    var prop = PropValuePair.GenereteWhereElements("Date", typeof(DateTime), String.Format("{0:d}..", BasePage.GetSystemDefaultDate().Date.AddDays(-i)));
                    await Filter(new List <PropValuePair>() { prop });
                }
                else
                {
                    break;
                }
            }
        }
        private async Task <TrackGenre> FindGenre(string genre)
        {
            // Call Query API
            var filter = new List <PropValuePair>
            {
                PropValuePair.GenereteWhereElements("KeyName", typeof(string), genre)
            };
            var trackGenres = await this.crudAPI.Query <TrackGenre>(filter);

            // Returns result
            if (trackGenres.Length != 0)
            {
                return(trackGenres[0]);
            }
            else
            {
                return(null);
            }
        }
        async private Task <DCPreviousAddressClient> GetPreviousAddressForInvoice(DCInvoiceClient invClient)
        {
            if (invClient == null || crudApi == null)
            {
                return(null);
            }

            DCPreviousAddressClient selectedDateInvoiceAddr = null;
            var propvaluePairList = new System.Collections.Generic.List <PropValuePair>()
            {
                PropValuePair.GenereteWhereElements("DateChange", invClient.Date, CompareOperator.GreaterThan)
            };
            var previousAddresses = await crudApi.Query <DCPreviousAddressClient>(invClient, propvaluePairList);

            if (previousAddresses != null && previousAddresses.Length > 0)
            {
                selectedDateInvoiceAddr = previousAddresses.FirstOrDefault();
            }

            return(selectedDateInvoiceAddr);
        }
예제 #26
0
        void LoadData()
        {
            var addWIP = (bool)chkAddWip.IsChecked;
            var removeWIP = (bool)chkRemoveWIP.IsChecked;
            if (addWIP == removeWIP)
            {
                UnicontaMessageBox.Show(Uniconta.ClientTools.Localization.lookup("BothCannotBeChecked"), Uniconta.ClientTools.Localization.lookup("Error"));
                return;
            }

            var inputs = new List<PropValuePair>(3)
            {
                PropValuePair.GenereteWhereElements("WIPPosted", typeof(bool), addWIP ? "0" : "1"),
                PropValuePair.GenereteWhereElements("Invoiceable", typeof(bool), "1"),
            };
            if (addWIP)
                inputs.Add(PropValuePair.GenereteWhereElements("Invoiced", typeof(bool), "0"));
            else
            {
                string excludeCat = null;
                foreach (var pr in (IEnumerable<Uniconta.DataModel.PrCategory>)prCat.GetNotNullArray)
                {
                    if (pr._CatType == Uniconta.DataModel.CategoryType.Revenue || pr._CatType == Uniconta.DataModel.CategoryType.OnAccountInvoicing)
                    {
                        if (excludeCat == null)
                            excludeCat = "!" + pr._Number;
                        else
                            excludeCat = excludeCat + ";!" + pr._Number;
                    }
                }
                if (excludeCat != null)
                    inputs.Add(PropValuePair.GenereteWhereElements("PrCategory", typeof(string), excludeCat));
            }

            if (ribbonControl.filterValues != null)
                inputs.AddRange(ribbonControl.filterValues);

            var t = FilterData(inputs, ribbonControl.PropSort);
        }
예제 #27
0
        public int ImportEmailBilag()
        {
            MimeMessage message;
            int         antalbilag = 0;
            clsParam    objParam   = null;

            using (var imap_client = new ImapClient())
            {
                imap_client.Connect("outlook.office365.com", 993, true);
                imap_client.AuthenticationMechanisms.Remove("XOAUTH");
                imap_client.Authenticate(clsApp.ImapUser, clsApp.ImapPW);
                var HafsjoldDataBilag      = imap_client.GetFolder("_HafsjoldDataBilag");
                var HafsjoldDataBilagArkiv = imap_client.GetFolder("_HafsjoldDataBilagArkiv");
                HafsjoldDataBilag.Open(FolderAccess.ReadWrite);

                var results = HafsjoldDataBilag.Search(SearchQuery.All);
                antalbilag = results.Count();
                foreach (var result in results)
                {
                    message = HafsjoldDataBilag.GetMessage(result);

                    MemoryStream msMail = new MemoryStream();
                    message.WriteTo(msMail);

                    List <VouchersClient> documents = new List <VouchersClient>();
                    VouchersClient        mail      = new VouchersClient()
                    {
                        Fileextension     = FileextensionsTypes.EML,
                        Text              = "e-Mail",
                        VoucherAttachment = msMail.ToArray(),
                        DocumentDate      = DateTime.Now,
                    };
                    var task1 = m_api.Insert(mail);
                    task1.Wait();
                    var res1 = task1.Result;
                    documents.Add(mail);

                    foreach (var msg_attachment in message.Attachments)
                    {
                        if (msg_attachment is MimePart)
                        {
                            var bSaveAttachment      = true;
                            FileextensionsTypes type = FileextensionsTypes.PDF;
                            switch (msg_attachment.ContentType.MediaSubtype.ToUpper())
                            {
                            case "PDF":
                                type = FileextensionsTypes.PDF;
                                break;

                            case "JPEG":
                                type = FileextensionsTypes.JPEG;
                                break;

                            case "TXT":
                                type = FileextensionsTypes.TXT;
                                break;

                            case "PLAIN":
                                type = FileextensionsTypes.TXT;
                                break;

                            case "MSWORD":
                                type = FileextensionsTypes.DOC;
                                break;

                            case "VND.OPENXMLFORMATS-OFFICEDOCUMENT.SPREADSHEETML.SHEET":
                                type = FileextensionsTypes.XLSX;
                                break;

                            default:
                                type = FileextensionsTypes.UNK;
                                break;
                            }
                            var          part     = (MimePart)msg_attachment;
                            MemoryStream msstream = new MemoryStream();
                            part.Content.DecodeTo(msstream);
                            byte[] arrStream = msstream.ToArray();
                            if (type == FileextensionsTypes.UNK)
                            {
                                if (arrStream[0] == 0x25 && arrStream[1] == 0x50 && arrStream[2] == 0x44 && arrStream[3] == 0x46) // PDF Magic number
                                {
                                    type = FileextensionsTypes.PDF;
                                }
                                else if (Path.GetExtension(part.FileName.ToUpper()) == ".MSG")
                                {
                                    type = FileextensionsTypes.MSG;
                                    using (var msg = new MsgReader.Outlook.Storage.Message(msstream))
                                    {
                                        var      MessageBody = msg.BodyText;
                                        var      msgtext     = Regex.Replace(MessageBody, "<[^>]*>", String.Empty).Replace("&nbsp;", String.Empty).Trim();
                                        string[] splitstring = { "\r\n" };
                                        string[] arrParams   = msgtext.Split(splitstring, StringSplitOptions.RemoveEmptyEntries);
                                        objParam = new clsParam(arrParams);
                                    }
                                    bSaveAttachment = false;
                                }
                            }
                            if (bSaveAttachment)
                            {
                                VouchersClient attm = new VouchersClient()
                                {
                                    Fileextension     = type,
                                    Text              = (msg_attachment as MimePart).FileName,
                                    VoucherAttachment = arrStream,
                                    DocumentDate      = DateTime.Now,
                                };
                                var task3 = m_api.Insert(attm);
                                task3.Wait();
                                var res3 = task3.Result;
                                documents.Add(attm);
                            }
                        }
                        else if (msg_attachment is MessagePart)
                        {
                            var msgpart     = msg_attachment as MessagePart;
                            var MessageBody = msgpart.Message.HtmlBody;
                            if (string.IsNullOrEmpty(MessageBody))
                            {
                                MessageBody = msgpart.Message.TextBody;
                            }
                            var      msgtext     = Regex.Replace(MessageBody, "<[^>]*>", String.Empty).Replace("&nbsp;", String.Empty).Trim();
                            string[] splitstring = { "\r\n" };
                            string[] arrParams   = msgtext.Split(splitstring, StringSplitOptions.RemoveEmptyEntries);
                            objParam = new clsParam(arrParams);
                        }
                    }

                    if (documents.Count > 0)
                    {
                        VouchersClient folder = new VouchersClient()
                        {
                            _Fileextension = FileextensionsTypes.DIR,
                            _Text          = message.Subject,
                            _DocumentDate  = DateTime.Now,
                        };
                        var ref3  = folder.PrimaryKeyId;
                        var task4 = m_api.Insert(folder);
                        task4.Wait();
                        var res4 = task4.Result;
                        var ref1 = folder.PrimaryKeyId;

                        DocumentAPI docapi = new DocumentAPI(m_api);
                        var         task5  = docapi.CreateFolder(folder, documents);
                        task5.Wait();
                        var res5 = task5.Result;
                        var ref2 = folder.PrimaryKeyId;

                        int DocumentRef = ref2;

                        if (ref1 != ref2) //Delete ref1
                        {
                            var crit = new List <PropValuePair>();
                            var pair = PropValuePair.GenereteWhereElements("PrimaryKeyId", typeof(int), ref1.ToString());
                            crit.Add(pair);
                            var task6 = m_api.Query <VouchersClient>(crit);
                            task6.Wait();
                            var col = task6.Result;
                            if (col.Count() == 1)
                            {
                                var rec = col[0];
                                m_api.DeleteNoResponse(rec);
                            }
                        }

                        if (objParam == null)
                        {
                            objParam = new clsParam()
                            {
                                Delsystem    = "Finans",
                                Tekst        = "Ukendt post",
                                Kontotype    = "Finans",
                                Konto        = "5820",
                                Modkontotype = "Finans",
                                Modkonto     = "9900",
                                Kredit       = 0.00
                            };
                        }

                        switch (objParam.Delsystem.ToLower())
                        {
                        case "finans":
                            InsertFinansJournal(message, DocumentRef, objParam);
                            break;

                        case "kreditor":
                            InsertKøbsOrder(message, DocumentRef, objParam);
                            break;

                        default:
                            break;
                        }
                        // move email to arkiv
                        var newId = HafsjoldDataBilag.MoveTo(result, HafsjoldDataBilagArkiv);
                    }
                }

                HafsjoldDataBilag.Close();
                imap_client.Disconnect(true);
            }
            return(antalbilag);// message;
        }
예제 #28
0
        async void calc(DateTime fromDate, DateTime toDate)
        {
            SetBusy();

            var employee = (master as Uniconta.DataModel.Employee)?._Number;

            var propValuePairList = new List <PropValuePair>()
            {
                PropValuePair.GenereteWhereElements("Date", typeof(DateTime), string.Concat(fromDate.ToShortDateString(), "..", toDate.ToShortDateString())),
                PropValuePair.GenereteWhereElements("Deleted", typeof(int), "0")
            };
            var invoiceHeaders = await api.Query <DebtorInvoiceClient>(dgEmployeeCommissionGrid.masterRecords, propValuePairList);

            var commlstLine = new List <EmployeeCommissionClient>(1000);
            var commlstHead = new List <EmployeeCommissionClient>(1000);
            var commAll     = (IEnumerable <EmployeeCommissionClient>)dgEmployeeCommissionGrid.ItemsSource;

            foreach (var rec in commAll)
            {
                if (rec._Disabled)
                {
                    continue;
                }

                if (rec._FromDate != DateTime.MinValue && rec._FromDate > toDate)
                {
                    continue;
                }

                if (rec._ToDate != DateTime.MinValue && rec._ToDate < fromDate)
                {
                    continue;
                }

                if (employee != null && employee != rec._Employee)
                {
                    continue;
                }

                if (rec._PerLine)
                {
                    commlstLine.Add(rec);
                }
                else
                {
                    commlstHead.Add(rec);
                }
            }

            var sort = new EmployeeCommissionClientSort();

            commlstLine.Sort(sort);
            commlstHead.Sort(sort);

            var debtors = api.GetCache(typeof(Uniconta.DataModel.Debtor));

            var calComs = new List <CalCommissionClient>();

            if (commlstLine.Count > 0)
            {
                propValuePairList.RemoveAt(1); // remove Deleted
                propValuePairList.Add(PropValuePair.GenereteWhereElements("MovementType", typeof(int), "1"));

                var trans = await api.Query <InvTransClient>(dgEmployeeCommissionGrid.masterRecords, propValuePairList); //sandt

                if (trans != null)
                {
                    var invItems = api.GetCache(typeof(Uniconta.DataModel.InvItem));

                    // lets sort invoices so we can find employee on invoice header
                    var invSort = new InvoiceSort();
                    DebtorInvoiceClient invKey = null;
                    if (invoiceHeaders != null && invoiceHeaders.Length > 0)
                    {
                        Array.Sort(invoiceHeaders, invSort);
                        invKey = new DebtorInvoiceClient();
                    }

                    foreach (var tran in trans)
                    {
                        var    item      = tran._Item;
                        var    acc       = tran._DCAccount;
                        var    emp       = tran._Employee;
                        string debGroup  = null;
                        string itemGroup = null;

                        if (item != null)
                        {
                            var inv = (InvItem)invItems.Get(item);
                            itemGroup = inv?._Group;
                        }
                        if (acc != null)
                        {
                            var deb = (Debtor)debtors.Get(acc);
                            debGroup = deb?._Group;
                        }
                        if (emp == null && invKey != null)
                        {
                            invKey._InvoiceNumber = tran._InvoiceNumber;
                            invKey._DCAccount     = tran._DCAccount;
                            invKey._Date          = tran._Date;
                            var pos = Array.BinarySearch(invoiceHeaders, invKey, invSort);
                            if (pos >= 0 && pos < invoiceHeaders.Length)
                            {
                                var rec = invoiceHeaders[pos];
                                emp = tran._Employee = rec._Employee;
                            }
                        }

                        foreach (var c in commlstLine)
                        {
                            var cmp = string.Compare(c._Employee, emp);
                            if (cmp > 0)
                            {
                                break;
                            }

                            if (cmp == 0 &&
                                CompareKey(c._Item, item) && CompareKey(c._Account, acc) && CompareKey(c._ItemGroup, itemGroup) &&
                                CompareKey(c._DebGroup, debGroup))
                            {
                                var calculatedCommission = CalculateCommissionInvTran(tran, c);
                                if (calculatedCommission == null || calculatedCommission._Commission == 0)
                                {
                                    continue;
                                }

                                calComs.Add(calculatedCommission);

                                if (!c._KeepLooking)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            if (commlstHead.Count > 0 && invoiceHeaders != null)
            {
                foreach (var it in invoiceHeaders)
                {
                    string debGroup = null;
                    var    emp      = it._Employee;
                    var    acc      = it._DCAccount;
                    if (acc != null)
                    {
                        var deb = (Debtor)debtors.Get(acc);
                        debGroup = deb?._Group;
                    }

                    foreach (var c in commlstHead)
                    {
                        var cmp = string.Compare(c._Employee, emp);
                        if (cmp > 0)
                        {
                            break;
                        }

                        if (cmp == 0 && CompareKey(c._Account, acc) && CompareKey(c._DebGroup, debGroup))
                        {
                            var calculatedCommission = CalculateCommissionDebInvoice(it, c);
                            if (calculatedCommission == null || calculatedCommission._Commission == 0)
                            {
                                continue;
                            }

                            calComs.Add(calculatedCommission);

                            if (!c._KeepLooking)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            ClearBusy();

            if (calComs.Count == 0)
            {
                UnicontaMessageBox.Show(Localization.lookup("NoRecordExport"), Uniconta.ClientTools.Localization.lookup("Message"));
                return;
            }
            var arr = calComs.ToArray();

            Array.Sort(arr, new CalCommissionClientSort());
            AddDockItem(TabControls.CalculatedCommissionPage, new object[] { arr }, Uniconta.ClientTools.Localization.lookup("CalculateCommission"), null, true);
        }
        private async void AddTracks(List <LastFMTrack> tracks)
        {
            var newTracks = new List <Track>();

            foreach (var track in tracks)
            {
                // Check if track already exists
                var filter = new List <PropValuePair>
                {
                    PropValuePair.GenereteWhereElements("Title", typeof(string), track.Name),
                    PropValuePair.GenereteWhereElements("Artist", typeof(string), track.Artist.Name)
                };
                var apiTracks = await this.crudAPI.Query <Track>(filter);

                if (apiTracks.Length == 0)
                {
                    var trackData = track;

                    // Getting more detailed track info
                    var trackInfo = this.lastFMAPI.GetTrackInfo(track);
                    if (trackInfo != null)
                    {
                        trackData = trackInfo;
                    }

                    // Finalizing data
                    string trackGenre = "Unknown";
                    if (trackData.TopTags != null && trackData.TopTags.Tag.Count != 0)
                    {
                        var genre = trackData.TopTags.Tag[0].Name;

                        // Checking if genre exists, and creates it if it dosnt
                        var apiTrackGenre = await this.FindGenre(genre);

                        if (apiTrackGenre == null)
                        {
                            apiTrackGenre = await this.AddGenre(genre);
                        }

                        trackGenre = apiTrackGenre._KeyStr;
                    }

                    int trackLentgh = (trackData.Duration / 1000);

                    // Adding new track to list
                    newTracks.Add(new Track
                    {
                        KeyName     = trackData.Name,
                        Artist      = trackData.Artist.Name,
                        Genre       = trackGenre,
                        Length      = trackLentgh,
                        LicensePaid = false
                    });
                }
            }

            // Call Insert API
            var errorCode = await crudAPI.Insert(newTracks);

            if (errorCode == ErrorCodes.Succes)
            {
                MessageBox.Show($"{newTracks.Count} new tracks was added.");
            }
        }
        async Task LoadGrid()
        {
            fromDate    = txtFromDate.DateTime;
            toDate      = txtToDate.DateTime;
            budgetGroup = cmbBudgetGroup.Text;
            grpWeek     = chkGroupWeek.IsChecked.Value;
            grpPrevYear = chkGroupPrevYear.IsChecked.Value;

            fieldQtyPrev.Visible                   = grpPrevYear;
            fieldCostPrev.Visible                  = grpPrevYear;
            fieldSalesPrev.Visible                 = grpPrevYear;
            fieldQtyActualPrevBudDiff.Visible      = grpPrevYear;
            fieldSalesActualPrevBudgetDiff.Visible = grpPrevYear;
            fieldCostActualPrevBudgetDiff.Visible  = grpPrevYear;

            fieldAnchorBudgetQty.Visible                 = false;
            fieldAnchorBudgetCost.Visible                = false;
            fieldAnchorBudgetSales.Visible               = false;
            fieldQtyNormAnchorBudDiff.Visible            = false;
            fieldQtyActualAnchorBudDiff.Visible          = false;
            fieldQtyActualPrevAnchorBudDiff.Visible      = false;
            fieldQtyAnchorBudBudDiff.Visible             = false;
            fieldSalesActualAnchorBudgetDiff.Visible     = false;
            fieldCostActualAnchorBudgetDiff.Visible      = false;
            fieldSalesActualPrevAnchorBudgetDiff.Visible = false;
            fieldCostActualPrevAnchorBudgetDiff.Visible  = false;
            fieldSalesAnchorBudBudDiff.Visible           = false;
            fieldCostAnchorBudBudDiff.Visible            = false;

            if (string.IsNullOrEmpty(budgetGroup))
            {
                var msgText = FieldCannotBeEmpty(Uniconta.ClientTools.Localization.lookup("BudgetGroup"));
                UnicontaMessageBox.Show(msgText, Uniconta.ClientTools.Localization.lookup("Warning"), MessageBoxButton.OK);
                return;
            }

            if (fromDate == DateTime.MinValue)
            {
                var msgText = FieldCannotBeEmpty(Uniconta.ClientTools.Localization.lookup("FromDate"));
                UnicontaMessageBox.Show(msgText, Uniconta.ClientTools.Localization.lookup("Warning"), MessageBoxButton.OK);
                return;
            }

            if (toDate == DateTime.MinValue)
            {
                var msgText = FieldCannotBeEmpty(Uniconta.ClientTools.Localization.lookup("ToDate"));
                UnicontaMessageBox.Show(msgText, Uniconta.ClientTools.Localization.lookup("Warning"), MessageBoxButton.OK);
                return;
            }

            busyIndicator.IsBusy = true;

            List <PropValuePair> filter = new List <PropValuePair>();

            if (fromDate != DateTime.MinValue)
            {
                var propValuePairFolder = PropValuePair.GenereteParameter("FromDate", typeof(string), Convert.ToString(fromDate.Ticks));
                filter.Add(propValuePairFolder);
            }
            if (toDate != DateTime.MinValue)
            {
                var propValuePairFolder = PropValuePair.GenereteParameter("ToDate", typeof(string), Convert.ToString(toDate.Ticks));
                filter.Add(propValuePairFolder);
            }
            if (budgetGroup != null)
            {
                var propValuePairFolder = PropValuePair.GenereteParameter("BudgetGroup", typeof(string), budgetGroup);
                filter.Add(propValuePairFolder);
            }

            var api       = this.api;
            var CompanyId = api.CompanyId;

            var trans = await api.Query(new ProjectTransPivotClient(), new [] { master }, filter);

            if (trans == null)
            {
                return;
            }

            var len  = trans.Length;
            var sort = new ProjectTransBudgetPivotSort();

            Array.Sort(trans, sort);

            List <ProjectTransPivotClient> extras = null;

            if (showBudget)
            {
                var budget = await api.Query(new ProjectBudgetPivotClient(), new List <UnicontaBaseEntity>() { master }, filter);

                var key = new ProjectTransPivotClient();
                foreach (var bc in budget)
                {
                    key._Project         = bc._Project;
                    key._Date            = bc._Date;
                    key._PrCategory      = bc._PrCategory;
                    key._PayrollCategory = bc._PayrollCategory;
                    key._Employee        = bc.Employee;
                    var idx = Array.BinarySearch(trans, key, sort);
                    if (idx >= 0 && idx < len)
                    {
                        var t = trans[idx];
                        if (bc._AnchorBudget)
                        {
                            t._AnchorBudgetSales += bc._Sales;
                            t._AnchorBudgetCost  += bc._Cost;
                            t._AnchorBudgetQty   += bc._Qty;
                        }
                        else
                        {
                            t._BudgetSales += bc._Sales;
                            t._BudgetCost  += bc._Cost;
                            t._BudgetQty   += bc._Qty;
                        }
                    }
                    else
                    {
                        var prTrans = new ProjectTransPivotClient()
                        {
                            _CompanyId       = CompanyId,
                            _PrCategory      = bc._PrCategory,
                            _Project         = bc._Project,
                            _Date            = bc._Date,
                            _Employee        = bc._Employee,
                            _PayrollCategory = bc._PayrollCategory,
                        };

                        if (bc._AnchorBudget)
                        {
                            prTrans._AnchorBudgetSales = bc._Sales;
                            prTrans._AnchorBudgetCost  = bc._Cost;
                            prTrans._AnchorBudgetQty   = bc._Qty;
                        }
                        else
                        {
                            prTrans._BudgetSales = bc._Sales;
                            prTrans._BudgetCost  = bc._Cost;
                            prTrans._BudgetQty   = bc._Qty;
                        }

                        if (extras == null)
                        {
                            extras = new List <ProjectTransPivotClient>();
                        }
                        extras.Add(prTrans);
                    }
                }
            }

            if (grpPrevYear)
            {
                foreach (var p in filter)
                {
                    if (p.Prop == "FromDate")
                    {
                        p.Arg = Convert.ToString(fromDate.AddYears(-1).Ticks);
                    }
                    if (p.Prop == "ToDate")
                    {
                        p.Arg = Convert.ToString(toDate.AddYears(-1).Ticks);
                    }
                }

                var transTaskPrev = api.Query(new ProjectTransPivotClient(), new [] { master }, filter);
                var transPrev     = await transTaskPrev;

                foreach (var y in transPrev)
                {
                    var prTrans = new ProjectTransPivotClient()
                    {
                        _CompanyId       = CompanyId,
                        _SalesPrev       = y._Sales,
                        _CostPrev        = y._Cost,
                        _QtyPrev         = y._Qty,
                        _PrCategory      = y._PrCategory,
                        _Project         = y._Project,
                        _Date            = y._Date,
                        _Employee        = y._Employee,
                        _PayrollCategory = y._PayrollCategory
                    };

                    if (extras == null)
                    {
                        extras = new List <ProjectTransPivotClient>();
                    }
                    extras.Add(prTrans);
                }
            }

            if (extras != null)
            {
                Array.Resize(ref trans, len + extras.Count);
                foreach (var sum in extras)
                {
                    trans[len++] = sum;
                }
                Array.Sort(trans, sort);
                extras = null;
            }

            int start = 0;

            while (start < len)
            {
                int    end;
                string ProjectNumber;
                if (master == null)
                {
                    ProjectNumber = trans[start]._Project;
                    for (end = start; (end < len && trans[end]._Project == ProjectNumber); end++)
                    {
                        ;
                    }
                }
                else
                {
                    ProjectNumber = ((Uniconta.DataModel.Project)master)._Number;
                    end           = len;
                }

                start = end;
            }

            #region Norm Calendar

            CalenderNormLst[] normLst = null;

            var pairCalendarLine = new PropValuePair[]
            {
                PropValuePair.GenereteWhereElements(nameof(TMEmpCalendarLineClient.Date), typeof(DateTime), String.Format("{0:d}..{1:d}", fromDate, toDate))
            };

            var tmEmpCalenderLineLst = await api.Query <TMEmpCalendarLineClient>(pairCalendarLine);

            if (tmEmpCalenderLineLst.Length > 0)
            {
                if (grpWeek)
                {
                    var grpCalendarLst = tmEmpCalenderLineLst.GroupBy(x => new { x.Calendar, PeriodFirstDate = x.WeekMonday }).Select(x => new { x.Key, Hours = x.Sum(y => y.Hours) });
                    foreach (var rec in grpCalendarLst)
                    {
                        var normTrans = new CalenderNormLst()
                        {
                            CalendarId = rec.Key.Calendar,
                            Date       = rec.Key.PeriodFirstDate,
                            NormQty    = rec.Hours
                        };

                        if (normLst == null)
                        {
                            normLst = new CalenderNormLst[] { normTrans }
                        }
                        ;
                        else
                        {
                            Array.Resize(ref normLst, normLst.Length + 1);
                            normLst[normLst.Length - 1] = normTrans;
                        }
                    }
                }
                else
                {
                    var grpCalendarLst = tmEmpCalenderLineLst.GroupBy(x => new { x.Calendar, x.FirstDayOfMonth }).Select(x => new { Key = x.Key, Hours = x.Sum(y => y.Hours) }).ToList();

                    foreach (var rec in grpCalendarLst)
                    {
                        var normTrans = new CalenderNormLst()
                        {
                            CalendarId = rec.Key.Calendar,
                            Date       = rec.Key.FirstDayOfMonth,
                            NormQty    = rec.Hours
                        };

                        if (normLst == null)
                        {
                            normLst = new CalenderNormLst[] { normTrans }
                        }
                        ;
                        else
                        {
                            Array.Resize(ref normLst, normLst.Length + 1);
                            normLst[normLst.Length - 1] = normTrans;
                        }
                    }
                }

                var normCalSort = new SortNormCalendar();
                Array.Sort(normLst, normCalSort);

                var lstCalendarSetup = await api.Query <TMEmpCalendarSetupClient>();

                var calSetupSort = new SortCalendarSetup();
                Array.Sort(lstCalendarSetup, calSetupSort);

                var calenders      = new List <TMEmpCalendarSetupClient>(10);
                var searchCalSetup = new TMEmpCalendarSetupClient();

                var empNormLst = new List <ProjectTransPivotClient>();
                var searchNorm = new CalenderNormLst();

                foreach (var empl in employeeCache)
                {
                    var curEmployee = empl._Number;

                    calenders.Clear();

                    searchCalSetup.Employee = curEmployee;
                    var posCalSetup = Array.BinarySearch(lstCalendarSetup, searchCalSetup, calSetupSort);
                    if (posCalSetup < 0)
                    {
                        posCalSetup = ~posCalSetup;
                    }
                    while (posCalSetup < lstCalendarSetup.Length)
                    {
                        var s = lstCalendarSetup[posCalSetup++];
                        if (s.Employee != curEmployee)
                        {
                            break;
                        }

                        calenders.Add(s);
                    }

                    if (calenders.Count == 0)
                    {
                        continue;
                    }

                    if (grpWeek)
                    {
                        foreach (var rec in calenders.OrderBy(s => s.ValidFrom))
                        {
                            var newStartDate = rec._ValidFrom != DateTime.MinValue && rec._ValidFrom > fromDate ? rec._ValidFrom : fromDate;
                            var empStartDate = empl._Hired == DateTime.MinValue ? newStartDate : empl._Hired > newStartDate ? empl._Hired : newStartDate;

                            var newEndDate = rec._ValidTo != DateTime.MinValue && rec._ValidTo < toDate ? rec._ValidTo : toDate;
                            var empEndDate = empl._Terminated == DateTime.MinValue ? newEndDate : empl._Terminated < newEndDate ? empl._Terminated : newEndDate;

                            var empFirstDayOfWk = FirstDayOfWeek(empStartDate);

                            searchNorm.CalendarId = rec._Calendar;
                            searchNorm.Date       = empFirstDayOfWk;

                            var pos = Array.BinarySearch(normLst, searchNorm, normCalSort);
                            if (pos < 0)
                            {
                                pos = ~pos;
                            }
                            while (pos < normLst.Length)
                            {
                                var s = normLst[pos++];
                                if (s.CalendarId != rec._Calendar || s.Date > empEndDate)
                                {
                                    break;
                                }

                                if (s.Date >= empStartDate && s.Date <= empEndDate)
                                {
                                    var newTrans = new ProjectTransPivotClient()
                                    {
                                        _CompanyId = CompanyId,
                                        _Employee  = curEmployee,
                                        _Date      = s.Date,
                                        _NormQty   = s.NormQty
                                    };

                                    empNormLst.Add(newTrans);
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (var rec in calenders.OrderBy(s => s.ValidFrom))
                        {
                            var newStartDate = rec._ValidFrom != DateTime.MinValue && rec._ValidFrom > fromDate ? rec._ValidFrom : fromDate;
                            var empStartDate = empl._Hired == DateTime.MinValue ? newStartDate : empl._Hired > newStartDate ? empl._Hired : newStartDate;

                            var newEndDate = rec._ValidTo != DateTime.MinValue && rec._ValidTo < toDate ? rec._ValidTo : toDate;
                            var empEndDate = empl._Terminated == DateTime.MinValue ? newEndDate : empl._Terminated < newEndDate ? empl._Terminated : newEndDate;

                            var empFirstDayOfMonth = FirstDayOfMonth(empStartDate);
                            var empLastDayOfMonth  = LastDayOfMonth(empEndDate);

                            int empFirstMth = 0, empLastMth = 0;

                            if (empFirstDayOfMonth != empStartDate)
                            {
                                empFirstMth = empStartDate.Month;
                            }

                            if (empLastDayOfMonth != empEndDate)
                            {
                                empLastMth = empEndDate.Month;
                            }

                            searchNorm.CalendarId = rec._Calendar;
                            searchNorm.Date       = empFirstDayOfMonth;

                            var pos = Array.BinarySearch(normLst, searchNorm, normCalSort);
                            if (pos < 0)
                            {
                                pos = ~pos;
                            }
                            while (pos < normLst.Length)
                            {
                                var s = normLst[pos++];
                                if (s.CalendarId != rec._Calendar || s.Date > empEndDate)
                                {
                                    break;
                                }


                                if (empFirstMth != 0 && s.Date.Month == empFirstMth)
                                {
                                    var firstDayOfMonth = FirstDayOfMonth(empStartDate);
                                    var lastDayOfMonth  = firstDayOfMonth.AddMonths(1).AddDays(-1);

                                    var hours = tmEmpCalenderLineLst.Where(x => x._Calendar == s.CalendarId && x.Date >= empStartDate && x.Date <= lastDayOfMonth).Sum(y => y._Hours);

                                    var newTrans = new ProjectTransPivotClient()
                                    {
                                        _CompanyId = CompanyId,
                                        _Employee  = curEmployee,
                                        _Date      = firstDayOfMonth,
                                        _NormQty   = hours
                                    };

                                    empNormLst.Add(newTrans);
                                }
                                else if (empLastMth != 0 && s.Date.Month == empLastMth)
                                {
                                    var firstDayOfMonth = FirstDayOfMonth(empEndDate);
                                    var lastDayOfMonth  = firstDayOfMonth.AddMonths(1).AddDays(-1);

                                    var hours = tmEmpCalenderLineLst.Where(x => x._Calendar == s.CalendarId && x.Date >= firstDayOfMonth && x.Date <= empEndDate).Sum(y => y._Hours);

                                    var newTrans = new ProjectTransPivotClient()
                                    {
                                        _CompanyId = CompanyId,
                                        _Employee  = curEmployee,
                                        _Date      = firstDayOfMonth,
                                        _NormQty   = hours
                                    };

                                    empNormLst.Add(newTrans);
                                }
                                else if (s.Date >= empStartDate && s.Date <= empEndDate)
                                {
                                    var newTrans = new ProjectTransPivotClient()
                                    {
                                        _CompanyId = CompanyId,
                                        _Employee  = curEmployee,
                                        _Date      = s.Date,
                                        _NormQty   = s.NormQty
                                    };

                                    empNormLst.Add(newTrans);
                                }
                            }
                        }
                    }
                }
                if (empNormLst.Count > 0)
                {
                    Array.Resize(ref trans, len + empNormLst.Count);
                    foreach (var norm in empNormLst)
                    {
                        trans[len++] = norm;
                    }

                    Array.Sort(trans, sort);
                }
            }
            #endregion Norm Calendar

            pivotDgProjectPlanning.DataSource = trans as IList;
            if (!isPivotIsVisible)
            {
                pivotDgProjectPlanning.EndUpdate();
                pivotDgProjectPlanning.Visibility = Visibility.Visible;
                isPivotIsVisible = true;
            }
            pivotDgProjectPlanning.RefreshData();
            busyIndicator.IsBusy = false;
        }