using Comal.Classes; using InABox.Core; using InABox.Poster.MYOB; using MYOB.AccountRight.SDK.Contracts.Version2; using MYOB.AccountRight.SDK.Services; using MYOB.AccountRight.SDK.Services.GeneralLedger; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MYOBBaseEntity = MYOB.AccountRight.SDK.Contracts.Version2.BaseEntity; using MYOBTaxCode = MYOB.AccountRight.SDK.Contracts.Version2.GeneralLedger.TaxCode; namespace PRS.Shared.Posters.MYOB; public static class PRSMYOBPosterUtils { public class QueryResult : Result, Exception> { public QueryResult(PagedCollection value) : base(value) { } public QueryResult(Exception error) : base(error) { } public static QueryResult Ok(PagedCollection collection) => new QueryResult(collection); public static QueryResult Error(Exception e) => new QueryResult(e); } public class GetResult : Result { public GetResult(T value) : base(value) { } public GetResult(Exception error) : base(error) { } public static GetResult Ok(T value) => new GetResult(value); public static GetResult Error(Exception e) => new GetResult(e); } public static Result, Exception> Query( this MutableService service, MYOBConnectionData data, Filter? filter, int? top = null, int? skip = null ) where T : MYOBBaseEntity { var queries = new List(); if(filter is not null) { queries.Add($"$filter={Uri.EscapeDataString(filter.AsOData())}"); } if (top.HasValue) { queries.Add($"$top={top.Value}"); } if (skip.HasValue) { queries.Add($"$skip={skip.Value}"); } try { var values = service.GetRange(data.CompanyFile, string.Join('&', queries), data.CompanyFileCredentials); return QueryResult.Ok(values); } catch(Exception e) { return QueryResult.Error(e); } } public static GetResult Get(this MutableService service, MYOBConnectionData data, Guid id) where T : MYOBBaseEntity { try { var value = service.Get(data.CompanyFile, id, data.CompanyFileCredentials); return GetResult.Ok(value); } catch(Exception e) { return GetResult.Error(e); } } public static Result GetMYOBTaxCodeUID(this MYOBConnectionData data, string code) { var service = new TaxCodeService(data.Configuration, null, data.AuthKey); var result = service.Query(data, new Filter(x => x.Code).IsEqualTo(code), top: 1); if(!result.Get(out var myobCodes, out var error)) { return Result.Error(error); } if(myobCodes.Count == 0) { return Result.Ok(Guid.Empty); } return Result.Ok(myobCodes.Items[0].UID); } public static Result GetMYOBTaxCodeUID(this MYOBConnectionData data, ITaxCode code) { if(Guid.TryParse(code.PostedReference, out var id)) { return Result.Ok(id); } return GetMYOBTaxCodeUID(data, code.Code); } }