123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489 |
- 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.NewProvider(Logger.Main).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();
- }
- private static bool IsBlankCode(string code)
- {
- return code.IsNullOrWhiteSpace() || code.Equals("*None");
- }
- public IPullResult<Supplier> Pull()
- {
- var result = new PullResult<Supplier>();
- var top = 400;
- var skip = 0;
- var supplierCodes = new HashSet<string>();
- var service = new SupplierService(ConnectionData.Configuration, null, ConnectionData.AuthKey);
- while (true)
- {
- if(!service.Query(ConnectionData, null, top: top, skip: skip).Get(out var myobSuppliers, out var error))
- {
- CoreUtils.LogException("", error);
- throw new PullFailedMessageException(error.Message);
- }
- if(myobSuppliers.Items.Length == 0)
- {
- break;
- }
- var myobIDs = myobSuppliers.Items.ToArray(x => x.UID.ToString());
- var myobCodes = myobSuppliers.Items.Select(x => x.DisplayID).Where(x => !IsBlankCode(x)).ToArray();
- var myobNames = myobSuppliers.Items.Where(x => IsBlankCode(x.DisplayID) && !x.CompanyName.IsNullOrWhiteSpace())
- .Select(x => x.CompanyName).ToArray();
- var suppliers = Client.Query(
- new Filter<Supplier>(x => x.PostedReference).InList(myobIDs)
- .Or(x => x.Code).InList(myobCodes)
- .Or(x => x.Name).InList(myobNames),
- Columns.None<Supplier>().Add(x => x.ID).Add(x => x.PostedReference).Add(x => x.Code).Add(x => x.Name))
- .ToArray<Supplier>();
- var supplierDict = suppliers.Where(x => !x.PostedReference.IsNullOrWhiteSpace())
- .ToDictionary(x => x.PostedReference);
- var blankSuppliers = suppliers.Where(x => x.PostedReference.IsNullOrWhiteSpace()).ToArray();
- var needCodes = new Dictionary<string, (string prefix, int i, Supplier supplier)>();
- foreach(var myobSupplier in myobSuppliers.Items)
- {
- if (supplierDict.TryGetValue(myobSupplier.UID.ToString(), out var supplier))
- {
- // Skipping existing suppliers at this point.
- continue;
- }
- supplier = !IsBlankCode(myobSupplier.DisplayID)
- ? blankSuppliers.FirstOrDefault(x => string.Equals(x.Code, myobSupplier.DisplayID))
- : blankSuppliers.FirstOrDefault(x => string.Equals(x.Name, myobSupplier.CompanyName));
- if(supplier is not null)
- {
- supplier.PostedReference = myobSupplier.UID.ToString();
- result.AddEntity(PullResultType.Linked, supplier);
- continue;
- }
- supplier = new Supplier();
- string code;
- if (!IsBlankCode(myobSupplier.DisplayID))
- {
- code = myobSupplier.DisplayID.ToString();
- }
- else if (!myobSupplier.CompanyName.IsNullOrWhiteSpace())
- {
- code = myobSupplier.CompanyName[..Math.Min(3, myobSupplier.CompanyName.Length)].ToUpper();
- }
- else
- {
- code = "SUP";
- }
- int i = 1;
- supplier.Code = code;
- while (supplierCodes.Contains(supplier.Code))
- {
- supplier.Code = $"{code}{i:d3}";
- ++i;
- }
- supplierCodes.Add(supplier.Code);
- supplier.Name = myobSupplier.CompanyName;
- supplier.ABN = myobSupplier.BuyingDetails.ABN;
- if(myobSupplier.Addresses is not null)
- {
- var delivery = myobSupplier.Addresses.FirstOrDefault(x => x.Location == 2);
- if(delivery is not null)
- {
- supplier.Delivery.CopyFrom(ContactMYOBUtils.ConvertAddress(delivery));
- }
- var postal = myobSupplier.Addresses.FirstOrDefault(x => x.Location == 1);
- if(postal is not null)
- {
- supplier.Postal.CopyFrom(ContactMYOBUtils.ConvertAddress(postal));
- }
- supplier.Email = delivery?.Email ?? postal?.Email ?? "";
- }
- supplier.PostedReference = myobSupplier.UID.ToString();
- result.AddEntity(PullResultType.New, supplier);
- needCodes.Add(supplier.Code, (code, i, supplier));
- }
- // Do code clash checking
- while(needCodes.Count > 0)
- {
- var codes = Client.Query(
- new Filter<Supplier>(x => x.Code).InList(needCodes.Values.Select(x => x.supplier.Code).ToArray()),
- Columns.None<Supplier>().Add(x => x.Code));
- var newNeedCodes = new Dictionary<string, (string prefix, int i, Supplier supplier)>();
- foreach(var row in codes.Rows)
- {
- var code = row.Get<Supplier, string>(x => x.Code);
- if(needCodes.Remove(code, out var needed))
- {
- int i = needed.i;
- do
- {
- needed.supplier.Code = $"{needed.prefix}{i:d3}";
- ++i;
- } while (supplierCodes.Contains(needed.supplier.Code));
- supplierCodes.Add(needed.supplier.Code);
- newNeedCodes.Add(needed.supplier.Code, (needed.prefix, i, needed.supplier));
- }
- }
- needCodes = newNeedCodes;
- }
- skip += top;
- }
- return result;
- }
- 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 if(service.Query(
- ConnectionData,
- new Filter<MYOBSupplier>(x => x.CompanyName).IsEqualTo(supplier.Name)
- .And(new Filter<MYOBSupplier>(x => x.DisplayID).IsEqualTo(null)
- .Or(x => x.DisplayID).IsEqualTo("")
- .Or(x => x.DisplayID).IsEqualTo("*None")),
- top: 1).Get(out myobSuppliers, out error))
- {
- if(myobSuppliers.Items.Length > 0)
- {
- myobSupplier = myobSuppliers.Items[0];
- myobSupplier.DisplayID = supplier.Code;
- isNew = false;
- }
- else
- {
- myobSupplier = new MYOBSupplier();
- isNew = true;
- }
- }
- else
- {
- CoreUtils.LogException("", error);
- results.AddFailed(supplier, error.Message);
- continue;
- }
- }
- 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, SupplierMYOBPoster, SupplierMYOBPosterSettings>, IPullerEngine<Supplier, SupplierMYOBPoster>
- {
- public IPullResult<Supplier> DoPull()
- {
- LoadConnectionData();
- return Poster.Pull();
- }
- }
|