private List <EstablishmentMapData> GetMapData(string search)
        {
            string cacheKey;

            if (string.IsNullOrEmpty(search))
            {
                cacheKey = "MAP_NOSEARCH";
            }
            else
            {
                search   = search.ToUpper();
                search   = search.Trim();
                cacheKey = $"MAP_SEARCH_{search}";
            }
            List <EstablishmentMapData> establishmentMapData;

            if (!_cache.TryGetValue("S_" + cacheKey, out establishmentMapData))
            {
                try
                {
                    string applicationsFilter = "_adoxio_assignedlicence_value ne null ";
                    // get establishments
                    string   licenseFilter = "statuscode eq 1"; // only active licenses
                    string[] licenseExpand = { "adoxio_LicenceType" };

                    // we need to get applications so we can see if the inspection is complete.

                    IList <MicrosoftDynamicsCRMadoxioApplication> applications = null;
                    try
                    {
                        applications = _dynamicsClient.Applications.Get(filter: applicationsFilter).Value;
                    }
                    catch (HttpOperationException httpOperationException)
                    {
                        _logger.LogError(httpOperationException, "Error getting applications");
                        throw new Exception("Unable to get applications");
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, "Unexpected error getting applications");
                    }

                    // get licenses
                    IList <MicrosoftDynamicsCRMadoxioLicences> licences = null;

                    try
                    {
                        licences = _dynamicsClient.Licenceses.Get(filter: licenseFilter, expand: licenseExpand).Value;
                    }
                    catch (HttpOperationException httpOperationException)
                    {
                        _logger.LogError(httpOperationException, "Error getting licenses");
                        throw new Exception("Unable to get licences");
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e, "Unexpected error getting establishment map data.");
                    }

                    establishmentMapData = new List <EstablishmentMapData>();
                    if (licences != null)
                    {
                        foreach (var license in licences)
                        {
                            if (license.AdoxioLicenceType != null && license.AdoxioLicenceType.AdoxioName.Equals("Cannabis Retail Store"))
                            {
                                // Change 2019-10-24 - default to add, as we no longer check to see if the establishment has had the final inspection.
                                bool add = true;

                                // only consider the item if the inspection is complete.

                                // note that the Linq query is required because the License does not contain accurate data to show the related applications.

                                //var relatedApplications = applications.Where(app => app._adoxioAssignedlicenceValue == license.AdoxioLicencesid).ToList();

                                // Change 2019-10-24 - no longer filter out establishments that have not passed the final inspection.

                                /*
                                 * if (relatedApplications != null)
                                 * {
                                 *  foreach (var item in relatedApplications)
                                 *  {
                                 *      // with the new business flow, we check for a pass (845280000) in AdoxioAppchecklistinspectionresults
                                 *      if (item.AdoxioAppchecklistinspectionresults != null && item.AdoxioAppchecklistinspectionresults == 845280000)
                                 *      {
                                 *          add = true;
                                 *      }
                                 *  }
                                 * }
                                 */
                                // do not add LDB stores at this time.
                                if (add && license._adoxioEstablishmentValue != null)
                                {
                                    var establishment = _dynamicsClient.GetEstablishmentById(license._adoxioEstablishmentValue);


                                    if (establishment != null &&
                                        (establishment.AdoxioLicencee == null || establishment.AdoxioLicencee.Name != LDB_ACCOUNT_NAME) &&
                                        establishment.AdoxioLatitude != null && establishment.AdoxioLongitude != null)
                                    {
                                        if (add && !string.IsNullOrEmpty(search) && establishment.AdoxioName != null && establishment.AdoxioAddresscity != null)
                                        {
                                            search = search.ToUpper();
                                            if (!establishment.AdoxioName.ToUpper().StartsWith(search) &&
                                                !establishment.AdoxioAddresscity.ToUpper().StartsWith(search))
                                            {
                                                // candidate for rejection; check the lgin too.
                                                if (establishment._adoxioLginValue != null)
                                                {
                                                    establishment.AdoxioLGIN = _dynamicsClient.GetLginById(establishment._adoxioLginValue);
                                                    if (establishment.AdoxioLGIN == null ||
                                                        establishment.AdoxioLGIN.AdoxioName == null ||
                                                        !establishment.AdoxioLGIN.AdoxioName.ToUpper().StartsWith(search))
                                                    //|| !
                                                    {
                                                        add = false;
                                                    }
                                                }
                                                else
                                                {
                                                    add = false;
                                                }
                                            }
                                        }

                                        if (add)
                                        {
                                            establishmentMapData.Add(new EstablishmentMapData
                                            {
                                                id            = establishment.AdoxioEstablishmentid,
                                                Name          = establishment.AdoxioName,
                                                License       = license.AdoxioLicencenumber,
                                                Phone         = establishment.AdoxioPhone,
                                                AddressCity   = establishment.AdoxioAddresscity,
                                                AddressPostal = establishment.AdoxioAddresspostalcode,
                                                AddressStreet = establishment.AdoxioAddressstreet,
                                                Latitude      = (decimal)establishment.AdoxioLatitude,
                                                Longitude     = (decimal)establishment.AdoxioLongitude,
                                                IsOpen        = establishment.AdoxioIsopen.HasValue && establishment.AdoxioIsopen.Value
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                                            // Set the cache to expire in an hour.
                                            .SetAbsoluteExpiration(TimeSpan.FromHours(1));

                    // Save data in cache.
                    _cache.Set("S_" + cacheKey, establishmentMapData, cacheEntryOptions);
                    cacheEntryOptions = new MemoryCacheEntryOptions()
                                        // Set the cache to expire in an hour.
                                        .SetAbsoluteExpiration(TimeSpan.FromDays(1));
                    // long term cache
                    _cache.Set(cacheKey, establishmentMapData, cacheEntryOptions);
                }
                catch (Exception e)
                {
                    if (!_cache.TryGetValue(cacheKey, out establishmentMapData))
                    {
                        establishmentMapData = new List <EstablishmentMapData>();
                        _logger.LogError(e, "Error getting map data, and nothing in long term cache.");
                    }
                    else
                    {
                        _logger.LogError(e, "Error getting map data, showing long term cache data");
                    }
                }
            }

            // make a copy of the results to guard against accidental cache pollution.
            List <EstablishmentMapData> result = establishmentMapData.ToList();

            // add LDB stores
            result.AddRange(GetLDBStores(search));

            // sort the establishment list by the city alphabetically
            result = result.OrderBy(o => o.AddressCity).ToList();

            return(result);
        }
Example #2
0
        private async Task GeocodeEstablishment(PerformContext hangfireContext, MicrosoftDynamicsCRMadoxioEstablishment establishment)
        {
            if (establishment != null && !string.IsNullOrEmpty(establishment.AdoxioAddresscity))
            {
                string streetAddress = SanitizeStreetAddress(establishment.AdoxioAddressstreet);
                string address       = $"{establishment.AdoxioAddressstreet}, {establishment.AdoxioAddresscity}, BC";
                // output format can be xhtml, kml, csv, shpz, geojson, geojsonp, gml
                var output = _geocoder.GeoCoderAPI.Sites(outputFormat: "json", addressString: address);

                // if there are any faults try a query based on the LGIN instead of the city.
                if (output.Features[0].Properties.Faults.Count > 0 && establishment._adoxioLginValue != null)
                {
                    var lgin = _dynamics.GetLginById(establishment._adoxioLginValue);
                    _logger.LogError($"Unable to find a good match for address {address}, using lgin of {lgin.AdoxioName}");
                    hangfireContext.WriteLine($"Unable to find a good match for address {address}, using lgin of {lgin.AdoxioName}");

                    address = $"{establishment.AdoxioAddressstreet}, {lgin.AdoxioName}, BC";
                    output  = _geocoder.GeoCoderAPI.Sites(outputFormat: "json", addressString: address);
                }

                // if the LGIN did not provide a good match just default to the specified city.
                if (output.Features[0].Properties.Faults.Count > 2)
                {
                    _logger.LogError($"Unable to find a good match for address {address} with city {establishment._adoxioLginValue}, defaulting to just {establishment.AdoxioAddresscity}");
                    hangfireContext.WriteLine($"Unable to find a good match for address {address} with city {establishment._adoxioLginValue}, defaulting to just {establishment.AdoxioAddresscity}");
                    output = _geocoder.GeoCoderAPI.Sites(outputFormat: "json", addressString: $"{establishment.AdoxioAddresscity}, BC");
                }


                // get the lat and long for the pin.
                double?longData = output.Features[0].Geometry.Coordinates[0];
                double?latData  = output.Features[0].Geometry.Coordinates[1];

                // update the establishment.

                var patchEstablishment = new MicrosoftDynamicsCRMadoxioEstablishment()
                {
                    AdoxioLongitude = (decimal?)longData,
                    AdoxioLatitude  = (decimal?)latData
                };
                try
                {
                    _dynamics.Establishments.Update(establishment.AdoxioEstablishmentid, patchEstablishment);
                    _logger.LogInformation($"Updated establishment with address {address}");
                    hangfireContext.WriteLine($"Updated establishment with address {address}");
                }
                catch (HttpOperationException odee)
                {
                    if (hangfireContext != null)
                    {
                        _logger.LogError("Error updating establishment");
                        _logger.LogError("Request:");
                        _logger.LogError(odee.Request.Content);
                        _logger.LogError("Response:");
                        _logger.LogError(odee.Response.Content);
                        hangfireContext.WriteLine("Error updating establishment");
                        hangfireContext.WriteLine("Request:");
                        hangfireContext.WriteLine(odee.Request.Content);
                        hangfireContext.WriteLine("Response:");
                        hangfireContext.WriteLine(odee.Response.Content);
                    }

                    // fail if we can't update.
                    throw (odee);
                }
            }
        }