public Order GetOrder(long key) { Order order; try { order = (from item in OrderRoot.Elements() where long.Parse(item.Element("OrderKey").Value) == key select new Order() { OrderKey = long.Parse(item.Element("OrderKey").Value), GuestRequestKey = long.Parse(item.Element("GuestRequestKey").Value), HostingUnitKey = long.Parse(item.Element("HostingUnitKey").Value), Status = getEnumFromString <OrderStatusEnum>((item.Element("Status").Value)), isClosed = bool.Parse(item.Element("isClosed").Value), isSendMail = bool.Parse(item.Element("isSendMail").Value), CreateDate = DateTime.Parse(item.Element("CreateDate").Value), OrderDate = DateTime.Parse(item.Element("OrderDate").Value), }).FirstOrDefault(); } catch { order = null; } if (order == null) { throw new Exception("מספר הזמנה לא נכון"); } return(order); }
public Task <Result <OrderRoot> > PlaceNewOrder(Guid customerId) => _repository .Get <Contractor>(customerId) .OnSuccess(customer => SnapBuyer(customer)) .OnSuccess(buyerSnapshot => OrderRoot.Create(Guid.NewGuid(), buyerSnapshot, _systemTime.Now)) .OnSuccess(orderRoot => _unitOfWork.Add(orderRoot)) .OnSuccess(orderId => _unitOfWork.Compleate());
public IEnumerable <Order> getListOrders(Func <Order, bool> predicate = null) { IEnumerable <Order> orders = from item in OrderRoot.Elements() where GetOrder(long.Parse(item.Element("OrderKey").Value)) != null select GetOrder(long.Parse(item.Element("OrderKey").Value)); if (predicate == null) { return(orders); } return(orders.Where(predicate)); }
public async Task <print.Models.OrderConfirm.RootObject> PlaceOrder(OrderRoot order) { order.items[0].itemSequenceNumber = 1; order.shipments[0].shipmentSequenceNumber = 1; order.items[0].productionDays = 1; var request = JsonConvert.SerializeObject(order); var content = new StringContent(request, Encoding.UTF8, "application/json"); var response = await Client.PostAsync(RequestUrl, content); string result = await response.Content.ReadAsStringAsync(); var deserialized = JsonConvert.DeserializeObject <print.Models.OrderConfirm.RootObject>(result); return(deserialized); }
public void addOrder(Order order) { order.OrderKey = getAndUpdateOrderConfig(); XElement HostingUnitKey = new XElement("HostingUnitKey", order.HostingUnitKey); XElement GuestRequestKey = new XElement("GuestRequestKey", order.GuestRequestKey); XElement OrderKey = new XElement("OrderKey", order.OrderKey); XElement Status = new XElement("Status", order.Status); XElement CreateDate = new XElement("CreateDate", order.CreateDate); XElement OrderDate = new XElement("OrderDate", order.OrderDate); XElement isClosed = new XElement("isClosed", order.isClosed); XElement isSendMail = new XElement("isSendMail", order.isSendMail); OrderRoot.Add(new XElement("Order", HostingUnitKey, GuestRequestKey, OrderKey, Status, CreateDate, OrderDate, isClosed, isSendMail)); OrderRoot.Save(OrderdPath); }
public bool deleteOrder(long key) { XElement OrderElement; try { OrderElement = (from item in OrderRoot.Elements() where int.Parse(item.Element("OrderKey").Value) == key select item).FirstOrDefault(); OrderElement.Remove(); OrderRoot.Save(OrderdPath); return(true); } catch { return(false); } }
public async Task TestAddPost() { // Create a post OrderRoot post = new OrderRoot { Order = new Order { DocumentNumber = "100001", CustomerNumber = "2", OrderRows = new List<OrderRow> { new OrderRow { ArticleNumber = "1", OrderedQuantity = 10M, DeliveredQuantity = 8M, Price = 34.45M, Unit = "st" }, new OrderRow { ArticleNumber = "2", OrderedQuantity = 5M, DeliveredQuantity = 5M, } } } }; // Add the post FortnoxResponse<OrderRoot> fr = await config.fortnox_client.Add<OrderRoot>(post, "orders"); // Log the error if (fr.model == null) { config.logger.LogError(fr.error); } // Test evaluation Assert.AreNotEqual(null, fr.model); } // End of the TestAddPost method
public void updateOrder(Order order) { XElement orderElement = (from item in OrderRoot.Elements() where int.Parse(item.Element("OrderKey").Value) == order.OrderKey select item).FirstOrDefault(); if (orderElement == null) { throw new Exception("ההזמנה לא נמצאה"); } orderElement.Element("OrderKey").Value = order.HostingUnitKey.ToString(); orderElement.Element("CreateDate").Value = order.CreateDate.ToString(); orderElement.Element("GuestRequestKey").Value = order.GuestRequestKey.ToString(); orderElement.Element("isClosed").Value = order.isClosed.ToString(); orderElement.Element("isSendMail").Value = order.isSendMail.ToString(); orderElement.Element("OrderDate").Value = order.OrderDate.ToString(); orderElement.Element("OrderKey").Value = order.OrderKey.ToString(); orderElement.Element("Status").Value = order.Status.ToString(); OrderRoot.Save(OrderdPath); }
} // 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 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 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
} // End of the CreateQuotation method /// <summary> /// Create an order confirmation /// </summary> private async Task<AnnytabDoxTrade> CreateOrderConfirmation(CompanySettingsRoot company, OrderRoot root, CustomerRoot customer_root) { // Create a Annytab Dox Trade document AnnytabDoxTrade post = new AnnytabDoxTrade(); post.id = root.Order.DocumentNumber; post.document_type = "order_confirmation"; post.issue_date = root.Order.OrderDate; post.delivery_date = root.Order.DeliveryDate; post.seller_references = new Dictionary<string, string>(); post.seller_references.Add("quotation_id", root.Order.OfferReference); post.buyer_references = new Dictionary<string, string>(); post.buyer_references.Add("customer_id", root.Order.CustomerNumber); post.buyer_references.Add("order_id", root.Order.YourOrderNumber); post.terms_of_delivery = root.Order.TermsOfDelivery; post.terms_of_payment = root.Order.TermsOfPayment; post.mode_of_delivery = root.Order.WayOfDelivery; post.total_weight_kg = 0M; post.penalty_interest = this.default_values.PenaltyInterest; post.currency_code = root.Order.Currency; post.vat_country_code = company.CompanySettings.CountryCode; post.comment = root.Order.Remarks; post.seller_information = GetCompanyParty(company, root.Order.OurReference); post.buyer_information = new PartyInformation { person_id = root.Order.OrganisationNumber, person_name = root.Order.CustomerName, address_line_1 = root.Order.Address1, address_line_2 = root.Order.Address2, postcode = root.Order.ZipCode, city_name = root.Order.City, country_name = root.Order.Country, contact_name = root.Order.YourReference, phone_number = root.Order.Phone1, email = customer_root.Customer.Email }; 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.payment_options = GetPaymentOptions(company); post.product_rows = new List<ProductRow>(); foreach (OrderRow row in root.Order.OrderRows) { // 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.OrderedQuantity) / 1000M : 0; // Calculate the price decimal? price = root.Order.VATIncluded == true ? row.Price / ((100 + row.VAT) / 100) : row.Price; if (row.Discount > 0M && row.DiscountType == "AMOUNT") { if (root.Order.VATIncluded == true) { decimal? discount = row.Discount / ((100 + row.VAT) / 100); price = price - (discount / row.OrderedQuantity); } else { price = price - (row.Discount / row.OrderedQuantity); } } 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.OrderedQuantity, unit_code = row.Unit, unit_price = price, subrows = null }); } decimal? invoice_fee = AddInvoiceFee(root.Order.VATIncluded, root.Order.AdministrationFee, root.Order.AdministrationFeeVAT, post.product_rows, root.Order.Language); decimal? freight_fee = AddFreight(root.Order.VATIncluded, root.Order.Freight, root.Order.FreightVAT, post.product_rows, root.Order.Language); post.vat_specification = CommonTools.GetVatSpecification(post.product_rows); post.subtotal = root.Order.Net + invoice_fee + freight_fee; post.vat_total = root.Order.TotalVAT; post.rounding = root.Order.RoundOff; post.total = root.Order.Total; // Return the post return post; } // End of the CreateOrderConfirmation method