Ejemplo n.º 1
0
        public ErrorCodes Execute(UnicontaBaseEntity master, UnicontaBaseEntity currentRow, IEnumerable <UnicontaBaseEntity> source, string command, string args)
        {
            // Plugin must be installed on Control: GL_DailyJournal
            var journal = currentRow as GLDailyJournalClient;

            Crud.LoadCache(typeof(DebtorClient)).Wait();

            // TODO: Change Path
            using (TextFieldParser parser = new TextFieldParser(@"C:\Users\Alexander Banks\api-training\JournalLoader\JournalLoader\Data.csv"))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(";");
                // Read the first line to get rid of header
                parser.ReadFields();

                var loc = Localization.GetLocalization(Language.da);

                var newJournalLines = new List <GLDailyJournalLineClient>();
                while (!parser.EndOfData)
                {
                    //Process row
                    string[] fields = parser.ReadFields();
                    // TODO: Process fields
                    var date        = DateTime.ParseExact(fields[0], "dd-MM-yyyy", CultureInfo.InvariantCulture);
                    var account     = fields[1];
                    var accountType = loc.Lookup(fields[2]);
                    var amount      = double.Parse(fields[3], CultureInfo.GetCultureInfo("da"));

                    var journalLine = new GLDailyJournalLineClient
                    {
                        // TODO: Insert properties from fields[]
                        Date        = date,
                        Account     = account,
                        _Account    = account,
                        AccountType = accountType,
                        Amount      = amount,
                    };
                    journal.Account = account;
                    journalLine.SetMaster(journal);
                    journal.Account = account;
                    newJournalLines.Add(journalLine);
                }

                // Done parsing file. Insert new journal lines.
                var result = Crud.Insert(newJournalLines).Result;
                if (result != ErrorCodes.Succes)
                {
                    // TODO: Do Error Handling.
                    return(result);
                }

                // Post Journals
                var postingAPI = new PostingAPI(Crud);
                var res        = postingAPI.PostDailyJournal(journal, DateTime.Now, "My Fine Comment", newJournalLines.Count, lines: newJournalLines).Result;
            }
            return(ErrorCodes.Succes);
        }
        void OpenImportDataPage(GLDailyJournalClient selectedItem)
        {
            var    dailyJournals = new GLDailyJournalLineClient();
            string header        = selectedItem.Journal;

            UnicontaBaseEntity[] baseEntityArray = new UnicontaBaseEntity[2] {
                dailyJournals, selectedItem
            };
            object[] param = new object[2];
            param[0] = baseEntityArray;
            param[1] = header;
            AddDockItem(TabControls.ImportPage, param, string.Format("{0}: {1}", Uniconta.ClientTools.Localization.lookup("Import"), header));
        }
Ejemplo n.º 3
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;
            }
        }
Ejemplo n.º 4
0
        private GLDailyJournalLineClient GetJournalLine(List <string> line, int year, string account, string contraAccount, string VAT)
        {
            var date = DateTime.ParseExact(line[9], "ddMM", null);

            date = new DateTime(year, date.Month, date.Day);
            int accInt    = (int)NumberConvert.ToInt(account);
            int offaccInt = (int)NumberConvert.ToInt(contraAccount);

            var journalLine = new GLDailyJournalLineClient
            {
                _Date          = date,
                _Account       = account,
                _OffsetAccount = contraAccount,
                _Vat           = VAT,
                // 0-9999=Ledger, 10000-69999=Customer, 70000-99999=Vendor
                _AccountType       = (accInt < DebtorLower ? (byte)GLJournalAccountType.Finans : (accInt < CreditorLower ? (byte)GLJournalAccountType.Debtor : (byte)GLJournalAccountType.Creditor)),
                _OffsetAccountType = (offaccInt < DebtorLower ? (byte)GLJournalAccountType.Finans : (offaccInt < CreditorLower ? (byte)GLJournalAccountType.Debtor : (byte)GLJournalAccountType.Creditor)),
                _Text    = line[13],
                _Dim1    = line[36],
                _Dim2    = line[37],
                _Invoice = line[10]
            };

            var amount    = NumberConvert.ToDoubleNoThousandSeperator(line[0]);
            var amountLin = line[1][0];

            if (amountLin == 'S')
            {
                journalLine._Debit = amount;
            }
            else if (amountLin == 'H')
            {
                journalLine._Credit = amount;
            }

            journalLine._OffsetAccount = contraAccount;

            if (journalLine._AccountType == (byte)GLJournalAccountType.Finans && string.IsNullOrEmpty(journalLine._Vat))
            {
                var gla = GLAccCache.Get(journalLine._Account) as GLAccount;
                if (gla != null && gla._DATEVAuto)
                {
                    journalLine._Vat = gla._Vat;
                }
            }

            return(journalLine);
        }
        public SettleOpenTransactionPage(UnicontaBaseEntity baseEntity, byte openTransType, UnicontaBaseEntity selectedjournalLine, bool offSet, IEnumerable <string> markedList) : base(null)
        {
            InitializeComponent();
            this.DataContext         = this;
            this.OffSet              = offSet;
            this.OpenTransactionType = openTransType;
            InitializePage(baseEntity, openTransType);
            if (selectedjournalLine is GLDailyJournalLineClient)
            {
                SelectedJournalLine = selectedjournalLine as GLDailyJournalLineClient;
            }
            else if (selectedjournalLine is BankStatementLineClient)
            {
                SelectedBankStatemenLine = selectedjournalLine as BankStatementLineClient;
            }

            ((DevExpress.Xpf.Grid.TableView)dgOpenTransactionGrid.View).RowStyle = Application.Current.Resources["DisableStyleRow"] as Style;
            InitGridView(markedList);
        }
Ejemplo n.º 6
0
        private void GenerateJournalLines()
        {
            DirectDebitToJournal cwwin = new DirectDebitToJournal(api);

            cwwin.Closed += async delegate
            {
                if (cwwin.DialogResult == true && !string.IsNullOrEmpty(cwwin.Journal))
                {
                    ExpandCollapseAllGroups();

                    busyIndicator.IsBusy = true;
                    Uniconta.API.GeneralLedger.PostingAPI posApi = new Uniconta.API.GeneralLedger.PostingAPI(api);
                    long LineNumber = await posApi.MaxLineNumber(cwwin.Journal);

                    NumberSerieAPI numberserieApi    = new NumberSerieAPI(posApi);
                    int            nextVoucherNumber = 0;

                    var DJclient       = (Uniconta.DataModel.GLDailyJournal)JournalCache.Get(cwwin.Journal);
                    var listLineClient = new List <Uniconta.DataModel.GLDailyJournalLine>();

                    if (!DJclient._GenerateVoucher && !DJclient._ManualAllocation)
                    {
                        nextVoucherNumber = (int)await numberserieApi.ViewNextNumber(DJclient._NumberSerie);
                    }

                    List <DebtorTransDirectDebit> paymentListTransfer = null;
                    var dictPaymTransfer = new Dictionary <int, DebtorTransDirectDebit>();
                    DebtorTransDirectDebit mergePaymentRefId;

                    var netsBS = false;
                    int index  = 0;
                    foreach (var rec in (IEnumerable <DebtorTransDirectDebit>)dgDebtorTranOpenGrid.ItemsSource)
                    {
                        int rowHandle = dgDebtorTranOpenGrid.GetRowHandleByListIndex(index);
                        index++;
                        if (!dgDebtorTranOpenGrid.IsRowVisible(rowHandle) || rec._PaymentStatus == PaymentStatusLevel.OnHold) //TODO: Pt. tillades alle med undtagelse af OnHold
                        {
                            continue;
                        }

                        if (rec.PaymentFormat != null)
                        {
                            var paymFormatClient = (DebtorPaymentFormat)PaymentFormatCache.Get(rec.PaymentFormat);
                            netsBS = rec.PaymentFormat == paymFormatClient._Format;
                        }

                        var paymRefId = rec._PaymentRefId != 0 ? rec._PaymentRefId : -rec.PrimaryKeyId;

                        if (dictPaymTransfer.TryGetValue(paymRefId, out mergePaymentRefId))
                        {
                            mergePaymentRefId.MergedAmount += netsBS ? rec.Amount : rec.PaymentAmount;

                            mergePaymentRefId.settleTypeRowId = true;
                            mergePaymentRefId.rowNumbers.Append(';').Append(rec.PrimaryKeyId);

                            mergePaymentRefId.hasBeenMerged = true;
                        }
                        else
                        {
                            mergePaymentRefId = new DebtorTransDirectDebit();
                            StreamingManager.Copy(rec, mergePaymentRefId);
                            mergePaymentRefId._PaymentRefId = paymRefId;
                            mergePaymentRefId.MergedAmount  = netsBS ? rec.Amount : rec.PaymentAmount;

                            mergePaymentRefId.rowNumbers = new StringBuilder();
                            mergePaymentRefId.rowNumbers.Append(rec.PrimaryKeyId);
                            mergePaymentRefId.settleTypeRowId = true;

                            dictPaymTransfer.Add(paymRefId, mergePaymentRefId);
                        }
                        paymentListTransfer = dictPaymTransfer.Values.ToList();
                    }

                    foreach (var cTOpenClient in paymentListTransfer)
                    {
                        var lineclient = new GLDailyJournalLineClient();
                        lineclient.SetMaster(DJclient);
                        lineclient._DCPostType    = DCPostType.Payment;
                        lineclient._LineNumber    = ++LineNumber;
                        lineclient._Date          = cTOpenClient._PaymentDate != DateTime.MinValue ? cTOpenClient._PaymentDate : cTOpenClient._DueDate;
                        lineclient._TransType     = cwwin.TransType;
                        lineclient._AccountType   = (byte)GLJournalAccountType.Debtor;
                        lineclient._Account       = cTOpenClient.Account;
                        lineclient._OffsetAccount = cwwin.BankAccount;
                        lineclient._Invoice       = cTOpenClient.hasBeenMerged ? 0 : cTOpenClient.Invoice;

                        if (cTOpenClient.settleTypeRowId)
                        {
                            lineclient._SettleValue = SettleValueType.RowId;
                            lineclient._Settlements = cTOpenClient.rowNumbers.ToString();
                        }
                        else
                        {
                            lineclient._Settlements = null;
                        }

                        lineclient._DocumentRef = cTOpenClient.DocumentRef;
                        lineclient.Amount       = netsBS ? -cTOpenClient.Amount : -cTOpenClient.PaymentAmount;

                        if (nextVoucherNumber != 0)
                        {
                            lineclient._Voucher = nextVoucherNumber;
                            nextVoucherNumber++;
                        }

                        listLineClient.Add(lineclient);
                    }
                    if (listLineClient.Count > 0)
                    {
                        if (nextVoucherNumber != 0)
                        {
                            numberserieApi.SetNumber(DJclient._NumberSerie, nextVoucherNumber - 1);
                        }

                        ErrorCodes errorCode = await api.Insert(listLineClient);

                        busyIndicator.IsBusy = false;
                        if (errorCode != ErrorCodes.Succes)
                        {
                            UtilDisplay.ShowErrorCode(errorCode);
                        }
                        else
                        {
                            var text = string.Concat(Uniconta.ClientTools.Localization.lookup("TransferedToJournal"), ": ", DJclient._Journal,
                                                     Environment.NewLine, string.Format(Uniconta.ClientTools.Localization.lookup("GoTo"), Uniconta.ClientTools.Localization.lookup("Journallines")), " ?");
                            var select = UnicontaMessageBox.Show(text, Uniconta.ClientTools.Localization.lookup("Information"), MessageBoxButton.OKCancel);
                            if (select == MessageBoxResult.OK)
                            {
                                AddDockItem(TabControls.GL_DailyJournalLine, DJclient, null, null, true);
                            }
                        }
                    }
                    else
                    {
                        busyIndicator.IsBusy = false;
                        UtilDisplay.ShowErrorCode(ErrorCodes.NoLinesToUpdate);
                    }
                }
            };
            cwwin.Show();
        }
Ejemplo n.º 7
0
        async public void InsertGLDailyJournalLinesYearEnd()
        {
            var api  = UCInitializer.GetBaseAPI;
            var col3 = await api.Query <NumberSerieClient>();

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

            crit.Add(pair);
            var col = await api.Query <GLDailyJournalClient>(null, crit);

            var rec_Master = col.FirstOrDefault();


            var qryPosteringer = from p in Program.karPosteringer
                                 where p.Bilag == 0 && (p.Tekst.StartsWith("ÅP:") || p.Tekst.StartsWith("EP:"))
                                 orderby p.Konto, p.Nr
            select p;

            int antal = qryPosteringer.Count();

            DateTime Dato_last      = DateTime.Today;
            int      Konto_last     = 0;
            decimal  Nettobeløb_sum = 0;

            foreach (var p in qryPosteringer)
            {
                if (p.Konto != Konto_last)
                {
                    if (Konto_last != 0)
                    {
                        GLDailyJournalLineClient jl = new GLDailyJournalLineClient()
                        {
                            Date    = Dato_last,
                            Voucher = 9999,
                            Text    = "Primo SummaSummarum",
                            Account = KarNyKontoplan.NytKontonr(Konto_last)
                        };

                        if (Nettobeløb_sum > 0)
                        {
                            jl.Debit = (double)Nettobeløb_sum;
                        }
                        else
                        {
                            jl.Credit = -(double)Nettobeløb_sum;
                        }

                        jl.SetMaster(rec_Master);
                        var err = await api.Insert(jl);
                    }
                    Nettobeløb_sum = 0;
                }
                Dato_last       = p.Dato;
                Konto_last      = p.Konto;
                Nettobeløb_sum += p.Nettobeløb;
            }

            if (antal > 0)
            {
                GLDailyJournalLineClient jl = new GLDailyJournalLineClient()
                {
                    Date    = Dato_last,
                    Voucher = 9999,
                    Text    = "Primo SummaSummarum",
                    Account = KarNyKontoplan.NytKontonr(Konto_last)
                };

                if (Nettobeløb_sum > 0)
                {
                    jl.Debit = (double)Nettobeløb_sum;
                }
                else
                {
                    jl.Credit = -(double)Nettobeløb_sum;
                }

                jl.SetMaster(rec_Master);
                var err = await api.Insert(jl);
            }
        }
Ejemplo n.º 8
0
        async public void InsertGLDailyJournalLines()
        {
            var api = UCInitializer.GetBaseAPI;
            //var col3 = await api.Query<NumberSerieClient>();

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

            crit.Add(pair);
            var col = await api.Query <GLDailyJournalClient>(null, crit);

            var rec_Master = col.FirstOrDefault();

            var qryKladder = from k in Program.karKladder
                             where k.Bilag > 183 // <-----------------------
                             orderby k.Bilag, k.Id
            select k;
            int antal = qryKladder.Count();

            foreach (var k in qryKladder)
            {
                //if (k.Bilag > 3)
                //    break;
                int refbilag = await InsertVouchersClients(k);

                GLDailyJournalLineClient jl = new GLDailyJournalLineClient()
                {
                    Date        = (DateTime)k.Dato,
                    Voucher     = (k.Bilag != null) ? (int)k.Bilag : 0,
                    Text        = k.Tekst,
                    DocumentRef = refbilag,
                };


                if (!String.IsNullOrWhiteSpace(k.Afstemningskonto)) //Afstemningskonto er udfyldt
                {
                    if (k.Belob > 0)
                    {
                        jl.Debit = (double)k.Belob;
                    }
                    else
                    {
                        jl.Credit = -(double)k.Belob;
                    }
                }
                else //Afstemningskonto er ikke udfyldt
                {
                    if (k.Belob > 0)
                    {
                        jl.Credit = (double)k.Belob;
                    }
                    else
                    {
                        jl.Debit = -(double)k.Belob;
                    }
                }

                if (KarNyKontoplan.NytKontonr(k.Afstemningskonto) != string.Empty)
                {
                    jl.Account = KarNyKontoplan.NytKontonr(k.Afstemningskonto);

                    if (KarNyKontoplan.NytKontonr(k.Konto) != string.Empty)
                    {
                        jl.OffsetAccount = KarNyKontoplan.NytKontonr(k.Konto);
                    }
                }
                else
                {
                    if (KarNyKontoplan.NytKontonr(k.Konto) != string.Empty)
                    {
                        jl.Account = KarNyKontoplan.NytKontonr(k.Konto);
                    }
                }
                jl.Dimension1 = KarDimensionSag.getDimension1(k.Sag);
                jl.Dimension2 = KarDimensionSag.getDimension2(k.Sag);
                jl.SetMaster(rec_Master);
                var err = await api.Insert(jl);
            }
        }
Ejemplo n.º 9
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;
            }

            string wAccount = null;

            if (!string.IsNullOrEmpty(objParam.Konto))
            {
                try
                {
                    wAccount = (from c in this.m_GLAccounts where c.Account == objParam.Konto select c.Account).First();
                }
                catch (Exception)
                {
                    wAccount = "9900"; //Fejlkonto
                }
            }

            string wOffsetAccount = null;

            if (!string.IsNullOrEmpty(objParam.Modkonto))
            {
                try
                {
                    wOffsetAccount = (from c in this.m_GLAccounts where c.Account == objParam.Modkonto select c.Account).First();
                }
                catch (Exception)
                {
                    wOffsetAccount = "9900"; //Fejlkonto
                }
            }

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

            crit.Add(pair);
            var task = m_api.Query <GLDailyJournalClient>(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           = wAccount,
                OffsetAccountType = objParam.Modkontotype,
                OffsetAccount     = wOffsetAccount,
                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;
            }
        }
Ejemplo n.º 10
0
        void CopyToJOurnal()
        {
            var gltranslst = dgAccountsTransGrid.GetVisibleRows() as IEnumerable <GLTransClient>;
            var cwObj      = new CWCopyVoucherToJrnl(api);

#if !SILVERLIGHT
            cwObj.DialogTableId = 2000000082;
#endif
            cwObj.Closed += async delegate
            {
                if (cwObj.DialogResult == true)
                {
                    var Accounts = api.GetCache(typeof(GLAccount));

                    GLDailyJournalLineClient gljournaLine = null;
                    double factor             = CWCopyVoucherToJrnl.InvertSign ? -1d : 1d;
                    double vatAmount          = 0;
                    var    glDailyJrnlLineLst = new List <GLDailyJournalLineClient>(gltranslst.Count());
                    foreach (var trans in gltranslst)
                    {
                        if (gljournaLine != null && gljournaLine._AccountType == 0 && vatAmount != 0 && vatAmount == trans._Amount && gljournaLine._Vat == trans._Vat)
                        {
                            // We join vat with previous line
                            gljournaLine.Amount    += (factor * vatAmount);
                            gljournaLine.AmountCur += factor * trans._AmountCur;
                            gljournaLine            = null;
                            continue;
                        }
                        vatAmount = trans._AmountVat;

                        gljournaLine = new GLDailyJournalLineClient();

                        gljournaLine.Date      = CWCopyVoucherToJrnl.Date == DateTime.MinValue ? trans.Date : CWCopyVoucherToJrnl.Date;
                        gljournaLine.Text      = string.IsNullOrEmpty(CWCopyVoucherToJrnl.Comment) ? trans.Text : CWCopyVoucherToJrnl.Comment;
                        gljournaLine.TransType = string.IsNullOrEmpty(CWCopyVoucherToJrnl.TransType) ? trans.TransType : CWCopyVoucherToJrnl.TransType;

                        gljournaLine._DocumentDate = trans._DocumentDate;
                        gljournaLine._Account      = trans._Account;
                        gljournaLine._Vat          = trans._Vat;
                        gljournaLine._VatOperation = trans._VatOperation;
                        gljournaLine._Voucher      = trans._Voucher;
                        gljournaLine.Amount        = factor * trans._Amount;
                        gljournaLine._Currency     = trans._Currency;
                        gljournaLine.AmountCur     = factor * trans._AmountCur;
                        gljournaLine._Project      = trans._Project;
                        gljournaLine._DocumentRef  = trans._DocumentRef;
                        gljournaLine._Qty          = trans._Qty;
                        gljournaLine._Dim1         = trans._Dimension1;
                        gljournaLine._Dim2         = trans._Dimension2;
                        gljournaLine._Dim3         = trans._Dimension3;
                        gljournaLine._Dim4         = trans._Dimension4;
                        gljournaLine._Dim5         = trans._Dimension5;

                        if (trans._DCType > 0)
                        {
                            var acc = (GLAccount)Accounts.Get(trans._Account);
                            if (acc != null)
                            {
                                if ((trans._DCType == GLTransRefType.Debtor && acc.AccountTypeEnum == GLAccountTypes.Debtor) ||
                                    (trans._DCType == GLTransRefType.Creditor && acc.AccountTypeEnum == GLAccountTypes.Creditor))
                                {
                                    gljournaLine._Account     = trans._DCAccount;
                                    gljournaLine._AccountType = (byte)trans._DCType;
                                }
                            }
                        }

                        gljournaLine.SetMaster(cwObj.GlDailyJournal);
                        glDailyJrnlLineLst.Add(gljournaLine);
                    }
                    busyIndicator.IsBusy = true;
                    var result = await api.Insert(glDailyJrnlLineLst);

                    busyIndicator.IsBusy = false;
                    UtilDisplay.ShowErrorCode(result);
                }
            };
            cwObj.Show();
        }
Ejemplo n.º 11
0
        private async void ReadFromBilagscan(UnicontaBaseEntity selectedItem)
        {
#if !SILVERLIGHT
            if (!readingFromBilagscan)
            {
                readingFromBilagscan = true;

                bool processLines = false;
                var  accessToken  = await Bilagscan.Account.GetBilagscanAccessToken(api);

                var noOfVouchers    = 0;
                var companySettings = await api.Query <CompanySettingsClient>();

                var orgNo = companySettings.FirstOrDefault()._OrgNumber;

                var journal = dgGldailyJournal.SelectedItem as GLDailyJournalClient;

                //  UnicontaBaseEntity[] baseEntityArray = new UnicontaBaseEntity[1] { selectedItem };

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    var response = await client.GetAsync($"https://api.bilagscan.dk/v1/organizations/" + orgNo.ToString() + "/vouchers?seen=false&count=100&offset=0&sorts=-upload_date&status=successful");

                    var content = await response.Content.ReadAsStringAsync();

                    var vouchers = Bilagscan.Voucher.GetVouchers(content);

                    var credCache = api.CompanyEntity.GetCache(typeof(Uniconta.DataModel.Creditor)) ?? await api.CompanyEntity.LoadCache(typeof(Uniconta.DataModel.Creditor), api);

                    var offsetCache = api.CompanyEntity.GetCache(typeof(Uniconta.DataModel.GLAccount)) ?? await api.CompanyEntity.LoadCache(typeof(Uniconta.DataModel.GLAccount), api);

                    var vouchersSeen = new CommaDelimitedStringCollection();

                    var master = new List <UnicontaBaseEntity>
                    {
                        journal
                    };

                    var newLines       = new List <UnicontaBaseEntity>();
                    var updateCreditor = new List <UnicontaBaseEntity>();

                    if (vouchers?.data != null)
                    {
                        var creditors = credCache.GetKeyStrRecords as Uniconta.DataModel.Creditor[];

                        foreach (var voucher in vouchers.data)
                        {
                            vouchersSeen.Add(NumberConvert.ToString(voucher.id));
                            var journalLine = new GLDailyJournalLineClient()
                            {
                                Approved        = false,
                                ForceSettlement = false
                            };

                            var postingType = BilagscanVoucherType.Invoice;

                            var hint = Bilagscan.Voucher.GetHint(voucher.note);

                            var bilagscanRefID = voucher.id;
                            journalLine.ReferenceNumber = bilagscanRefID != 0 ? NumberConvert.ToString(bilagscanRefID) : null;

                            var bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "voucher_number", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                journalLine.Invoice = bsItem.value;
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "voucher_type", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                switch (bsItem.value)
                                {
                                case "invoice": postingType = BilagscanVoucherType.Invoice; break;

                                case "creditnote": postingType = BilagscanVoucherType.Creditnote; break;

                                case "receipt": postingType = BilagscanVoucherType.Receipt; break;
                                }
                            }

                            var creditorCVR = string.Empty;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "company_vat_reg_no", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                creditorCVR = bsItem.value;
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "total_amount_incl_vat", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                journalLine.Amount = Math.Abs(NumberConvert.ToDoubleNoThousandSeperator(bsItem.value));

                                if (postingType != BilagscanVoucherType.Creditnote)
                                {
                                    journalLine.Amount = -journalLine.Amount;
                                }
                            }

                            CountryCode countryCode = CountryCode.Denmark;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "country", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                CountryISOCode countryISO;
                                countryCode = CountryCode.Denmark; //default
                                if (Enum.TryParse(bsItem.value, true, out countryISO))
                                {
                                    countryCode = (CountryCode)countryISO;
                                }
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "invoice_date", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                var invoiceDate = bsItem.value == string.Empty ? GetSystemDefaultDate() : StringSplit.DateParse(bsItem.value, DateFormat.ymd);
                                journalLine.Date = invoiceDate;

                                if (journalLine.Date == DateTime.MinValue)
                                {
                                    journalLine.Date = GetSystemDefaultDate();
                                }
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_date", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                var paymentDate = bsItem.value == string.Empty ? DateTime.MinValue : StringSplit.DateParse(bsItem.value, DateFormat.ymd);
                                journalLine._DueDate = paymentDate;
                            }

                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "currency", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                Currencies currencyISO;
                                if (!Enum.TryParse(bsItem.value, true, out currencyISO))
                                {
                                    currencyISO = Currencies.DKK; //default
                                }
                                journalLine._Currency = (byte)currencyISO;
                            }

                            string bbanAcc = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_account_number", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                bbanAcc = bsItem.value;
                            }

                            string bbanRegNum = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_reg_number", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                bbanRegNum = bsItem.value;
                            }

                            string ibanNo = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_iban", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                ibanNo = bsItem.value;
                            }

                            string swiftNo = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_swift_bic", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                swiftNo = bsItem.value;
                            }

                            string paymentCodeId = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_code_id", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                paymentCodeId = bsItem.value;
                            }

                            string paymentId = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "payment_id", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                paymentId = bsItem.value;
                            }

                            string jointPaymentId = null;
                            bsItem = voucher.header_fields.Where(hf => string.Compare(hf.code, "joint_payment_id", true) == 0).FirstOrDefault();
                            if (bsItem != null)
                            {
                                jointPaymentId = bsItem.value;
                            }

                            var paymentMethod = PaymentTypes.VendorBankAccount;
                            switch (paymentCodeId)
                            {
                            case "71": paymentMethod = PaymentTypes.PaymentMethod3; break;

                            case "73": paymentMethod = PaymentTypes.PaymentMethod4; break;

                            case "75": paymentMethod = PaymentTypes.PaymentMethod5; break;

                            case "04":
                            case "4": paymentMethod = PaymentTypes.PaymentMethod6; break;
                            }

                            if (paymentMethod != PaymentTypes.VendorBankAccount && (paymentId != null || jointPaymentId != null))
                            {
                                journalLine._PaymentMethod = paymentMethod;
                                journalLine._PaymentId     = string.Format("{0} +{1}", paymentId, jointPaymentId);
                            }
                            else if (bbanRegNum != null && bbanAcc != null)
                            {
                                journalLine._PaymentMethod = PaymentTypes.VendorBankAccount;
                                journalLine._PaymentId     = string.Format("{0}-{1}", bbanRegNum, bbanAcc);
                            }
                            else if (swiftNo != null && ibanNo != null)
                            {
                                journalLine._PaymentMethod = PaymentTypes.IBAN;
                                journalLine._PaymentId     = ibanNo;
                            }

                            journalLine.SettleValue = "Voucher";

                            Uniconta.DataModel.Creditor creditor = null;

                            if (hint != null)
                            {
                                journalLine._DocumentRef = hint.RowId;
                                //if (hint.CreditorAccount != null)
                                //    creditor = (Uniconta.DataModel.Creditor)credCache.Get(hint.CreditorAccount);
                                //if (hint.Amount != 0)
                                //    journalLine.Amount = hint.Amount;
                                //if (hint.Currency != null && hint.Currency != "-")
                                //    journalLine.Currency = hint.Currency;
                                //if (hint.PaymentId != null)
                                //{
                                //    journalLine._PaymentId = hint.PaymentId;
                                //    journalLine.PaymentMethod = hint.PaymentMethod;
                                //}
                            }

                            journalLine._AccountType = 2;

                            var creditorCVRNum = Regex.Replace(creditorCVR, "[^0-9]", string.Empty);

                            if (creditorCVRNum != string.Empty)
                            {
                                creditor = creditors.Where(s => (Regex.Replace(s._LegalIdent ?? string.Empty, "[^0-9.]", "") == creditorCVRNum)).FirstOrDefault();
                            }

                            if (creditorCVRNum == string.Empty)
                            {
                                journalLine.Text = Uniconta.ClientTools.Localization.lookup("NotValidVatNo");
                            }
                            else if (creditor == null)
                            {
                                var newCreditor = new CreditorClient()
                                {
                                    _Account       = creditorCVR,
                                    _LegalIdent    = creditorCVR,
                                    _PaymentMethod = journalLine._PaymentMethod,
                                    _PaymentId     = journalLine._PaymentId,
                                    _SWIFT         = swiftNo
                                };

                                CompanyInfo companyInformation = null;
                                try
                                {
                                    companyInformation = await CVR.CheckCountry(creditorCVR, countryCode);
                                }
                                catch (Exception ex)
                                {
                                    UnicontaMessageBox.Show(ex);
                                    return;
                                }

                                if (companyInformation != null)
                                {
                                    if (companyInformation.life != null)
                                    {
                                        newCreditor._Name = companyInformation.life.name;
                                    }

                                    if (companyInformation.address != null)
                                    {
                                        newCreditor._Address1 = companyInformation.address.CompleteStreet;
                                        newCreditor._ZipCode  = companyInformation.address.zipcode;
                                        newCreditor._City     = companyInformation.address.cityname;
                                        newCreditor._Country  = companyInformation.address.Country;
                                    }

                                    if (companyInformation.contact != null)
                                    {
                                        newCreditor._Phone        = companyInformation.contact.phone;
                                        newCreditor._ContactEmail = companyInformation.contact.email;
                                    }

                                    journalLine.Text = newCreditor.Name;
                                }
                                else
                                {
                                    newCreditor.Name = Uniconta.ClientTools.Localization.lookup("NotValidVatNo");
                                }

                                await api.Insert(newCreditor);

                                journalLine.Account = creditorCVR;
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(creditor._PostingAccount))
                                {
                                    var account = (GLAccountClient)offsetCache.Get(creditor._PostingAccount);
                                    if (!string.IsNullOrEmpty(account.Vat))
                                    {
                                        var dailyJournal = (GLDailyJournalClient)master[0];
                                        if (dailyJournal.TwoVatCodes)
                                        {
                                            journalLine._OffsetVat = account.Vat;
                                        }
                                        else
                                        {
                                            journalLine._Vat = account.Vat;
                                        }
                                    }

                                    journalLine._OffsetAccount = creditor._PostingAccount;
                                }
                                else
                                {
                                    journalLine.Vat = creditor._Vat;
                                }


                                if (journalLine._DueDate == DateTime.MinValue && creditor._Payment != string.Empty)
                                {
                                    var paymentTermsCache = api.GetCache(typeof(PaymentTerm)) ?? await api.LoadCache(typeof(PaymentTerm));

                                    var paymentTerm = (PaymentTerm)paymentTermsCache.Get(creditor._Payment);

                                    if (paymentTerm != null)
                                    {
                                        journalLine._DueDate = paymentTerm.GetDueDate(journalLine.DueDate);
                                    }
                                }

                                journalLine.Account = creditor._Account;
                                journalLine.Text    = creditor._Name;

                                if (creditor._SWIFT == null && swiftNo != null)
                                {
                                    creditor._SWIFT = swiftNo;
                                    updateCreditor.Add(creditor);
                                }
                            }

                            journalLine.SetMaster(master[0]);
                            newLines.Add(journalLine);

                            noOfVouchers += 1;
                        }
                    }
                    var errorCode = await api.Insert(newLines);

                    api.UpdateNoResponse(updateCreditor);

                    if (vouchersSeen.Count != 0)
                    {
                        // Mark voucher as seen
                        string serializedRequest = "{ \"vouchers\": [ " + vouchersSeen.ToString() + " ] }";
                        var    vContent          = new StringContent(serializedRequest, Encoding.UTF8, "application/json");
                        response = await client.PostAsync($"https://api.bilagscan.dk/v1/organizations/" + NumberConvert.ToString(orgNo) + "/vouchers/seen", vContent);

                        var res = await response.Content.ReadAsStringAsync();
                    }
                }

                if (noOfVouchers == 0)
                {
                    UnicontaMessageBox.Show(string.Format(Uniconta.ClientTools.Localization.lookup("StillProcessingTryAgain"), Uniconta.ClientTools.Localization.lookup("Bilagscan")), Uniconta.ClientTools.Localization.lookup("Bilagscan"), MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    var messageText = string.Concat(string.Format("{0} {1}", Uniconta.ClientTools.Localization.lookup("NumberOfImportedVouchers"), noOfVouchers),
                                                    Environment.NewLine, Environment.NewLine,
                                                    string.Format(Uniconta.ClientTools.Localization.lookup("GoTo"), Uniconta.ClientTools.Localization.lookup("Journallines")), "?");
                    if (UnicontaMessageBox.Show(messageText, Uniconta.ClientTools.Localization.lookup("BilagscanRead"), MessageBoxButton.OKCancel, MessageBoxImage.Information) == MessageBoxResult.OK)
                    {
                        AddDockItem(TabControls.GL_DailyJournalLine, journal, null, null, true);
                    }
                }
                readingFromBilagscan = false;
            }
#endif
        }
Ejemplo n.º 12
0
        public void InsertGLDailyJournalLines(MemBogfoeringsKlader karKladde)
        {
            var crit = new List <PropValuePair>();
            var pair = PropValuePair.GenereteWhereElements("KeyStr", typeof(String), "Dag");

            crit.Add(pair);
            var task1 = m_api.Query <GLDailyJournalClient>(crit);

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

            foreach (var kk in karKladde)
            {
                GLDailyJournalLineClient jl = new GLDailyJournalLineClient()
                {
                    Date = (DateTime)kk.Dato,
                    Text = kk.Tekst,
                };
                if ((kk.Afstemningskonto == "Bank") &&
                    (kk.Kontonr == null))
                {
                    jl.Account = "5840";
                    if (kk.Belob > 0)
                    {
                        jl.Debit = (double)kk.Belob;
                    }
                    else
                    {
                        jl.Credit = -(double)kk.Belob;
                    }
                }

                if ((kk.Afstemningskonto == "PayPal") &&
                    (kk.Kontonr == null))
                {
                    jl.Account = "5830";
                    if (kk.Belob > 0)
                    {
                        jl.Debit = (double)kk.Belob;
                    }
                    else
                    {
                        jl.Credit = -(double)kk.Belob;
                    }
                }

                if ((kk.Afstemningskonto == "PayPal") && //NEW
                    (kk.Kontonr != null))
                {
                    jl.Account       = "5830";
                    jl.OffsetAccount = kk.Kontonr.ToString();
                    if (kk.Belob > 0)
                    {
                        jl.Debit = (double)kk.Belob;
                    }
                    else
                    {
                        jl.Credit = -(double)kk.Belob;
                    }
                }

                if ((String.IsNullOrEmpty(kk.Afstemningskonto)) &&
                    (kk.Kontonr != null))
                {
                    jl.Account = kk.Kontonr.ToString();
                    if (kk.Belob > 0)
                    {
                        jl.Credit = (double)kk.Belob;
                    }
                    else
                    {
                        jl.Debit = -(double)kk.Belob;
                    }
                }
                jl.SetMaster(rec_Master);
                var task2 = m_api.Insert(jl);
                task2.Wait();
                var err = task2.Result;
            }
        }
Ejemplo n.º 13
0
        public int InsertGLDailyJournalLines(IOrderedQueryable <tblbankkonto> qrybankkonto)
        {
            var GLDailyJournalLines = 0;
            var crit = new List <PropValuePair>();
            var pair = PropValuePair.GenereteWhereElements("KeyStr", typeof(String), "Dag");

            crit.Add(pair);
            var task1 = m_api.Query <GLDailyJournalClient>(crit);

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

            foreach (var bk in qrybankkonto)
            {
                tblmobilepay mp = null;

                var qrymobilepay = from v in m_dbData3060.tblmobilepays
                                   where v.pid == bk.mobilepay_pid &&
                                   (v.Bogfoert == null || v.Bogfoert == false)
                                   select v;
                var qrycount = qrymobilepay.Count();
                if (qrycount == 1)
                {
                    mp = qrymobilepay.First();
                }
                else
                {
                    continue;
                }

                GLDailyJournalLines++;

                GLDailyJournalLineClient jl = new GLDailyJournalLineClient()
                {
                    Date    = (DateTime)bk.dato,
                    Text    = bk.tekst,
                    Account = "5850",
                };

                if (bk.belob > 0)
                {
                    jl.Debit = (double)bk.belob;
                }
                else
                {
                    jl.Credit = -(double)bk.belob;
                }


                switch (mp.Type.ToUpper())
                {
                case "SALG":
                    jl.OffsetAccount = "1004";
                    break;

                case "REFUNDERING":
                    jl.OffsetAccount = "1004";
                    break;

                case "GEBYR":
                    jl.OffsetAccount = "4471";
                    break;

                case "OVERFØRSEL":
                    jl.OffsetAccount = "5840";
                    break;

                default:
                    jl.OffsetAccount = "9900";
                    break;
                }

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

                mp.Bogfoert = true;
            }
            m_dbData3060.SubmitChanges();

            return(GLDailyJournalLines);
        }
        void InitPage(UnicontaBaseEntity master)
        {
            InitializeComponent();
            _master            = master;
            glDailyJournalLine = master as GLDailyJournalLineClient;
            bankStatementLine  = master as BankStatementLineClient;
            vouchersClient     = master as VouchersClient;

            ((TableView)dgGlOffSetAccountTplt.View).RowStyle = Application.Current.Resources["StyleRow"] as Style;
            localMenu.dataGrid        = dgGlOffSetAccountTplt;
            dgGlOffSetAccountTplt.api = api;
            SetRibbonControl(localMenu, dgGlOffSetAccountTplt);
            dgGlOffSetAccountTplt.BusyIndicator = busyIndicator;
            localMenu.OnItemClicked            += LocalMenu_OnItemClicked;
            dgGlOffSetAccountTplt.View.DataControl.CurrentItemChanged += DataControl_CurrentItemChanged;
            btnAdd.Content    = Uniconta.ClientTools.Localization.lookup("Add");
            btnEdit.Content   = string.Format(Uniconta.ClientTools.Localization.lookup("EditOBJ"), (Uniconta.ClientTools.Localization.lookup("Name")));
            btnDelete.Content = Uniconta.ClientTools.Localization.lookup("Delete");
            var company = api.CompanyEntity;

            LedgerCache   = company.GetCache(typeof(Uniconta.DataModel.GLAccount));
            DebtorCache   = company.GetCache(typeof(Uniconta.DataModel.Debtor));
            CreditorCache = company.GetCache(typeof(Uniconta.DataModel.Creditor));
            RibbonBase rb = (RibbonBase)localMenu.DataContext;

            if (company.RoundTo100)
            {
                Debit.HasDecimals = Credit.HasDecimals = Amount.HasDecimals = false;
            }
            else
            {
                Decimals = 2;
            }
            if (_master != null)
            {
                dgGlOffSetAccountTplt.UpdateMaster(master);
                var glOffSetAccLines = new List <GLOffsetAccountLineGridClient>();

                GLOffsetAccountLine[] glOffsetLines;
                if (glDailyJournalLine != null)
                {
                    glOffsetLines = glDailyJournalLine.GetOffsetAccount(typeof(GLOffsetAccountLineGridClient));
                }
                else if (bankStatementLine != null)
                {
                    glOffsetLines = bankStatementLine.GetOffsetAccount(typeof(GLOffsetAccountLineGridClient));
                }
                else if (vouchersClient != null)
                {
                    glOffsetLines = vouchersClient.GetOffsetAccount(typeof(GLOffsetAccountLineGridClient));
                }
                else
                {
                    glOffsetLines = null;
                }
                if (glOffsetLines != null)
                {
                    foreach (var item in glOffsetLines)
                    {
                        item.SetMaster(company);
                        glOffSetAccLines.Add(item as GLOffsetAccountLineGridClient);
                    }
                }
                dgGlOffSetAccountTplt.ItemsSource = glOffSetAccLines;
                dgGlOffSetAccountTplt.Visibility  = Visibility.Visible;
                RecalculateSum();
                btnAdd.Visibility = btnDelete.Visibility = btnEdit.Visibility = Visibility.Collapsed;
                UtilDisplay.RemoveMenuCommand(rb, "SaveGrid");
            }
            else
            {
                UtilDisplay.RemoveMenuCommand(rb, new string[] { "SaveAndClose", "StatusAmt", "StatusSum", "StatusDiff", "LoadTemplate",
                                                                 "SaveTemplate", "DeleteTemplate" });
            }

            var TemplateCache = company.GetCache(typeof(Uniconta.DataModel.GLOffsetAccountTemplate));

            if (TemplateCache == null)
            {
                BindComboBox();
            }
            else
            {
                BindComboBox(TemplateCache);
            }
        }