PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Downplay.Theory.Identity/Services/AddressDirectoryService.cs

#
C# | 275 lines | 228 code | 29 blank | 18 comment | 22 complexity | 1bf8fa181649d0c4d886b6275421266a MD5 | raw file
Possible License(s): CC-BY-SA-3.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using Downplay.Theory.Identity.Models;
  6. using Orchard.Data;
  7. using Orchard.ContentManagement;
  8. using Orchard;
  9. using Orchard.Collections;
  10. using System.Xml.Linq;
  11. using Downplay.Mechanics.Services;
  12. using Orchard.Logging;
  13. using Orchard.Localization;
  14. using Orchard.Core.Title.Models;
  15. namespace Downplay.Theory.Identity.Services
  16. {
  17. public class AddressDirectoryService : IAddressDirectoryService
  18. {
  19. private readonly IOrchardServices _services;
  20. private readonly Lazy<IMechanicsService> _mechanics;
  21. public ILogger Logger { get; set; }
  22. public Localizer T { get; set; }
  23. public const string CountriesContentType = "Country";
  24. public const string TownsContentType = "Town";
  25. public const string AddressesContentType = "Address";
  26. public const string PhoneNumbersContentType = "PhoneNumber";
  27. public AddressDirectoryService(IOrchardServices services,Lazy<IMechanicsService> mechanics)
  28. {
  29. _services = services;
  30. _mechanics = mechanics;
  31. Logger = NullLogger.Instance;
  32. T = NullLocalizer.Instance;
  33. }
  34. public IEnumerable<IContent> GetCountries()
  35. {
  36. return _services.ContentManager.Query<TitlePart, TitlePartRecord>(CountriesContentType).OrderBy(t => t.Title).List();
  37. }
  38. public IContent CreateCountry(string countryName, string countryCode)
  39. {
  40. var country = _services.ContentManager.New(CountriesContentType);
  41. var c = country.As<CountryPart>();
  42. if (c!=null) {
  43. c.As<TitlePart>().Title = countryName;
  44. c.CountryCode = countryCode;
  45. _services.ContentManager.Create(c);
  46. return c;
  47. }
  48. return null;
  49. }
  50. public IContent GetCountry(int countryId)
  51. {
  52. return _services.ContentManager.Get(countryId);
  53. }
  54. public IContent GetCountryByName(string countryName)
  55. {
  56. return _services.ContentManager.Query<TitlePart, TitlePartRecord>(CountriesContentType).Where(t => t.Title == countryName).Slice(0, 1).FirstOrDefault();
  57. }
  58. public IContent GetOrCreateCountryByName(string countryName)
  59. {
  60. var country = GetCountryByName(countryName);
  61. if (country == null)
  62. {
  63. country = CreateCountry(countryName, "xx");
  64. }
  65. return country;
  66. }
  67. public IEnumerable<IContent> GetTowns()
  68. {
  69. return _services.ContentManager.Query<TitlePart,TitlePartRecord>(TownsContentType).OrderBy(t => t.Title).List();
  70. }
  71. public IEnumerable<IContent> GetTowns(int countryId)
  72. {
  73. var connectors = _mechanics.Value.Connectors(countryId, "CountryToTown");
  74. var towns = _mechanics.Value.RightItemsFromConnectors(connectors.List(),TownsContentType);//.Join<TitlePartRecord>().OrderBy(t=>t.Title);
  75. return towns;
  76. }
  77. public IContent CreateTown(int countryId, string regionName)
  78. {
  79. var c = _services.ContentManager.New<TitlePart>(TownsContentType);
  80. c.Title = regionName;
  81. _services.ContentManager.Create(c);
  82. // Create connector (ignoring permissions since this will be an automatic process when someone enters a postcode; rather than anything they can manually edit
  83. _mechanics.Value.CreateConnector(c, countryId, "TownToCountry", true);
  84. return c;
  85. }
  86. public IContent GetTown(int regionId)
  87. {
  88. return _services.ContentManager.Get(regionId);
  89. }
  90. public IContent GetRegionByName(int countryId, string regionName)
  91. {
  92. var connectors = _mechanics.Value.Connectors(countryId, "CountryToTown");
  93. var town = _mechanics.Value.RightItemsFromConnectors(connectors.List(), TownsContentType).FirstOrDefault(t=>t.As<TitlePart>().Title==regionName);
  94. return town;
  95. }
  96. public IContent GetOrCreateTownByName(int countryId, string regionName)
  97. {
  98. var region = GetRegionByName(countryId, regionName);
  99. if (region == null)
  100. {
  101. return CreateTown(countryId, regionName);
  102. }
  103. return region;
  104. }
  105. /*
  106. public RegionRecord GetRegion(int countryId, int regionId)
  107. {
  108. return _regions.Get(r=>r.CountryId==countryId && r.Id == regionId);
  109. }
  110. public IEnumerable<AddressPart> GetItemsByCountryRegion(int countryId, int regionId)
  111. {
  112. var q = _services.ContentManager.Query<AddressPart,AddressPartRecord>()
  113. .Where(p=>p.CountryId == countryId && p.RegionId == regionId);
  114. return q.List();
  115. }
  116. */
  117. public IEnumerable<AddressPart> GetItemsByPostalCodeSearch(string postCodePart)
  118. {
  119. var q = PostalCodeSearchQuery(postCodePart);
  120. return q.List();
  121. }
  122. private IContentQuery<AddressPart, AddressPartRecord> PostalCodeSearchQuery(string postCodePart)
  123. {
  124. var q = _services.ContentManager.Query<AddressPart, AddressPartRecord>()
  125. .Where(p => p.PostalCode.StartsWith(postCodePart));
  126. return q;
  127. }
  128. public IPageOfItems<IContent> GetItemsByPostalCodeSearch(string postCodePart, int page, int? pageSize)
  129. {
  130. var q = PostalCodeSearchQuery(postCodePart);
  131. var totalCount = q.Count();
  132. var paged = q.Slice((page > 0 ? page - 1 : 0) * (int)pageSize, (int)pageSize);
  133. return new PageOfItems<IContent>(q.List())
  134. {
  135. PageNumber = page,
  136. PageSize = pageSize ?? totalCount,
  137. TotalItemCount = totalCount
  138. };
  139. }
  140. public bool LinkAddressToTown(AddressPart part, int townId)
  141. {
  142. IEnumerable<IContent> result = null;
  143. try
  144. {
  145. result = _mechanics.Value.CreateConnector(part, townId, "AddressToTown", true);
  146. if (result.Count()>0) return true;
  147. }
  148. catch (Exception e)
  149. {
  150. Logger.Error(e, "Error linking address to town");
  151. }
  152. return false;
  153. }
  154. public TownPart GetTownForAddress(AddressPart part)
  155. {
  156. return _mechanics.Value.RightItemsFromConnectors(
  157. _mechanics.Value.Connectors(part, "AddressToTown").Slice(0, 1)
  158. ).FirstOrDefault().As<TownPart>();
  159. }
  160. public CountryPart GetCountryForTown(IContent town)
  161. {
  162. return _mechanics.Value.RightItemsFromConnectors(
  163. _mechanics.Value.Connectors(town, "TownToCountry").Slice(0, 1)
  164. ).FirstOrDefault().As<CountryPart>();
  165. }
  166. public IContent CreateAddress(ViewModels.AddressEditViewModel viewModel,IUpdateModel updater, string prefix)
  167. {
  168. var address = _services.ContentManager.New(AddressesContentType);
  169. var part = address.As<AddressPart>();
  170. if (part != null)
  171. {
  172. if (PopulateAddressFromViewModel(part, viewModel, updater, prefix))
  173. {
  174. // Publish
  175. _services.ContentManager.Create(address);
  176. if (!LinkAddressToTown(part, viewModel.TownId.Value))
  177. {
  178. updater.AddModelError(prefix + ".TownName", T("Error saving town. Enter a valid town name or select from the list."));
  179. _services.ContentManager.Remove(address);
  180. }
  181. return address;
  182. }
  183. }
  184. return null;
  185. }
  186. public bool PopulateAddressFromViewModel(AddressPart part, ViewModels.AddressEditViewModel viewModel, IUpdateModel updater, string prefix)
  187. {
  188. var ok = true;
  189. // Copy normal fields from view model
  190. if (String.IsNullOrWhiteSpace(viewModel.PostalCode))
  191. {
  192. updater.AddModelError(prefix + ".PostalCode", T("Please enter a post code."));
  193. ok = false;
  194. }
  195. else
  196. {
  197. // Strip any spaces
  198. part.PostalCode = viewModel.PostalCode = viewModel.PostalCode.Replace(" ", "");
  199. }
  200. part.AddressType = viewModel.AddressType;
  201. if (String.IsNullOrWhiteSpace(viewModel.Address1))
  202. {
  203. updater.AddModelError(prefix + ".Address1", T("Please enter at least the first line of the street address."));
  204. ok = false;
  205. }
  206. part.Address1 = viewModel.Address1;
  207. part.Address2 = viewModel.Address2;
  208. part.Address3 = viewModel.Address3;
  209. // Attempt to create inputted country name
  210. if (!String.IsNullOrWhiteSpace(viewModel.CountryName))
  211. {
  212. try
  213. {
  214. var country = GetOrCreateCountryByName(viewModel.CountryName);
  215. if (country != null)
  216. {
  217. viewModel.CountryId = country.Id;
  218. }
  219. }
  220. catch (Exception e)
  221. {
  222. Logger.Error(e, "Couldn't create country");
  223. }
  224. }
  225. // Attempt to create inputted region name
  226. if (!viewModel.CountryId.HasValue)
  227. {
  228. updater.AddModelError(prefix + ".CountryName", T("Error saving country. Enter a valid country name or select from the list."));
  229. ok = false;
  230. }
  231. if (viewModel.CountryId.HasValue && !String.IsNullOrWhiteSpace(viewModel.TownName))
  232. {
  233. var region = GetOrCreateTownByName(viewModel.CountryId.Value, viewModel.TownName);
  234. if (region != null)
  235. {
  236. viewModel.TownId = region.Id;
  237. }
  238. }
  239. if (!viewModel.TownId.HasValue){
  240. updater.AddModelError(prefix + ".TownName", T("Enter a valid town name or select from the list."));
  241. ok = false;
  242. }
  243. return ok;
  244. }
  245. }
  246. }