Exemplo n.º 1
0
        private Vendor FindSageVendor(Models.Data.Vendor vendor)
        {
            var vendorKey   = vendor.GlobalKey(actionSource);
            var sageVendors = VendorsList();

            // find mapping for vendor globalKey
            var sageVendorId = localDbApi.GetVendorIdByKey(vendorKey);

            if (sageVendorId != null)
            {
                return(sageVendors.SingleOrDefault(sageVendorId));
            }

            // find by GlobalKey in Sage50
            var sageCustomer = sageVendors.SingleOrDefault(vendorKey);

            if (sageCustomer != null)
            {
                localDbApi.StoreVendorId(vendorKey, sageCustomer.ID);
                return(sageCustomer);
            }

            // if no mapping found, find customer by name or email and store mapping to localDb

            if (string.IsNullOrEmpty(vendor.Name) && string.IsNullOrEmpty(vendor.Email))
            {
                throw new AbortException("Can not find Vendor because name and email is null");
            }

            FilterExpression expression;
            string           message = "";

            if (!string.IsNullOrEmpty(vendor.Name) && !string.IsNullOrEmpty(vendor.Email))
            {
                expression = FilterExpression.AndAlso(
                    FilterExpression.Equal(FilterExpression.Property("Vendor.Name"), FilterExpression.Constant(vendor.Name)),
                    FilterExpression.Equal(FilterExpression.Property("Vendor.Email"), FilterExpression.Constant(vendor.Email))
                    );
                LoadVendorsList(expression, sageVendors);
                message = $"name: '{vendor.Name}' and email: '{vendor.Email}'";
            }
            if (sageVendors.Count == 0 && !string.IsNullOrEmpty(vendor.Email))
            {
                expression = FilterExpression.Equal(FilterExpression.Property("Vendor.Email"),
                                                    FilterExpression.Constant(vendor.Email));
                LoadVendorsList(expression, sageVendors);
                message = $"email: '{vendor.Email}'";
            }
            if (sageVendors.Count == 0 && !string.IsNullOrEmpty(vendor.Name))
            {
                expression = FilterExpression.Equal(FilterExpression.Property("Vendor.Name"), FilterExpression.Constant(vendor.Name));
                LoadVendorsList(expression, sageVendors);
                message = $"name: '{vendor.Name}'";
            }

            if (sageVendors.Count == 0)
            {
                return(null);
            }

            if (sageVendors.Count > 1)
            {
                throw new AbortException($"Found more that one vendor with {message}");
            }

            sageCustomer = sageVendors.First();
            localDbApi.StoreVendorId(vendorKey, sageCustomer.ID);
            return(sageCustomer);
        }