Exemple #1
0
        } // End of the GetInvoices method

        /// <summary>
        /// Get an invoice to export
        /// </summary>
        public async Task<AnnytabDoxTradeRoot> GetInvoice(string id)
        {
            // Get data
            Dictionary<string, string> labels = await GetLabels();
            CompanySettingsRoot company = await GetCompanySettings();

            // Make sure that company and company.Settings not is null
            if (company == null || company.CompanySettings == null)
            {
                this.logger.LogError($"GetInvoice: {id}, Could not find any company settings.");
                return null;
            }

            // Get the invoice
            FortnoxResponse<InvoiceRoot> fr = await this.nox_client.Get<InvoiceRoot>($"invoices/{id}");

            // Return if model or model.Invoice is null
            if (fr.model == null || fr.model.Invoice == null)
            {
                // Log the error and return null
                this.logger.LogError(fr.error);
                return null;
            }

            // Check if the invoice should be exported
            bool export_invoice = false;
            foreach (Label label in fr.model.Invoice.Labels)
            {
                if (labels.ContainsKey(label.Id) && labels[label.Id] == "a-dox-trade-v1")
                {
                    // Export the invoice
                    export_invoice = true;
                    break;
                }
            }

            // Return null if the invoice not should be exported
            if (export_invoice == false)
            {
                return null;
            }

            // Get the customer
            FortnoxResponse<CustomerRoot> fr_customer = await this.nox_client.Get<CustomerRoot>($"customers/{fr.model.Invoice.CustomerNumber}");

            // Return if model or model.Customer is null
            if (fr_customer.model == null || fr_customer.model.Customer == null)
            {
                // Log the error and return null
                this.logger.LogError(fr_customer.error);
                return null;
            }

            // Create an invoice
            AnnytabDoxTrade post = await CreateInvoice(company, fr.model, fr_customer.model);

            // Return the post
            return new AnnytabDoxTradeRoot { document_type = post.document_type, document = post, email = fr_customer.model.Customer.Email, language_code = fr.model.Invoice.Language };

        } // End of the GetInvoice method
Exemple #2
0
        /// <summary>
        /// Create a new post
        /// </summary>
        public AnnytabDoxTradeRoot()
        {
            // Set values for instance variables
            this.document_type = null;
            this.document = null;
            this.email = null;
            this.language_code = null;

        } // End of the constructor
Exemple #3
0
        } // End of the CreateAnnytabDoxMeta method

        /// <summary>
        /// Create an quotation according to the Annytab Dox Trade v1 standard
        /// </summary>
        public static byte[] CreateAnnytabDoxQuotation()
        {
            // Create an order
            AnnytabDoxTrade post = new AnnytabDoxTrade();
            post.id = Guid.NewGuid().ToString();
            post.document_type = "quotation";
            post.payment_reference = "D1005";
            post.issue_date = "2020-04-15";
            post.due_date = "2020-04-30";
            post.delivery_date = "2020-04-15";
            post.buyer_references = new Dictionary<string, string>();
            post.buyer_references.Add("customer_id", "105");
            post.terms_of_delivery = "EXW";
            post.terms_of_payment = "15";
            post.mode_of_delivery = "WEB";
            post.total_weight_kg = 0M;
            post.penalty_interest = 0.10M;
            post.currency_code = "SEK";
            post.vat_country_code = "SE";
            post.vat_state_code = null;
            post.comment = "Thank you for buying from us.";
            post.seller_information = new PartyInformation()
            {
                person_id = "556864-2747",
                person_name = "A Name Not Yet Taken AB",
                address_line_1 = "Klyvaregatan 1 lgh 1103",
                postcode = "30290",
                city_name = "Halmstad",
                country_name = "Sweden",
                country_code = "SE",
                contact_name = "Fredrik Stigsson",
                email = "*****@*****.**",
                vat_number = "SE556864274701"
            };
            post.buyer_information = new PartyInformation
            {
                person_id = "888888-9999",
                person_name = "Jan Jansson",
                address_line_1 = "St. Eriksgatan 15",
                address_line_2 = "Floor 1",
                postcode = "500505",
                city_name = "Stockholm",
                country_name = "Sweden",
                country_code = "SE",
                state_code = null,
                contact_name = "Jan Jansson",
                phone_number = "078008080",
                email = "*****@*****.**",
                vat_number = "SE888888999901"
            };
            post.product_rows = new List<ProductRow>();
            post.product_rows.Add(new ProductRow
            {
                product_code = "GiB",
                manufacturer_code = "GiB",
                gtin = "",
                product_name = "Gibibytes",
                vat_rate = 0.25M,
                quantity = 1000M,
                unit_code = "pcs",
                unit_price = 0.5M,
                subrows = new List<ProductRow>()
            });
            post.product_rows.Add(new ProductRow
            {
                product_code = "File",
                manufacturer_code = "File",
                gtin = "",
                product_name = "Files",
                vat_rate = 0.12M,
                quantity = 100M,
                unit_code = "pcs",
                unit_price = 0.4M,
                subrows = null
            });
            post.product_rows.Add(new ProductRow
            {
                product_code = "Sign",
                manufacturer_code = "Sign",
                gtin = "",
                product_name = "Signatures",
                vat_rate = 0.06M,
                quantity = 13M,
                unit_code = "pcs",
                unit_price = 60M,
                subrows = null
            });
            post.vat_specification = new List<VatSpecification>();
            post.vat_specification.Add(new VatSpecification
            {
                tax_rate = 0.25M,
                taxable_amount = 500M,
                tax_amount = 125M
            });
            post.vat_specification.Add(new VatSpecification
            {
                tax_rate = 0.12M,
                taxable_amount = 40M,
                tax_amount = 4.80M
            });
            post.vat_specification.Add(new VatSpecification
            {
                tax_rate = 0.06M,
                taxable_amount = 780M,
                tax_amount = 46.8M
            });
            post.subtotal = 1320M;
            post.vat_total = 176.60M;
            post.rounding = 0.4M;
            post.total = 1497M;
            post.paid_amount = 0M;
            post.balance_due = 1497M;

            // Convert the object to a byte array and return it
            return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(post));

        } // End of the CreateAnnytabDoxQuotation method
        } // End of the AddOrder method

        /// <summary>
        /// Add an supplier invoice
        /// </summary>
        public async Task<SupplierInvoiceRoot> AddSupplierInvoice(string dox_email, AnnytabDoxTrade doc)
        {
            // Terms of payment
            if (string.IsNullOrEmpty(doc.terms_of_payment) == false)
            {
                doc.terms_of_payment = CommonTools.ConvertToAlphanumeric(doc.terms_of_payment).ToUpper().Replace("-", "");
                await AddTermsOfPayment(doc.terms_of_payment);
            }

            // Currency
            if (string.IsNullOrEmpty(doc.currency_code) == false)
            {
                doc.currency_code = doc.currency_code.ToUpper();
                await AddCurrency(doc.currency_code);
            }

            // Upsert the supplier
            SupplierRoot supplier_root = await UpsertSupplier(dox_email, doc);

            // Return if the supplier_root is null
            if(supplier_root == null || supplier_root.Supplier == null)
            {
                return null;
            }

            // Create a list with supplier invoice rows
            IList<SupplierInvoiceRow> rows = new List<SupplierInvoiceRow>();

            //// Add accounts payable amount
            //if(doc.total != null && doc.total != 0M)
            //{
            //    rows.Add(new SupplierInvoiceRow
            //    {
            //        Code = "TOT",
            //        Total = doc.total * -1
            //    });
            //}
            
            //// Add value added tax
            //if (doc.vat_total != null && doc.vat_total != 0M)
            //{
            //    rows.Add(new SupplierInvoiceRow
            //    {
            //        Code = "VAT",
            //        Total = doc.vat_total
            //    });
            //}

            //// Add rounding
            //if(doc.rounding != null && doc.rounding != 0M)
            //{
            //    rows.Add(new SupplierInvoiceRow
            //    {
            //        Code = "ROV",
            //        Total = doc.rounding
            //    });
            //}
            
            // Add supplier invoice rows
            if (doc.product_rows != null)
            {
                await AddSupplierInvoiceRows(doc.product_rows, rows);
            }

            // Create a supplier invoice
            SupplierInvoiceRoot root = new SupplierInvoiceRoot
            {
                SupplierInvoice = new SupplierInvoice
                {
                    SupplierNumber = supplier_root.Supplier.SupplierNumber,
                    InvoiceNumber = string.IsNullOrEmpty(doc.payment_reference) == false ? doc.payment_reference : null,
                    InvoiceDate = string.IsNullOrEmpty(doc.issue_date) == false ? doc.issue_date : null,
                    DueDate = string.IsNullOrEmpty(doc.due_date) == false ? doc.due_date : null,
                    Currency = doc.currency_code,
                    Comments = doc.comment,
                    Total = doc.total != null ? doc.total : 0M,
                    VAT = doc.vat_total != null ? doc.vat_total : 0M,
                    RoundOffValue = doc.rounding != null ? doc.rounding : 0M,
                    SupplierInvoiceRows = rows
                }
            };

            // Add a supplier invoice
            FortnoxResponse<SupplierInvoiceRoot> fr = await this.nox_client.Add<SupplierInvoiceRoot>(root, "supplierinvoices");
            
            // Log errors
            if (string.IsNullOrEmpty(fr.error) == false)
            {
                this.logger.LogError(fr.error);
            }

            // Return the supplier invoice
            return fr.model;

        } // End of the AddSupplierInvoice method
        } // End of the AddOffer method

        /// <summary>
        /// Add an order
        /// </summary>
        public async Task<OrderRoot> AddOrder(string dox_email, AnnytabDoxTrade doc)
        {
            // Terms of delivery
            if (string.IsNullOrEmpty(doc.terms_of_delivery) == false)
            {
                doc.terms_of_delivery = CommonTools.ConvertToAlphanumeric(doc.terms_of_delivery).ToUpper();
                await AddTermsOfDelivery(doc.terms_of_delivery);
            }

            // Terms of payment
            if (string.IsNullOrEmpty(doc.terms_of_payment) == false)
            {
                doc.terms_of_payment = CommonTools.ConvertToAlphanumeric(doc.terms_of_payment).ToUpper().Replace("-", "");
                await AddTermsOfPayment(doc.terms_of_payment);
            }

            // Way of delivery
            if (string.IsNullOrEmpty(doc.mode_of_delivery) == false)
            {
                doc.mode_of_delivery = CommonTools.ConvertToAlphanumeric(doc.mode_of_delivery).ToUpper();
                await AddWayOfDelivery(doc.mode_of_delivery);
            }

            // Currency
            if (string.IsNullOrEmpty(doc.currency_code) == false)
            {
                doc.currency_code = doc.currency_code.ToUpper();
                await AddCurrency(doc.currency_code);
            }

            // Upsert the customer
            CustomerRoot customer_root = await UpsertCustomer(dox_email, doc);

            // Return if the customer is null
            if (customer_root == null || customer_root.Customer == null)
            {
                return null;
            }

            // Create a list with order rows
            IList<OrderRow> rows = new List<OrderRow>();

            // Add order rows
            if (doc.product_rows != null)
            {
                await AddOrderRows(doc.product_rows, rows);
            }

            // Create an order
            OrderRoot root = new OrderRoot
            {
                Order = new Order
                {
                    CustomerNumber = customer_root.Customer.CustomerNumber,
                    OrderDate = string.IsNullOrEmpty(doc.issue_date) == false ? doc.issue_date : null,
                    DeliveryDate = string.IsNullOrEmpty(doc.delivery_date) == false ? doc.delivery_date : null,
                    YourOrderNumber = doc.buyer_references != null && doc.buyer_references.ContainsKey("order_id") ? doc.buyer_references["order_id"] : null,
                    ExternalInvoiceReference1 = string.IsNullOrEmpty(doc.payment_reference) == false ? doc.payment_reference : null,
                    ExternalInvoiceReference2 = string.IsNullOrEmpty(doc.id) == false ? doc.id : null,
                    Comments = doc.comment,
                    OrderRows = rows,
                    Currency = doc.currency_code,
                    VATIncluded = false
                }
            };

            // Add the order
            FortnoxResponse<OrderRoot> fr = await this.nox_client.Add<OrderRoot>(root, "orders");

            // Log errors
            if (string.IsNullOrEmpty(fr.error) == false)
            {
                this.logger.LogError(fr.error);
            }

            // Return the order
            return fr.model;

        } // End of the AddOrder method
        } // End of the UpsertCustomer method

        /// <summary>
        /// Add or update a supplier
        /// </summary>
        public async Task<SupplierRoot> UpsertSupplier(string dox_email, AnnytabDoxTrade doc)
        {
            // Create variables
            FortnoxResponse<SupplierRoot> fr = new FortnoxResponse<SupplierRoot>();
            bool supplier_exists = false;
            string supplier_email = doc.seller_information != null && string.IsNullOrEmpty(doc.seller_information.email) == false ? doc.seller_information.email : dox_email;

            // Find suppliers on email
            FortnoxResponse<SuppliersRoot> fr_page = await this.nox_client.Get<SuppliersRoot>($"suppliers?email={supplier_email}");

            // Log errors
            if (string.IsNullOrEmpty(fr_page.error) == false)
            {
                this.logger.LogError(fr_page.error);
            }

            // Make sure that at least one supplier was found
            if (fr_page.model != null && fr_page.model.Suppliers != null && fr_page.model.Suppliers.Count > 0)
            {
                // Get a supplier
                fr = await this.nox_client.Get<SupplierRoot>($"suppliers/{fr_page.model.Suppliers[0].SupplierNumber}");

                // Log errors
                if (string.IsNullOrEmpty(fr.error) == false)
                {
                    this.logger.LogError(fr.error);
                }
            }

            // Check if the supplier exists
            if (fr.model != null)
            {
                supplier_exists = true;
            }
            else
            {
                fr.model = new SupplierRoot { Supplier = new Supplier() };
            }

            // Update the supplier
            fr.model.Supplier.Email = supplier_email;
            if (doc.buyer_information != null)
            {
                fr.model.Supplier.OurReference = string.IsNullOrEmpty(fr.model.Supplier.OurReference) == true ? doc.buyer_information.contact_name : fr.model.Supplier.OurReference;
            }
            if(doc.seller_information != null)
            {
                fr.model.Supplier.Name = string.IsNullOrEmpty(doc.seller_information.person_name) == false ? doc.seller_information.person_name : fr.model.Supplier.Name;
                fr.model.Supplier.OrganisationNumber = string.IsNullOrEmpty(doc.seller_information.person_id) == false ? doc.seller_information.person_id : fr.model.Supplier.OrganisationNumber;
                fr.model.Supplier.VATNumber = string.IsNullOrEmpty(doc.seller_information.vat_number) == false ? doc.seller_information.vat_number : fr.model.Supplier.VATNumber;
                fr.model.Supplier.YourReference = string.IsNullOrEmpty(doc.seller_information.contact_name) == false ? doc.seller_information.contact_name : fr.model.Supplier.YourReference;
                fr.model.Supplier.Phone1 = string.IsNullOrEmpty(doc.seller_information.phone_number) == false ? doc.seller_information.phone_number : fr.model.Supplier.Phone1;
                fr.model.Supplier.Address1 = string.IsNullOrEmpty(doc.seller_information.address_line_1) == false ? doc.seller_information.address_line_1 : fr.model.Supplier.Address1;
                fr.model.Supplier.Address2 = string.IsNullOrEmpty(doc.seller_information.address_line_2) == false ? doc.seller_information.address_line_2 : fr.model.Supplier.Address2;
                fr.model.Supplier.ZipCode = string.IsNullOrEmpty(doc.seller_information.postcode) == false ? doc.seller_information.postcode : fr.model.Supplier.ZipCode;
                fr.model.Supplier.City = string.IsNullOrEmpty(doc.seller_information.city_name) == false ? doc.seller_information.city_name : fr.model.Supplier.City;
                fr.model.Supplier.CountryCode = string.IsNullOrEmpty(doc.seller_information.country_code) == false ? doc.seller_information.country_code : fr.model.Supplier.CountryCode;
            }
            fr.model.Supplier.Currency = string.IsNullOrEmpty(doc.currency_code) == false ? doc.currency_code : fr.model.Supplier.Currency;
            fr.model.Supplier.TermsOfPayment = string.IsNullOrEmpty(doc.terms_of_payment) == false ? doc.terms_of_payment : fr.model.Supplier.TermsOfPayment;
            fr.model.Supplier.VATType = string.IsNullOrEmpty(fr.model.Supplier.VATType) == true ? "NORMAL" : fr.model.Supplier.VATType;
            fr.model.Supplier.OurCustomerNumber = doc.buyer_references != null && doc.buyer_references.ContainsKey("customer_id") ? doc.buyer_references["customer_id"] : null;
            if(doc.payment_options != null)
            {
                // Loop payment options
                foreach(PaymentOption po in doc.payment_options)
                {
                    // Get the name
                    string name = po.name.ToUpper();

                    // Add information based on name
                    if (name == "IBAN")
                    {
                        fr.model.Supplier.BIC = string.IsNullOrEmpty(po.bank_identifier_code) == false ? po.bank_identifier_code : fr.model.Supplier.BIC;
                        fr.model.Supplier.IBAN = string.IsNullOrEmpty(po.account_reference) == false ? po.account_reference : fr.model.Supplier.IBAN;
                    }
                    else if (name == "BG")
                    {
                        fr.model.Supplier.BG = string.IsNullOrEmpty(po.account_reference) == false ? po.account_reference : fr.model.Supplier.BG;
                    }
                    else if (name == "PG")
                    {
                        fr.model.Supplier.PG = string.IsNullOrEmpty(po.account_reference) == false ? po.account_reference : fr.model.Supplier.PG;
                    }
                    else if (name == "BANK")
                    {
                        fr.model.Supplier.BankAccountNumber = string.IsNullOrEmpty(po.account_reference) == false ? po.account_reference.Replace(" ", "").Replace("-", "") : fr.model.Supplier.BankAccountNumber;
                        fr.model.Supplier.Bank = string.IsNullOrEmpty(po.bank_name) == false ? po.bank_name : fr.model.Supplier.Bank;
                    }
                }
            }

            // Add or update the supplier
            if (supplier_exists == true)
            {
                fr = await this.nox_client.Update<SupplierRoot>(fr.model, $"suppliers/{fr.model.Supplier.SupplierNumber}");
            }
            else
            {
                fr = await this.nox_client.Add<SupplierRoot>(fr.model, "suppliers");
            }

            // Log errors
            if (string.IsNullOrEmpty(fr.error) == false)
            {
                this.logger.LogError(fr.error);
            }

            // Return the post
            return fr.model;

        } // End of the UpsertSupplier method
        } // End of the AddArticle method

        /// <summary>
        /// Add or update a customer
        /// </summary>
        public async Task<CustomerRoot> UpsertCustomer(string dox_email, AnnytabDoxTrade doc)
        {
            // Create variables
            FortnoxResponse<CustomerRoot> fr = new FortnoxResponse<CustomerRoot>();
            bool customer_exists = false;
            string customer_email = doc.buyer_information != null && string.IsNullOrEmpty(doc.buyer_information.email) == false ? doc.buyer_information.email : dox_email;

            // Find customers on email
            FortnoxResponse<CustomersRoot> fr_page = await this.nox_client.Get<CustomersRoot>($"customers?email={customer_email}");

            // Log errors
            if (string.IsNullOrEmpty(fr_page.error) == false)
            {
                this.logger.LogError(fr_page.error);
            }

            // Make sure that at least one customer was found
            if (fr_page.model != null && fr_page.model.Customers != null && fr_page.model.Customers.Count > 0)
            {
                // Get a customer
                fr = await this.nox_client.Get<CustomerRoot>($"customers/{fr_page.model.Customers[0].CustomerNumber}");

                // Log errors
                if (string.IsNullOrEmpty(fr.error) == false)
                {
                    this.logger.LogError(fr.error);
                }
            }

            // Check if the customer exists
            if (fr.model != null)
            {
                customer_exists = true;
            }
            else
            {
                fr.model = new CustomerRoot { Customer = new Customer() };
            }

            // Update the customer: ONLY SET VAT TYPE, ACCOUNT IS SET IN ARTICLE
            fr.model.Customer.Email = customer_email;
            if (doc.seller_information != null)
            {
                fr.model.Customer.OurReference = string.IsNullOrEmpty(fr.model.Customer.OurReference) == true ? doc.seller_information.contact_name : fr.model.Customer.OurReference;
            }
            if(doc.buyer_information != null)
            {
                fr.model.Customer.Name = string.IsNullOrEmpty(doc.buyer_information.person_name) == false ? doc.buyer_information.person_name : fr.model.Customer.Name;
                fr.model.Customer.OrganisationNumber = string.IsNullOrEmpty(doc.buyer_information.person_id) == false ? doc.buyer_information.person_id : fr.model.Customer.OrganisationNumber;
                fr.model.Customer.VATNumber = string.IsNullOrEmpty(doc.buyer_information.vat_number) == false ? doc.buyer_information.vat_number : fr.model.Customer.VATNumber;
                fr.model.Customer.YourReference = string.IsNullOrEmpty(doc.buyer_information.contact_name) == false ? doc.buyer_information.contact_name : fr.model.Customer.YourReference;
                fr.model.Customer.Phone1 = string.IsNullOrEmpty(doc.buyer_information.phone_number) == false ? doc.buyer_information.phone_number : fr.model.Customer.Phone1;
                fr.model.Customer.Address1 = string.IsNullOrEmpty(doc.buyer_information.address_line_1) == false ? doc.buyer_information.address_line_1 : fr.model.Customer.Address1;
                fr.model.Customer.Address2 = string.IsNullOrEmpty(doc.buyer_information.address_line_2) == false ? doc.buyer_information.address_line_2 : fr.model.Customer.Address2;
                fr.model.Customer.ZipCode = string.IsNullOrEmpty(doc.buyer_information.postcode) == false ? doc.buyer_information.postcode : fr.model.Customer.ZipCode;
                fr.model.Customer.City = string.IsNullOrEmpty(doc.buyer_information.city_name) == false ? doc.buyer_information.city_name : fr.model.Customer.City;
                fr.model.Customer.CountryCode = string.IsNullOrEmpty(doc.buyer_information.country_code) == false ? doc.buyer_information.country_code : fr.model.Customer.CountryCode;
                fr.model.Customer.EmailOffer = string.IsNullOrEmpty(fr.model.Customer.EmailOffer) == true ? customer_email : fr.model.Customer.EmailOffer;
                fr.model.Customer.EmailOrder = string.IsNullOrEmpty(fr.model.Customer.EmailOrder) == true ? customer_email : fr.model.Customer.EmailOrder;
                fr.model.Customer.EmailInvoice = string.IsNullOrEmpty(fr.model.Customer.EmailInvoice) == true ? customer_email : fr.model.Customer.EmailInvoice;
            }
            if(doc.delivery_information != null)
            {
                fr.model.Customer.DeliveryName = string.IsNullOrEmpty(doc.delivery_information.person_name) == false ? doc.delivery_information.person_name : fr.model.Customer.DeliveryName;
                fr.model.Customer.DeliveryPhone1 = string.IsNullOrEmpty(doc.delivery_information.phone_number) == false ? doc.delivery_information.phone_number : fr.model.Customer.DeliveryPhone1;
                fr.model.Customer.DeliveryAddress1 = string.IsNullOrEmpty(doc.delivery_information.address_line_1) == false ? doc.delivery_information.address_line_1 : fr.model.Customer.DeliveryAddress1;
                fr.model.Customer.DeliveryAddress2 = string.IsNullOrEmpty(doc.delivery_information.address_line_2) == false ? doc.delivery_information.address_line_2 : fr.model.Customer.DeliveryAddress2;
                fr.model.Customer.DeliveryCity = string.IsNullOrEmpty(doc.delivery_information.city_name) == false ? doc.delivery_information.city_name : fr.model.Customer.DeliveryCity;
                fr.model.Customer.DeliveryCountryCode = string.IsNullOrEmpty(doc.delivery_information.country_code) == false ? doc.delivery_information.country_code : fr.model.Customer.DeliveryCountryCode;
                fr.model.Customer.DeliveryZipCode = string.IsNullOrEmpty(doc.delivery_information.postcode) == false ? doc.delivery_information.postcode : fr.model.Customer.DeliveryZipCode;
            }
            fr.model.Customer.Currency = string.IsNullOrEmpty(doc.currency_code) == false ? doc.currency_code : fr.model.Customer.Currency;
            fr.model.Customer.TermsOfDelivery = string.IsNullOrEmpty(doc.terms_of_delivery) == false ? doc.terms_of_delivery : fr.model.Customer.TermsOfDelivery;
            fr.model.Customer.TermsOfPayment = string.IsNullOrEmpty(doc.terms_of_payment) == false ? doc.terms_of_payment : fr.model.Customer.TermsOfPayment;
            fr.model.Customer.VATType = CommonTools.GetCustomerVatType(fr.model.Customer, this.default_values);
            fr.model.Customer.WayOfDelivery = string.IsNullOrEmpty(doc.mode_of_delivery) == false ? doc.mode_of_delivery : fr.model.Customer.WayOfDelivery;
            fr.model.Customer.Type = string.IsNullOrEmpty(fr.model.Customer.Type) == true && string.IsNullOrEmpty(fr.model.Customer.VATNumber) == false ? "COMPANY" : fr.model.Customer.Type;
            fr.model.Customer.PriceList = string.IsNullOrEmpty(fr.model.Customer.PriceList) == true ? this.default_values.PriceList : fr.model.Customer.PriceList;

            // Add or update the customer
            if (customer_exists == true)
            {
                fr = await this.nox_client.Update<CustomerRoot>(fr.model, $"customers/{fr.model.Customer.CustomerNumber}");
            }
            else
            {
                fr = await this.nox_client.Add<CustomerRoot>(fr.model, "customers");
            }

            // Log errors
            if (string.IsNullOrEmpty(fr.error) == false)
            {
                this.logger.LogError(fr.error);
            }

            // Return the post
            return fr.model;

        } // End of the UpsertCustomer method
Exemple #8
0
        } // End of the run method

        /// <summary>
        /// Import to Fortnox
        /// </summary>
        private async Task RunImport(string directory, IDoxservrFilesClient dox_files_client, IFortnoxClient nox_client)
        {
            // Log the start
            this.logger.LogInformation("START: Importing documents to Fortnox!");

            // Get files from doxservr
            await GetDoxservrFiles(directory);

            // Create a list with accounts
            IList<string> accounts = new List<string> { this.default_values.SalesAccountEUREVERSEDVAT, this.default_values.SalesAccountEUVAT,
                this.default_values.SalesAccountEXPORT, this.default_values.SalesAccountSE0, this.default_values.SalesAccountSE12,
                this.default_values.SalesAccountSE25, this.default_values.SalesAccountSE6, this.default_values.SalesAccountSEREVERSEDVAT,
                this.default_values.PurchaseAccount };

            // Add accounts
            foreach(string account in accounts)
            {
                if(string.IsNullOrEmpty(account) == false)
                {
                    await this.fortnox_importer.AddAccount(account);
                }
            }

            // Add a price list
            if (string.IsNullOrEmpty(this.default_values.PriceList) == false)
            {
                this.default_values.PriceList = this.default_values.PriceList.ToUpper();
                await this.fortnox_importer.AddPriceList(this.default_values.PriceList);
            }

            // Upsert currency rates
            //DoxservrResponse<FixerRates> dr_fixer_rates = await this.fixer_client.UpdateCurrencyRates(directory);
            //if(dr_fixer_rates.model != null)
            //{
            //    await this.fortnox_importer.UpsertCurrencies(dr_fixer_rates.model);
            //}

            // Get email senders
            EmailSendersRoot email_senders = null;
            if(this.default_values.OnlyAllowTrustedSenders == true)
            {
                email_senders = await this.fortnox_importer.GetTrustedEmailSenders();
            }

            // Get downloaded metadata files
            string[] metadata_files = System.IO.Directory.GetFiles(directory + "\\Files\\Meta\\");

            // Loop metadata files
            foreach(string meta_path in metadata_files)
            {
                // Metadata
                FileDocument post = null;

                try
                {
                    // Get the meta data
                    string meta_data = System.IO.File.ReadAllText(meta_path, Encoding.UTF8);

                    // Make sure that there is meta data
                    if (string.IsNullOrEmpty(meta_data) == true)
                    {
                        this.logger.LogError($"File is empty: {meta_path}");
                        continue;
                    }

                    // Get the post
                    post = JsonConvert.DeserializeObject<FileDocument>(meta_data);
                }
                catch (Exception ex)
                {
                    // Log the error
                    this.logger.LogError(ex, $"Deserialize file: {meta_path}", null);
                    continue;
                }

                // Make sure that the post not is null
                if(post == null)
                {
                    // Log the error
                    this.logger.LogError($"Post is null: {meta_path}", null);
                    continue;
                }
                
                // Get the sender
                Party sender = null;
                foreach (Party party in post.parties)
                {
                    if (party.is_sender == 1)
                    {
                        sender = party;
                        break;
                    }
                }

                // Check if we only should allow trusted senders
                if(this.default_values.OnlyAllowTrustedSenders == true)
                {
                    // Check if the sender is a trusted sender
                    bool trusted = false;

                    foreach(EmailSender email_sender in email_senders.EmailSenders.TrustedSenders)
                    {
                        if(email_sender.Email == sender.email)
                        {
                            trusted = true;
                            break;
                        }
                    }

                    // Check if the sender is trusted
                    if(trusted == false)
                    {
                        // Log the error
                        this.logger.LogError($"{sender.email} is not trusted, add the email to the list of trusted email addresses in Fortnox (Inställningar/Arkivplats).");
                        continue;
                    }
                }

                // Get the file path
                string file_path = directory + "\\Files\\" + post.id + CommonTools.GetExtensions(post.filename);

                // Make sure that the file exists
                if(System.IO.File.Exists(file_path) == false)
                {
                    // Log the error
                    this.logger.LogError($"File not found: {file_path}.");
                    continue;
                }

                // Document
                AnnytabDoxTrade doc = null;

                try
                {
                    // Get file data
                    string file_data = System.IO.File.ReadAllText(file_path, CommonTools.GetEncoding(post.file_encoding, Encoding.UTF8));

                    // Make sure that there is file data
                    if(string.IsNullOrEmpty(file_data) == true)
                    {
                        // Log the error
                        this.logger.LogError($"File is empty: {file_path}.");
                        continue;
                    }

                    // Get the document
                    doc = JsonConvert.DeserializeObject<AnnytabDoxTrade>(file_data);
                }
                catch(Exception ex)
                {
                    // Log the error
                    this.logger.LogError(ex, $"Deserialize file: {file_path}", null);
                    continue;
                }

                // Make sure that the document not is null
                if (doc == null)
                {
                    // Log the error
                    this.logger.LogError($"Post is null: {file_path}", null);
                    continue;
                }

                // Create an error variable
                bool error = false;

                // Check the document type
                if (doc.document_type == "request_for_quotation")
                {
                    // Log information
                    this.logger.LogInformation($"Starts to import offer {post.id}.json to Fortnox.");

                    // Import as offer
                    OfferRoot offer_root = await this.fortnox_importer.AddOffer(sender.email, doc);

                    if (offer_root == null)
                    {
                        // Log the error
                        error = true;
                        this.logger.LogError($"Offer, {post.id}.json was not imported to Fortnox.");
                    }
                    else
                    {
                        // Log information
                        this.logger.LogInformation($"Offer, {post.id}.json was imported to Fortnox.");
                    }
                }
                else if (doc.document_type == "quotation")
                {
                    // Log information
                    this.logger.LogInformation($"Quotation {post.id}.json is not imported to Fortnox.");
                }
                else if (doc.document_type == "order")
                {
                    // Log information
                    this.logger.LogInformation($"Starts to import order {post.id}.json to Fortnox.");

                    // Import as order
                    OrderRoot order_root = await this.fortnox_importer.AddOrder(sender.email, doc);

                    if (order_root == null)
                    {
                        // Log the error
                        error = true;
                        this.logger.LogError($"Order, {post.id}.json was not imported to Fortnox.");
                    }
                    else
                    {
                        // Log information
                        this.logger.LogInformation($"Order, {post.id}.json was imported to Fortnox.");
                    }
                }
                else if (doc.document_type == "order_confirmation")
                {
                    // Log information
                    this.logger.LogInformation($"Order confirmation {post.id}.json is not imported to Fortnox.");
                }
                else if (doc.document_type == "invoice")
                {
                    // Log information
                    this.logger.LogInformation($"Starts to import supplier invoice {post.id}.json to Fortnox.");

                    // Import as supplier invoice
                    SupplierInvoiceRoot invoice_root = await this.fortnox_importer.AddSupplierInvoice(sender.email, doc);

                    if (invoice_root == null)
                    {
                        // Log the error
                        error = true;
                        this.logger.LogError($"Supplier invoice, {post.id}.json was not imported to Fortnox.");
                    }
                    else
                    {
                        // Log information
                        this.logger.LogInformation($"Supplier invoice, {post.id}.json was imported to Fortnox.");
                    }
                }
                else if (doc.document_type == "credit_invoice")
                {
                    // Log information
                    this.logger.LogInformation($"Starts to import supplier credit invoice {post.id}.json to Fortnox.");

                    // Import as supplier credit invoice
                    SupplierInvoiceRoot invoice_root = await this.fortnox_importer.AddSupplierInvoice(sender.email, doc);

                    if (invoice_root == null)
                    {
                        // Log the error
                        error = true;
                        this.logger.LogError($"Supplier credit invoice, {post.id}.json was not imported to Fortnox.");
                    }
                    else
                    {
                        // Log information
                        this.logger.LogInformation($"Supplier credit invoice, {post.id}.json was imported to Fortnox.");
                    }
                }

                // Move files if no error was encountered
                if(error == false)
                {
                    // Create destination paths
                    string meta_destination = directory + $"\\Files\\Meta\\Imported\\{post.id}.json";
                    string file_destination = directory + $"\\Files\\Imported\\{post.id}.json";

                    try
                    {
                        // Delete destination files if the exists
                        if(System.IO.File.Exists(meta_destination) == true)
                        {
                            System.IO.File.Delete(meta_destination);
                        }
                        if(System.IO.File.Exists(file_destination) == true)
                        {
                            System.IO.File.Delete(file_destination);
                        }

                        // Move files
                        System.IO.Directory.Move(meta_path, meta_destination);
                        System.IO.Directory.Move(file_path, file_destination);
                    }
                    catch (Exception ex)
                    {
                        // Log the exception
                        this.logger.LogError(ex, "Moving files", null);
                    }
                }
            }

            // Log the end
            this.logger.LogInformation("END: Importing documents to Fortnox!");

        } // End of the RunImport method
Exemple #9
0
        public void ReadFromDisk()
        {
            // Create a file path
            string directory = "C:\\DATA\\home\\AnnytabDoxStandards";

            // Variables
            AnnytabDoxMeta meta = null;
            byte[] file_array = null;

            // Get all files
            string[] files = System.IO.Directory.GetFiles(directory + "\\Open");

            // Loop files
            foreach (string path in files)
            {
                // Create and use an archive
                using (ZipArchive archive = ZipFile.OpenRead(path))
                {
                    // Loop files in zip
                    foreach (ZipArchiveEntry entry in archive.Entries)
                    {
                        // Check if a file is meta or file
                        if (entry.FullName.StartsWith("meta", StringComparison.OrdinalIgnoreCase))
                        {
                            using (MemoryStream stream = new MemoryStream())
                            {
                                entry.Open().CopyTo(stream);
                                byte[] array = stream.ToArray();
                                meta = JsonConvert.DeserializeObject<AnnytabDoxMeta>(Encoding.UTF8.GetString(array, 0, array.Length));
                            }
                        }
                        else
                        {
                            using (MemoryStream stream = new MemoryStream())
                            {
                                entry.Open().CopyTo(stream);
                                file_array = stream.ToArray();
                            }
                        }
                    }

                    // Log standard name
                    this.logger.LogInformation($"Fetching: {meta.standard_name} from open folder.", null);

                    // Get file contents depending on standard name
                    if (meta.standard_name.Equals("Annytab Dox Trade v1", StringComparison.OrdinalIgnoreCase))
                    {
                        AnnytabDoxTrade doc = JsonConvert.DeserializeObject<AnnytabDoxTrade>(Encoding.UTF8.GetString(file_array, 0, file_array.Length));
                    }
                    else if (meta.standard_name.Equals("Annytab Dox Contract v1", StringComparison.OrdinalIgnoreCase))
                    {
                        AnnytabDoxContract doc = JsonConvert.DeserializeObject<AnnytabDoxContract>(Encoding.UTF8.GetString(file_array, 0, file_array.Length));
                    }
                    else if (meta.standard_name.Equals("Annytab Dox Drive Log v1", StringComparison.OrdinalIgnoreCase))
                    {
                        AnnytabDoxDriveLog doc = JsonConvert.DeserializeObject<AnnytabDoxDriveLog>(Encoding.UTF8.GetString(file_array, 0, file_array.Length));
                    }
                    else if (meta.standard_name.Equals("Annytab Dox Travel Expense Claim v1", StringComparison.OrdinalIgnoreCase))
                    {
                        AnnytabDoxTravelExpenseClaim doc = JsonConvert.DeserializeObject<AnnytabDoxTravelExpenseClaim>(Encoding.UTF8.GetString(file_array, 0, file_array.Length));
                    }
                }

                // Move file from open to closed
                System.IO.Directory.Move(path, directory + "\\Closed\\" + Path.GetFileName(path));
            }

        } // End of the ReadFromDisk method
Exemple #10
0
        } // End of the CreatePurchaseOrder method

        /// <summary>
        /// Create a invoice
        /// </summary>
        private async Task<AnnytabDoxTrade> CreateInvoice(CompanySettingsRoot company, InvoiceRoot root, CustomerRoot customer_root)
        {
            // Create a Annytab Dox Trade document
            AnnytabDoxTrade post = new AnnytabDoxTrade();
            post.id = root.Invoice.DocumentNumber;
            post.document_type = root.Invoice.Credit == true ? "credit_invoice" : "invoice";
            post.payment_reference = string.IsNullOrEmpty(root.Invoice.OCR) == false ? root.Invoice.OCR : root.Invoice.DocumentNumber;
            post.issue_date = root.Invoice.InvoiceDate;
            post.due_date = root.Invoice.DueDate;
            post.delivery_date = root.Invoice.DeliveryDate;
            post.seller_references = new Dictionary<string, string>();
            post.seller_references.Add("quotation_id", root.Invoice.OfferReference);
            post.seller_references.Add("order_id", root.Invoice.OrderReference);
            post.seller_references.Add("invoice_id", root.Invoice.InvoiceReference);
            post.buyer_references = new Dictionary<string, string>();
            post.buyer_references.Add("customer_id", root.Invoice.CustomerNumber);
            post.buyer_references.Add("order_id", root.Invoice.YourOrderNumber);
            post.terms_of_delivery = root.Invoice.TermsOfDelivery;
            post.terms_of_payment = root.Invoice.TermsOfPayment;
            post.mode_of_delivery = root.Invoice.WayOfDelivery;
            post.total_weight_kg = 0M;
            post.penalty_interest = this.default_values.PenaltyInterest;
            post.currency_code = root.Invoice.Currency;
            post.vat_country_code = company.CompanySettings.CountryCode;
            post.comment = root.Invoice.Remarks;
            post.seller_information = GetCompanyParty(company, root.Invoice.OurReference);
            post.buyer_information = new PartyInformation
            {
                person_id = root.Invoice.OrganisationNumber,
                person_name = root.Invoice.CustomerName,
                address_line_1 = root.Invoice.Address1,
                address_line_2 = root.Invoice.Address2,
                postcode = root.Invoice.ZipCode,
                city_name = root.Invoice.City,
                country_name = root.Invoice.Country,
                contact_name = root.Invoice.YourReference,
                phone_number = root.Invoice.Phone1,
                email = customer_root.Customer.Email
            };
            post.delivery_information = new PartyInformation
            {
                person_name = root.Invoice.DeliveryName,
                address_line_1 = root.Invoice.DeliveryAddress1,
                address_line_2 = root.Invoice.DeliveryAddress2,
                postcode = root.Invoice.DeliveryZipCode,
                city_name = root.Invoice.DeliveryCity,
                country_name = root.Invoice.DeliveryCountry
            };
            post.payment_options = GetPaymentOptions(company);
            post.product_rows = new List<ProductRow>();
            foreach (InvoiceRow row in root.Invoice.InvoiceRows)
            {
                // Get the article
                FortnoxResponse<ArticleRoot> fr_article = await this.nox_client.Get<ArticleRoot>($"articles/{row.ArticleNumber}");

                // Make sure that article root and article not is null
                if (fr_article.model == null || fr_article.model.Article == null)
                {
                    fr_article.model = new ArticleRoot { Article = new Article() };
                }

                // Add to the total weight
                post.total_weight_kg += fr_article.model.Article.Weight != null ? (fr_article.model.Article.Weight * row.DeliveredQuantity) / 1000M : 0;

                // Calculate the price
                decimal? price = root.Invoice.VATIncluded == true ? row.Price / ((100 + row.VAT) / 100) : row.Price;
                if (row.Discount > 0M && row.DiscountType == "AMOUNT")
                {
                    if (root.Invoice.VATIncluded == true)
                    {
                        decimal? discount = row.Discount / ((100 + row.VAT) / 100);
                        price = price - (discount / row.DeliveredQuantity);
                    }
                    else
                    {
                        price = price - (row.Discount / row.DeliveredQuantity);
                    }
                }
                else if (row.Discount > 0M && row.DiscountType == "PERCENT")
                {
                    price = price - (price * (row.Discount / 100));
                }

                // Add a product row
                post.product_rows.Add(new ProductRow
                {
                    product_code = fr_article.model.Article.ArticleNumber,
                    manufacturer_code = fr_article.model.Article.ManufacturerArticleNumber,
                    gtin = fr_article.model.Article.EAN,
                    product_name = row.Description,
                    vat_rate = row.VAT / 100,
                    quantity = row.DeliveredQuantity,
                    unit_code = row.Unit,
                    unit_price = price,
                    subrows = null
                });
            }
            decimal? invoice_fee = AddInvoiceFee(root.Invoice.VATIncluded, root.Invoice.AdministrationFee, root.Invoice.AdministrationFeeVAT, post.product_rows, root.Invoice.Language);
            decimal? freight_fee = AddFreight(root.Invoice.VATIncluded, root.Invoice.Freight, root.Invoice.FreightVAT, post.product_rows, root.Invoice.Language);
            post.vat_specification = CommonTools.GetVatSpecification(post.product_rows);
            post.subtotal = root.Invoice.Net + invoice_fee + freight_fee;
            post.vat_total = root.Invoice.TotalVAT;
            post.rounding = root.Invoice.RoundOff;
            post.total = root.Invoice.Total;
            post.paid_amount = root.Invoice.TotalToPay - root.Invoice.Balance;
            post.balance_due = root.Invoice.Balance;

            // Return the post
            return post;

        } // End of the CreateInvoice method
Exemple #11
0
        } // End of the CreateOrderConfirmation method

        /// <summary>
        /// Create a purchase order
        /// </summary>
        private AnnytabDoxTrade CreatePurchaseOrder(CompanySettingsRoot company, OrderRoot root, SupplierRoot supplier_root, IList<ProductRow> product_rows, decimal? total_weight)
        {
            // Calculate totals
            decimal? net_sum = 0;
            decimal? vat_sum = 0;
            foreach (ProductRow row in product_rows)
            {
                net_sum += row.unit_price * row.quantity;
                vat_sum += row.unit_price * row.quantity * row.vat_rate;
            }

            // Create a Annytab Dox Trade document
            AnnytabDoxTrade post = new AnnytabDoxTrade();
            post.id = root.Order.DocumentNumber;
            post.document_type = "order";
            post.issue_date = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.delivery_date = root.Order.DeliveryDate;
            post.seller_references = new Dictionary<string, string>();
            post.seller_references.Add("supplier_id", supplier_root.Supplier.SupplierNumber);
            post.buyer_references = new Dictionary<string, string>();
            post.buyer_references.Add("customer_id", supplier_root.Supplier.OurCustomerNumber);
            post.terms_of_delivery = root.Order.TermsOfDelivery;
            post.terms_of_payment = supplier_root.Supplier.TermsOfPayment;
            post.mode_of_delivery = root.Order.WayOfDelivery;
            post.total_weight_kg = total_weight;
            post.currency_code = supplier_root.Supplier.Currency;
            post.comment = root.Order.Remarks;
            post.seller_information = new PartyInformation
            {
                person_id = supplier_root.Supplier.OrganisationNumber,
                person_name = supplier_root.Supplier.Name,
                address_line_1 = supplier_root.Supplier.Address1,
                address_line_2 = supplier_root.Supplier.Address2,
                postcode = supplier_root.Supplier.ZipCode,
                city_name = supplier_root.Supplier.City,
                country_name = supplier_root.Supplier.Country,
                country_code = supplier_root.Supplier.CountryCode,
                contact_name = supplier_root.Supplier.YourReference,
                phone_number = supplier_root.Supplier.Phone1,
                email = supplier_root.Supplier.Email,
                vat_number = supplier_root.Supplier.VATNumber
            };
            post.buyer_information = GetCompanyParty(company, supplier_root.Supplier.OurReference);
            post.delivery_information = new PartyInformation
            {
                person_name = root.Order.DeliveryName,
                address_line_1 = root.Order.DeliveryAddress1,
                address_line_2 = root.Order.DeliveryAddress2,
                postcode = root.Order.DeliveryZipCode,
                city_name = root.Order.DeliveryCity,
                country_name = root.Order.DeliveryCountry
            };
            post.product_rows = product_rows;
            post.subtotal = net_sum;
            post.vat_total = vat_sum;
            post.rounding = 0M;
            post.total = net_sum + vat_sum;

            // Return the post
            return post;

        } // End of the CreatePurchaseOrder method
Exemple #12
0
        } // End of the GetOrders method

        /// <summary>
        /// Get an order to export
        /// </summary>
        public async Task<IList<AnnytabDoxTradeRoot>> GetOrder(string id)
        {
            // Get data
            Dictionary<string, string> labels = await GetLabels();
            CompanySettingsRoot company = await GetCompanySettings();

            // Make sure that company and company.Settings not is null
            if (company == null || company.CompanySettings == null)
            {
                this.logger.LogError($"GetOrder: {id}, Could not find any company settings.");
                return null;
            }

            // Get the order
            FortnoxResponse<OrderRoot> fr = await this.nox_client.Get<OrderRoot>($"orders/{id}");

            // Return if model or model.Order is null
            if (fr.model == null || fr.model.Order == null)
            {
                // Log the error and return null
                this.logger.LogError(fr.error);
                return null;
            }

            // Check if the order should be exported
            bool export_order = false;
            bool export_purchase_orders = false;
            foreach (Label label in fr.model.Order.Labels)
            {
                if (labels.ContainsKey(label.Id) && labels[label.Id] == "a-dox-trade-v1")
                {
                    // Export the order
                    export_order = true;
                }
                else if (labels.ContainsKey(label.Id) && labels[label.Id] == "a-dox-trade-v1-po")
                {
                    // Export the purchase order
                    export_purchase_orders = true;
                }
            }

            // Return null if nothing should be exported
            if (export_order == false && export_purchase_orders == false)
            {
                return null;
            }

            // Get the customer
            FortnoxResponse<CustomerRoot> fr_customer = await this.nox_client.Get<CustomerRoot>($"customers/{fr.model.Order.CustomerNumber}");

            // Return if model or model.Customer is null
            if (fr_customer.model == null || fr_customer.model.Customer == null)
            {
                // Log the error and return null
                this.logger.LogError(fr_customer.error);
                return null;
            }

            // Create the list to return
            IList<AnnytabDoxTradeRoot> posts = new List<AnnytabDoxTradeRoot>();

            // Create an order confirmation
            if(export_order == true)
            {
                AnnytabDoxTrade post = await CreateOrderConfirmation(company, fr.model, fr_customer.model);
                posts.Add(new AnnytabDoxTradeRoot { document_type = post.document_type, document = post, email = fr_customer.model.Customer.Email, language_code = fr.model.Order.Language });
            }

            // Create purchase orders
            if(export_purchase_orders == true)
            {
                // Create variables
                IDictionary<string, SupplierRoot> suppliers = new Dictionary<string, SupplierRoot>();
                IDictionary<string, IList<ProductRow>> supplier_rows = new Dictionary<string, IList<ProductRow>>();
                decimal? total_weight = 0M;

                // Get suppliers
                foreach (OrderRow row in fr.model.Order.OrderRows)
                {
                    // Get the article
                    FortnoxResponse<ArticleRoot> fr_article = await this.nox_client.Get<ArticleRoot>($"articles/{row.ArticleNumber}");

                    // Make sure that the article was found
                    if (fr_article.model != null && fr_article.model.Article != null)
                    {
                        // Get the supplier
                        if(string.IsNullOrEmpty(fr_article.model.Article.SupplierNumber) == false)
                        {
                            // Check if the supplier exists
                            if (suppliers.ContainsKey(fr_article.model.Article.SupplierNumber) == false)
                            {
                                // Get the supplier
                                FortnoxResponse<SupplierRoot> fr_supplier = await this.nox_client.Get<SupplierRoot>($"suppliers/{fr_article.model.Article.SupplierNumber}");

                                // Add the supplier
                                if(fr_supplier != null && fr_supplier.model != null)
                                {
                                    // Add the supplier
                                    suppliers.Add(fr_article.model.Article.SupplierNumber, fr_supplier.model);
                                }
                                else
                                {
                                    this.logger.LogError(fr_supplier.error);
                                }
                            }

                            // Check if the supplier has order rows
                            if(supplier_rows.ContainsKey(fr_article.model.Article.SupplierNumber) == false && suppliers.ContainsKey(fr_article.model.Article.SupplierNumber) == true)
                            {
                                // Add the row
                                supplier_rows.Add(fr_article.model.Article.SupplierNumber, new List<ProductRow>());
                            }

                            // Add to the total weight
                            total_weight += fr_article.model.Article.Weight != null ? (fr_article.model.Article.Weight * row.OrderedQuantity) / 1000M : 0;

                            // Add the row
                            supplier_rows[fr_article.model.Article.SupplierNumber].Add(new ProductRow
                            {
                                product_code = fr_article.model.Article.ArticleNumber,
                                manufacturer_code = fr_article.model.Article.ManufacturerArticleNumber,
                                gtin = fr_article.model.Article.EAN,
                                product_name = fr_article.model.Article.Description,
                                vat_rate = row.VAT / 100,
                                quantity = row.OrderedQuantity,
                                unit_code = row.Unit,
                                unit_price = fr_article.model.Article.PurchasePrice, // 0M
                                subrows = null
                            });
                        }
                    }
                    else
                    {
                        // Log the error
                        this.logger.LogError(fr_article.error);
                    }
                }

                // Create a purchase order to each supplier
                foreach(KeyValuePair<string, SupplierRoot> entry in suppliers)
                {
                    // Create a purchase order
                    AnnytabDoxTrade post = CreatePurchaseOrder(company, fr.model, entry.Value, supplier_rows[entry.Key], total_weight);

                    // Add the document
                    posts.Add(new AnnytabDoxTradeRoot { document_type = "purchase_order_" + entry.Value.Supplier.SupplierNumber, document = post,
                        email = entry.Value.Supplier.Email, language_code = "en" });
                }
            }

            // Return the list with posts
            return posts;

        } // End of the GetOrder method
        public void CreateCreditInvoice()
        {
            // Make sure that the directory exists
            string directory = Directory.GetCurrentDirectory() + "\\CreditInvoices";
            if (Directory.Exists(directory) == false)
            {
                Directory.CreateDirectory(directory);
            }

            // Create a request for quotation
            AnnytabDoxTrade post = new AnnytabDoxTrade();
            post.id = Guid.NewGuid().ToString();
            post.document_type = "credit_invoice";
            post.payment_reference = "D-1514";
            post.issue_date = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.due_date = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.delivery_date = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.seller_references = new Dictionary<string, string>();
            post.seller_references.Add("supplier_id", "test");
            //post.seller_references.Add("quotation_id", "500");
            //post.seller_references.Add("order_id", "");
            //post.seller_references.Add("invoice_id", "");
            post.buyer_references = new Dictionary<string, string>();
            post.buyer_references.Add("customer_id", "F557882");
            //post.buyer_references.Add("request_for_quotation_id", "784da920-a5e2-4ad0-afea-6961b9885554");
            //post.buyer_references.Add("order_id", "");
            post.terms_of_delivery = "CIF";
            post.terms_of_payment = "Net 30";
            post.mode_of_delivery = "UPS";
            post.total_weight_kg = 10M;
            post.penalty_interest = 0.20M;
            post.currency_code = "USD";
            //post.vat_country_code = invoice.vat_country_code;
            //post.vat_state_code = invoice.vat_state_code;
            post.comment = "Vänligen ange fakturanummer vid betalning.";
            post.seller_information = new PartyInformation()
            {
                person_id = "778899-7447",
                person_name = "Supplier Inc",
                address_line_1 = "Abroad way 55",
                //address_line_2 = "",
                //address_line_3 = "",
                postcode = "CA90009",
                city_name = "San Francisco",
                country_name = "USA",
                country_code = "US",
                state_code = "CA",
                contact_name = "Brenda Meatloaf",
                phone_number = "+8800004545",
                email = "*****@*****.**",
                vat_number = "778899-7447"
            };
            post.buyer_information = new PartyInformation
            {
                person_id = "556864-2747",
                person_name = "A Name Not Yet Taken AB",
                address_line_1 = "Skonertgatan 12",
                address_line_2 = "Kronobränneriet",
                address_line_3 = "",
                postcode = "30238",
                city_name = "Halmstad",
                country_name = "Sweden",
                country_code = "SE",
                state_code = "",
                contact_name = "Fredrik Stigsson",
                phone_number = "",
                email = "*****@*****.**",
                vat_number = "SE556864274701"
            };
            post.payment_options = new List<PaymentOption>
            {
                new PaymentOption
                {
                    name = "IBAN",
                    account_reference = "SE4680000816959239073274",
                    bank_identifier_code = "SWEDSESS",
                    bank_name = "Swedbank AB",
                    bank_country_code = "SE"
                },
                new PaymentOption
                {
                    name = "BG",
                    account_reference = "7893514",
                    bank_identifier_code = "BGABSESS",
                    bank_name = "Bankgirocentralen BGC AB",
                    bank_country_code = "SE"
                },
                new PaymentOption
                {
                    name = "SWISH",
                    account_reference = "1235370366",
                    bank_identifier_code = "SWEDSESS",
                    bank_name = "Swedbank AB",
                    bank_country_code = "SE"
                },
                new PaymentOption
                {
                    name = "PAYPAL.ME",
                    account_reference = "https://www.paypal.me/annytab",
                    bank_identifier_code = "",
                    bank_name = "PayPal",
                    bank_country_code = "US"
                }
            };
            post.product_rows = new List<ProductRow>
            {
                new ProductRow
                {
                    product_code = "US-law",
                    //manufacturer_code = "T2223445566",
                    //gtin = "888090909",
                    product_name = "Law consulting package",
                    vat_rate = 0M,
                    quantity = -60M,
                    unit_code = "h",
                    unit_price = 200M,
                    subrows = new List<ProductRow>
                    {
                        new ProductRow
                        {
                            product_code = "USLAW-1",
                            //manufacturer_code = "T2223445567",
                            //gtin = "",
                            product_name = "Trade",
                            vat_rate = 0M,
                            quantity = -20M,
                            unit_code = "h",
                            unit_price = 0M,
                            subrows = null
                        },
                        new ProductRow
                        {
                            product_code = "USLAW-1",
                            //manufacturer_code = "T2223445568",
                            //gtin = "",
                            product_name = "Real estate",
                            vat_rate = 0M,
                            quantity = -4M,
                            unit_code = "h",
                            unit_price = 0M,
                            subrows = null
                        }
                    }
                }
            };
            post.vat_specification = new List<VatSpecification>
            {
                new VatSpecification
                {
                    tax_rate = 0.25M,
                    taxable_amount = 0M,
                    tax_amount = 0M,
                }
            };
            post.subtotal = -12000M;
            post.vat_total = 0M;
            post.rounding = 0M;
            post.total = -12000M;
            post.paid_amount = 0M;
            post.balance_due = -12000M;

            // Write the  to a file
            File.WriteAllText(directory + "\\" + post.id + ".json", JsonConvert.SerializeObject(post));

        } // End of the CreateCreditInvoice method
        public void CreateOrder()
        {
            // Make sure that the directory exists
            string directory = Directory.GetCurrentDirectory() + "\\Orders";
            if (Directory.Exists(directory) == false)
            {
                Directory.CreateDirectory(directory);
            }

            // Create a request for quotation
            AnnytabDoxTrade post = new AnnytabDoxTrade();
            post.id = Guid.NewGuid().ToString();
            post.document_type = "order";
            post.payment_reference = "D-5001";
            post.issue_date = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            //post.due_date = invoice.invoice_date.AddDays(15).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.delivery_date = DateTime.Now.AddDays(60).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.seller_references = new Dictionary<string, string>();
            //post.seller_references.Add("supplier_id", "");
            post.seller_references.Add("quotation_id", "500");
            //post.seller_references.Add("order_id", "");
            //post.seller_references.Add("invoice_id", "");
            post.buyer_references = new Dictionary<string, string>();
            //post.buyer_references.Add("customer_id", "1");
            post.buyer_references.Add("request_for_quotation_id", "784da920-a5e2-4ad0-afea-6961b9885554");
            post.buyer_references.Add("order_id", "");
            //post.terms_of_delivery = "EXW";
            post.terms_of_payment = "Net 20";
            //post.mode_of_delivery = "WEB";
            post.total_weight_kg = 10M;
            //post.penalty_interest = 0.10M;
            post.currency_code = "SEK";
            //post.vat_country_code = invoice.vat_country_code;
            //post.vat_state_code = invoice.vat_state_code;
            post.comment = "Jag skickar en beställning enligt Offert: 5000. Hoppas att priserna är samma";
            post.seller_information = new PartyInformation()
            {
                person_id = "556864-2747",
                person_name = "A Name Not Yet Taken AB",
                address_line_1 = "Skonertgatan 12",
                address_line_2 = "Kronobränneriet",
                address_line_3 = "",
                postcode = "30238",
                city_name = "Halmstad",
                country_name = "Sweden",
                country_code = "SE",
                state_code = "",
                contact_name = "Fredrik Stigsson",
                phone_number = "",
                email = "*****@*****.**",
                vat_number = "SE556864274701"
            };
            post.buyer_information = new PartyInformation
            {
                person_id = "445566-8877",
                person_name = "Kundnamn",
                address_line_1 = "Address rad 1",
                address_line_2 = "Address rad 2",
                //address_line_3 = "",
                postcode = "Postkod",
                city_name = "Stad",
                country_name = "Land",
                country_code = "SE",
                //state_code = "",
                contact_name = "Kontaktnamn",
                phone_number = "Telefonnummer",
                email = "*****@*****.**",
                vat_number = "VAT-nummer"
            };
            //post.payment_options = new List<PaymentOption>
            //{
            //    new PaymentOption
            //    {
            //        name = "IBAN",
            //        account_reference = "SE4680000816959239073274",
            //        bank_identifier_code = "SWEDSESS",
            //        bank_name = "Swedbank AB",
            //        bank_country_code = "SE"
            //    },
            //    new PaymentOption
            //    {
            //        name = "BG",
            //        account_reference = "7893514",
            //        bank_identifier_code = "BGABSESS",
            //        bank_name = "Bankgirocentralen BGC AB",
            //        bank_country_code = "SE"
            //    },
            //    new PaymentOption
            //    {
            //        name = "SWISH",
            //        account_reference = "1235370366",
            //        bank_identifier_code = "SWEDSESS",
            //        bank_name = "Swedbank AB",
            //        bank_country_code = "SE"
            //    },
            //    new PaymentOption
            //    {
            //        name = "PAYPAL.ME",
            //        account_reference = "https://www.paypal.me/annytab",
            //        bank_identifier_code = "",
            //        bank_name = "PayPal",
            //        bank_country_code = "US"
            //    }
            //};
            post.product_rows = new List<ProductRow>
            {
                new ProductRow
                {
                    //product_code = "GiB",
                    //manufacturer_code = "GiB",
                    //gtin = "",
                    product_name = "Gibibytes",
                    vat_rate = 0.25M,
                    quantity = 5M,
                    unit_code = "PIEC",
                    unit_price = 100.45M,
                    subrows = new List<ProductRow>()
                },
                new ProductRow
                {
                    //product_code = "XX-1450",
                    //manufacturer_code = "T2223445566",
                    gtin = "00000047",
                    product_name = "Verktygslåda",
                    vat_rate = 0.25M,
                    quantity = 3.55M,
                    unit_code = "st",
                    unit_price = 5999.77M,
                    subrows = null         
                }
            };
            //post.vat_specification = new List<VatSpecification>
            //{
            //    new VatSpecification
            //    {
            //        tax_rate = 0.25M,
            //        taxable_amount = 0M,
            //        tax_amount = 0M,
            //    }
            //};
            post.subtotal = 10000M;
            post.vat_total = 2500M;
            post.rounding = 0M;
            post.total = 12500M;
            post.paid_amount = 0M;
            post.balance_due = 12500M;

            // Write the  to a file
            File.WriteAllText(directory + "\\" + post.id + ".json", JsonConvert.SerializeObject(post));

        } // End of the CreateOrder method
        public void CreateRequestForQuotation()
        {
            // Make sure that the directory exists
            string directory = Directory.GetCurrentDirectory() + "\\Offers";
            if(Directory.Exists(directory) == false)
            {
                Directory.CreateDirectory(directory);
            }

            // Create a request for quotation
            AnnytabDoxTrade post = new AnnytabDoxTrade();
            post.id = Guid.NewGuid().ToString();
            post.document_type = "request_for_quotation";
            post.payment_reference = "T2";
            post.issue_date = DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            //post.due_date = invoice.invoice_date.AddDays(15).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.delivery_date = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            post.offer_expires_date = DateTime.Now.AddDays(90).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            //post.seller_references = new Dictionary<string, string>();
            //post.seller_references.Add("supplier_id", "");
            //post.seller_references.Add("quotation_id", "");
            //post.seller_references.Add("order_id", "");
            //post.seller_references.Add("invoice_id", "");
            //post.buyer_references = new Dictionary<string, string>();
            //post.buyer_references.Add("customer_id", "1");
            //post.buyer_references.Add("request_for_quotation_id", post.id);
            //post.buyer_references.Add("order_id", "");
            post.terms_of_delivery = "EXW";
            post.terms_of_payment = "Net 30";
            post.mode_of_delivery = "RRR";
            post.total_weight_kg = 20M;
            //post.penalty_interest = 0.10M;
            //post.currency_code = invoice.currency_code;
            //post.vat_country_code = invoice.vat_country_code;
            //post.vat_state_code = invoice.vat_state_code;
            post.comment = "Jag önskar att få priser för dessa produkter.";
            post.seller_information = new PartyInformation()
            {
                person_id = "556864-2747",
                person_name = "A Name Not Yet Taken AB",
                address_line_1 = "Skonertgatan 12",
                address_line_2 = "Kronobränneriet",
                address_line_3 = "",
                postcode = "30238",
                city_name = "Halmstad",
                country_name = "Sweden",
                country_code = "SE",
                state_code = "",
                contact_name = "Fredrik Stigsson",
                phone_number = "",
                email = "*****@*****.**",
                vat_number = "SE556864274701"
            };
            post.buyer_information = new PartyInformation
            {
                person_id = "445566-8877",
                person_name = "Kundnamn",
                address_line_1 = "Address rad 1",
                address_line_2 = "Address rad 2",
                //address_line_3 = "",
                postcode = "Postkod",
                city_name = "Stad",
                country_name = "Land",
                country_code = "SE",
                //state_code = "",
                contact_name = "Kontaktnamn",
                phone_number = "Telefonnummer",
                email = "*****@*****.**",
                vat_number = "VAT-nummer"
            };
            //post.payment_options = new List<PaymentOption>
            //{
            //    new PaymentOption
            //    {
            //        name = "IBAN",
            //        account_reference = "SE4680000816959239073274",
            //        bank_identifier_code = "SWEDSESS",
            //        bank_name = "Swedbank AB",
            //        bank_country_code = "SE"
            //    },
            //    new PaymentOption
            //    {
            //        name = "BG",
            //        account_reference = "7893514",
            //        bank_identifier_code = "BGABSESS",
            //        bank_name = "Bankgirocentralen BGC AB",
            //        bank_country_code = "SE"
            //    },
            //    new PaymentOption
            //    {
            //        name = "SWISH",
            //        account_reference = "1235370366",
            //        bank_identifier_code = "SWEDSESS",
            //        bank_name = "Swedbank AB",
            //        bank_country_code = "SE"
            //    },
            //    new PaymentOption
            //    {
            //        name = "PAYPAL.ME",
            //        account_reference = "https://www.paypal.me/annytab",
            //        bank_identifier_code = "",
            //        bank_name = "PayPal",
            //        bank_country_code = "US"
            //    }
            //};
            post.product_rows = new List<ProductRow>
            {
                //new ProductRow
                //{
                //    //product_code = "P-87945656",
                //    //manufacturer_code = "T2223445566",
                //    //gtin = "",
                //    product_name = "SUPER",
                //    vat_rate = 0.25M,
                //    quantity = 50M,
                //    unit_code = "st",
                //    unit_price = 100.45M,
                //    subrows = new List<ProductRow>
                //    {
                //        new ProductRow
                //        {
                //            //product_code = "P-447",
                //            manufacturer_code = "TG00025",
                //            //gtin = "",
                //            product_name = "Ett",
                //            vat_rate = 0.25M,
                //            quantity = 200M,
                //            unit_code = "st",
                //            unit_price = 0M,
                //            subrows = null
                //        },
                //        new ProductRow
                //        {
                //            //product_code = "P-448",
                //            //manufacturer_code = "T2223445568",
                //            gtin = "00002",
                //            product_name = "Två",
                //            vat_rate = 0.25M,
                //            quantity = 50M,
                //            unit_code = "st",
                //            unit_price = 0M,
                //            subrows = new List<ProductRow>
                //            {
                //                new ProductRow
                //                {
                //                    product_code = "TTT-%%//34",
                //                    //manufacturer_code = "T2223445568",
                //                    //gtin = "00002",
                //                    product_name = "2:1",
                //                    vat_rate = 0.12M,
                //                    quantity = 10M,
                //                    unit_code = "st",
                //                    unit_price = 0M
                //                }
                //            }
                //        }
                //    }
                //},
                new ProductRow
                {
                    product_code = "NEW-00001",
                    manufacturer_code = "GiB",
                    gtin = "",
                    product_name = "Gibibytes",
                    vat_rate = 0.25M,
                    quantity = 5M,
                    unit_code = "PIEC",
                    unit_price = 0M,
                    subrows = new List<ProductRow>()
                },
                new ProductRow
                {
                    product_code = "NEW-00002",
                    manufacturer_code = "",
                    gtin = "",
                    product_name = "Sockar",
                    vat_rate = 0.25M,
                    quantity = 80M,
                    unit_code = "st",
                    unit_price = 10.89M,
                    subrows = new List<ProductRow>()
                }
            };
            //post.vat_specification = new List<VatSpecification>
            //{
            //    new VatSpecification
            //    {
            //        tax_rate = 0.25M,
            //        taxable_amount = 0M,
            //        tax_amount = 0M,
            //    }
            //};
            post.subtotal = 0M;
            post.vat_total = 0M;
            post.rounding = 0M;
            post.total = 0M;
            post.paid_amount = 0M;
            post.balance_due = 0M;

            // Write the  to a file
            File.WriteAllText(directory + "\\" + post.id + ".json", JsonConvert.SerializeObject(post));

        } // End of the CreateRequestForQuotation method