public async Task TestUpdatePost() { // Create a post OfferRoot post = new OfferRoot { Offer = new Offer { CustomerNumber = "11", OfferRows = new List<OfferRow> { new OfferRow { ArticleNumber = "3", Quantity = 50M, Price = 34.45M }, new OfferRow { ArticleNumber = "2", Quantity = 4M } } } }; // Update the post FortnoxResponse<OfferRoot> fr = await config.fortnox_client.Update<OfferRoot>(post, "offers/19"); // Log the error if (fr.model == null) { config.logger.LogError(fr.error); } // Test evaluation Assert.AreNotEqual(null, fr.model); } // End of the TestUpdatePost method
} // End of the GetTrustedEmailSenders method #endregion #region Documents /// <summary> /// Add an offer /// </summary> public async Task<OfferRoot> AddOffer(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 offer rows IList<OfferRow> rows = new List<OfferRow>(); // Add offer rows if(doc.product_rows != null) { await AddOfferRows(doc.product_rows, rows); } // Create an offer OfferRoot root = new OfferRoot { Offer = new Offer { CustomerNumber = customer_root.Customer.CustomerNumber, OfferDate = string.IsNullOrEmpty(doc.issue_date) == false ? doc.issue_date : null, DeliveryDate = string.IsNullOrEmpty(doc.delivery_date) == false ? doc.delivery_date : null, ExpireDate = string.IsNullOrEmpty(doc.offer_expires_date) == false ? doc.offer_expires_date : null, YourReferenceNumber = doc.buyer_references != null && doc.buyer_references.ContainsKey("request_for_quotation_id") ? doc.buyer_references["request_for_quotation_id"] : null, Comments = doc.comment, OfferRows = rows, Currency = doc.currency_code, VATIncluded = false } }; // Add the offer FortnoxResponse<OfferRoot> fr = await this.nox_client.Add<OfferRoot>(root, "offers"); // Log errors if (string.IsNullOrEmpty(fr.error) == false) { this.logger.LogError(fr.error); } // Return the offer return fr.model; } // End of the AddOffer method
} // 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
} // End of the GetInvoice method #endregion #region Helper methods /// <summary> /// Create a quotation /// </summary> private async Task<AnnytabDoxTrade> CreateQuotation(CompanySettingsRoot company, OfferRoot root, CustomerRoot customer_root) { // Create a Annytab Dox Trade document AnnytabDoxTrade post = new AnnytabDoxTrade(); post.id = root.Offer.DocumentNumber; post.document_type = "quotation"; post.issue_date = root.Offer.OfferDate; post.delivery_date = root.Offer.DeliveryDate; post.offer_expires_date = root.Offer.ExpireDate; post.buyer_references = new Dictionary<string, string>(); post.buyer_references.Add("customer_id", root.Offer.CustomerNumber); post.buyer_references.Add("request_for_quotation_id", root.Offer.YourReferenceNumber); post.terms_of_delivery = root.Offer.TermsOfDelivery; post.terms_of_payment = root.Offer.TermsOfPayment; post.mode_of_delivery = root.Offer.WayOfDelivery; post.total_weight_kg = 0M; post.penalty_interest = this.default_values.PenaltyInterest; post.currency_code = root.Offer.Currency; post.vat_country_code = company.CompanySettings.CountryCode; post.comment = root.Offer.Remarks; post.seller_information = GetCompanyParty(company, root.Offer.OurReference); post.buyer_information = new PartyInformation { person_id = root.Offer.OrganisationNumber, person_name = root.Offer.CustomerName, address_line_1 = root.Offer.Address1, address_line_2 = root.Offer.Address2, postcode = root.Offer.ZipCode, city_name = root.Offer.City, country_name = root.Offer.Country, contact_name = root.Offer.YourReference, phone_number = root.Offer.Phone1, email = customer_root.Customer.Email }; post.delivery_information = new PartyInformation { person_name = root.Offer.DeliveryName, address_line_1 = root.Offer.DeliveryAddress1, address_line_2 = root.Offer.DeliveryAddress2, postcode = root.Offer.DeliveryZipCode, city_name = root.Offer.DeliveryCity, country_name = root.Offer.DeliveryCountry, }; post.payment_options = GetPaymentOptions(company); post.product_rows = new List<ProductRow>(); foreach (OfferRow row in root.Offer.OfferRows) { // 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.Quantity)/ 1000M : 0; // Calculate the price decimal? price = root.Offer.VATIncluded == true ? row.Price / ((100 + row.VAT) / 100) : row.Price; if (row.Discount > 0M && row.DiscountType == "AMOUNT") { if (root.Offer.VATIncluded == true) { decimal? discount = row.Discount / ((100 + row.VAT) / 100); price = price - (discount / row.Quantity); } else { price = price - (row.Discount / row.Quantity); } } 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.Quantity, unit_code = row.Unit, unit_price = price, subrows = null }); } decimal? invoice_fee = AddInvoiceFee(root.Offer.VATIncluded, root.Offer.AdministrationFee, root.Offer.AdministrationFeeVAT, post.product_rows, root.Offer.Language); decimal? freight_fee = AddFreight(root.Offer.VATIncluded, root.Offer.Freight, root.Offer.FreightVAT, post.product_rows, root.Offer.Language); post.vat_specification = CommonTools.GetVatSpecification(post.product_rows); post.subtotal = root.Offer.Net + invoice_fee + freight_fee; post.vat_total = root.Offer.TotalVAT; post.rounding = root.Offer.RoundOff; post.total = root.Offer.Total; // Return the post return post; } // End of the CreateQuotation method