123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322 |
- using Comal.Classes;
- using InABox.Clients;
- using InABox.Core;
- using InABox.Core.Postable;
- using InABox.Database;
- using InABox.Poster.MYOB;
- using InABox.Scripting;
- using MYOB.AccountRight.SDK.Services.Contact;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using MYOBSupplier = MYOB.AccountRight.SDK.Contracts.Version2.Contact.Supplier;
- namespace PRS.Shared.Posters.MYOB;
- public class SupplierMYOBPosterSettings : MYOBPosterSettings
- {
- public override string DefaultScript(Type TPostable)
- {
- return @"using MYOBSupplier = MYOB.AccountRight.SDK.Contracts.Version2.Contact.Supplier;
- public class Module
- {
- public void BeforePost(IDataModel<Supplier> model)
- {
- // Perform pre-processing
- }
- public void ProcessSupplier(IDataModel<Supplier> model, Supplier supplier, MYOBSupplier myobSupplier)
- {
- // Do extra processing for a supplier; throw an exception to fail this supplier.
- }
- }";
- }
- }
- public class SupplierMYOBAutoRefresher : IAutoRefresher<Supplier>
- {
- public bool ShouldRepost(Supplier supplier)
- {
- var shouldRepost = supplier.HasOriginalValue(x => x.Name)
- || supplier.HasOriginalValue(x => x.Code)
- || supplier.HasOriginalValue(x => x.ABN)
- || supplier.HasOriginalValue(x => x.Email)
- || supplier.HasOriginalValue(x => x.Telephone)
- || supplier.Delivery.HasOriginalValue(x => x.Street)
- || supplier.Delivery.HasOriginalValue(x => x.City)
- || supplier.Delivery.HasOriginalValue(x => x.State)
- || supplier.Delivery.HasOriginalValue(x => x.PostCode)
- || supplier.Postal.HasOriginalValue(x => x.Street)
- || supplier.Postal.HasOriginalValue(x => x.City)
- || supplier.Postal.HasOriginalValue(x => x.State)
- || supplier.Postal.HasOriginalValue(x => x.PostCode);
- if (shouldRepost)
- {
- return true;
- }
- if(supplier.SupplierStatus.HasOriginalValue(x => x.ID))
- {
- var originalID = supplier.SupplierStatus.GetOriginalValue(x => x.ID);
- var currentID = supplier.SupplierStatus.ID;
- var statuses = DbFactory.Provider.Query(
- new Filter<SupplierStatus>(x => x.ID).IsEqualTo(originalID).Or(x => x.ID).IsEqualTo(currentID),
- Columns.None<SupplierStatus>().Add(x => x.ID).Add(x => x.Active))
- .ToArray<SupplierStatus>();
- if (statuses.Length == 2 && statuses[0].Active != statuses[1].Active)
- {
- return true;
- }
- }
- return false;
- }
- }
- public class SupplierMYOBPoster : IMYOBPoster<Supplier, SupplierMYOBPosterSettings>, IAutoRefreshPoster<Supplier, SupplierMYOBAutoRefresher>
- {
- public ScriptDocument? Script { get; set; }
- public MYOBConnectionData ConnectionData { get; set; }
- public SupplierMYOBPosterSettings Settings { get; set; }
- public MYOBGlobalPosterSettings GlobalSettings { get; set; }
- public bool BeforePost(IDataModel<Supplier> model)
- {
- foreach (var (_, table) in model.ModelTables)
- {
- table.IsDefault = false;
- }
- model.SetIsDefault<Supplier>(true);
- model.SetColumns<Supplier>(RequiredColumns());
- Script?.Execute(methodname: "BeforePost", parameters: [model]);
- return true;
- }
- #region Script Functions
- private Result<Exception> ProcessSupplier(IDataModel<Supplier> model, Supplier supplier, MYOBSupplier myobSupplier)
- {
- return this.WrapScript("ProcessSupplier", model, supplier, myobSupplier);
- }
- #endregion
- public static Columns<Supplier> RequiredColumns()
- {
- return Columns.None<Supplier>()
- .Add(x => x.ID)
- .Add(x => x.PostedReference)
- .Add(x => x.PostedStatus)
- .Add(x => x.Name)
- .Add(x => x.Code)
- .Add(x => x.SupplierStatus.ID)
- .Add(x => x.SupplierStatus.Active)
- .Add(x => x.Postal.Street)
- .Add(x => x.Postal.City)
- .Add(x => x.Postal.State)
- .Add(x => x.Postal.PostCode)
- .Add(x => x.Delivery.Street)
- .Add(x => x.Delivery.City)
- .Add(x => x.Delivery.State)
- .Add(x => x.Delivery.PostCode)
- .Add(x => x.Email)
- .Add(x => x.Telephone)
- .Add(x => x.ABN);
- }
- public static Result<Exception> UpdateSupplier(MYOBConnectionData data, MYOBGlobalPosterSettings settings, Supplier supplier, MYOBSupplier myobSupplier, bool isNew)
- {
- // Documentation: https://developer.myob.com/api/myob-business-api/v2/contact/supplier/
- // Since this might be called from some other poster, we need to ensure we have the right columns.
- Client.EnsureColumns(supplier, RequiredColumns());
- // ContactMYOBUtils.SplitName(supplier.DefaultContact.Name, out var firstName, out var lastName);
- myobSupplier.CompanyName = supplier.Name.Truncate(50);
- // myobSupplier.FirstName =
- // myobSupplier.LastName =
- myobSupplier.IsIndividual = false;
- myobSupplier.DisplayID = supplier.Code.Truncate(15);
- // If there is not customer status, we will use default to Active = true.
- myobSupplier.IsActive = supplier.SupplierStatus.ID == Guid.Empty || supplier.SupplierStatus.Active;
- myobSupplier.Addresses =
- [
- ContactMYOBUtils.ConvertAddress(supplier.Postal, 1, new Contact
- {
- Email = supplier.Email,
- Telephone = supplier.Telephone
- }),
- ContactMYOBUtils.ConvertAddress(supplier.Delivery, 2, new Contact
- {
- Email = supplier.Email,
- Telephone = supplier.Telephone
- })
- ];
- // Notes =
- // PhotoURI =
- // RowVersion =
- myobSupplier.BuyingDetails ??= new();
- // myobSupplier.BuyingDetails.PurchaseLayout =
- // myobCustomer.BuyingDetails.PrintedForm =
- // myobSupplier.BuyingDetails.PurchaseOrderDelivery =
- // myobCustomer.BuyingDetails.ExpenseAccount.UID =
- // myobCustomer.BuyingDetails.PaymentMemo =
- // myobCustomer.BuyingDetails.PurchaseComment =
- // myobCustomer.BuyingDetails.SupplierBillingRate =
- // myobCustomer.BuyingDetails.ShippingMethod =
- // myobCustomer.BuyingDetails.IsReportable =
- // myobCustomer.BuyingDetails.CostPerHour =
- // myobCustomer.BuyingDetails.Credit.Limit =
- myobSupplier.BuyingDetails.ABN = supplier.ABN.Truncate(14);
- // myobCustomer.BuyingDetails.ABNBranch
- // myobCustomer.BuyingDetails.TaxIdNumber
- if (isNew)
- {
- if(!MYOBPosterUtils.GetDefaultTaxCode(data, settings).Get(out var taxID, out var error))
- {
- return Result.Error(error);
- }
- myobSupplier.BuyingDetails.TaxCode ??= new();
- myobSupplier.BuyingDetails.TaxCode.UID = taxID;
- myobSupplier.BuyingDetails.FreightTaxCode ??= new();
- myobSupplier.BuyingDetails.FreightTaxCode.UID = taxID;
- }
- // myobCustomer.BuyingDetails.UseSupplierTaxCode
- // myobCustomer.BuyingDetails.Terms
- // myobCustomer.PaymentDetails
- // myobCustomer.PhotoURI
- return Result.Ok();
- }
- /// <summary>
- /// Try to find a supplier in MYOB which matches <paramref name="supplier"/>, and if this fails, create a new one.
- /// </summary>
- /// <remarks>
- /// After this has finished, <paramref name="supplier"/> will be updated with <see cref="Supplier.PostedReference"/> set to the correct ID.
- /// <br/>
- /// <paramref name="supplier"/> needs to have at least <see cref="Supplier.Code"/> and <see cref="Supplier.PostedReference"/> as loaded columns.
- /// </remarks>
- /// <param name="data"></param>
- /// <param name="supplier">The supplier to map to.</param>
- /// <returns>The UID of the MYOB supplier.</returns>
- public static Result<Guid, Exception> MapSupplier(MYOBConnectionData data, Supplier supplier, MYOBGlobalPosterSettings settings)
- {
- if(Guid.TryParse(supplier.PostedReference, out var myobID))
- {
- return Result.Ok(myobID);
- }
- var service = new SupplierService(data.Configuration, null, data.AuthKey);
- var result = service.Query(data, new Filter<MYOBSupplier>(x => x.DisplayID).IsEqualTo(supplier.Code), top: 1);
- return result.MapOk(suppliers =>
- {
- if(suppliers.Items.Length == 0)
- {
- if(supplier.Code.Length > 15)
- {
- return Result.Error(new Exception("Customer code is longer than 15 characters"));
- }
- var myobSupplier = new MYOBSupplier();
- return UpdateSupplier(data, settings, supplier, myobSupplier, true)
- .MapOk(() => service.Save(data, myobSupplier)
- .MapOk(x =>
- {
- supplier.PostedReference = x.UID.ToString();
- // Marking as repost because a script may not have run.
- supplier.PostedStatus = PostedStatus.RequiresRepost;
- return x.UID;
- })).Flatten();
- }
- else
- {
- supplier.PostedReference = suppliers.Items[0].UID.ToString();
- supplier.PostedStatus = PostedStatus.RequiresRepost;
- return Result.Ok(suppliers.Items[0].UID);
- }
- }).Flatten();
- }
- public IPostResult<Supplier> Process(IDataModel<Supplier> model)
- {
- var results = new PostResult<Supplier>();
- var service = new SupplierService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
- var suppliers = model.GetTable<Supplier>().ToArray<Supplier>();
-
- foreach(var supplier in suppliers)
- {
- if(supplier.Code.Length > 15)
- {
- results.AddFailed(supplier, "Code is longer than 15 characters.");
- continue;
- }
- bool isNew;
- MYOBSupplier myobSupplier;
- Exception? error;
- if(Guid.TryParse(supplier.PostedReference, out var myobID))
- {
- if(!service.Get(ConnectionData, myobID).Get(out var newSupplier, out error))
- {
- CoreUtils.LogException("", error, $"Failed to find Supplier in MYOB with id {myobID}");
- results.AddFailed(supplier, $"Failed to find Supplier in MYOB with id {myobID}: {error.Message}");
- continue;
- }
- myobSupplier = newSupplier;
- isNew = false;
- }
- else
- {
- if(service.Query(
- ConnectionData,
- new Filter<MYOBSupplier>(x => x.DisplayID).IsEqualTo(supplier.Code),
- top: 1).Get(out var myobSuppliers, out error))
- {
- if(myobSuppliers.Items.Length > 0)
- {
- myobSupplier = myobSuppliers.Items[0];
- isNew = false;
- }
- else
- {
- myobSupplier = new MYOBSupplier();
- isNew = true;
- }
- }
- else
- {
- CoreUtils.LogException("", error);
- results.AddFailed(supplier, error.Message);
- continue;
- }
- }
- if(UpdateSupplier(ConnectionData, GlobalSettings, supplier, myobSupplier, isNew)
- .MapOk(() => ProcessSupplier(model, supplier, myobSupplier)).Flatten()
- .MapOk(() => service.Save(ConnectionData, myobSupplier)).Flatten()
- .Get(out var result, out error))
- {
- supplier.PostedReference = result.UID.ToString();
- results.AddSuccess(supplier);
- }
- else
- {
- CoreUtils.LogException("", error, $"Error while posting supplier {supplier.ID}");
- results.AddFailed(supplier, error.Message);
- }
- }
- return results;
- }
- }
- public class SupplierMYOBPosterEngine<T> : MYOBPosterEngine<Supplier, SupplierMYOBPosterSettings> { }
|