-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathCustomerExtentions.cs
431 lines (374 loc) · 15 KB
/
CustomerExtentions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Xml;
using SmartStore.Core.Domain.Customers;
using SmartStore.Core.Domain.Orders;
using SmartStore.Core.Infrastructure;
using SmartStore.Services.Common;
using SmartStore.Services.Localization;
using SmartStore.Services.Orders;
namespace SmartStore.Services.Customers
{
public static class CustomerExtentions
{
/// <summary>
/// Gets a value indicating whether customer is in a certain customer role
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="customerRoleSystemName">Customer role system name</param>
/// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
/// <returns>Result</returns>
public static bool IsInCustomerRole(this Customer customer, string customerRoleSystemName, bool onlyActiveCustomerRoles = true)
{
if (customer == null)
throw new ArgumentNullException("customer");
if (String.IsNullOrEmpty(customerRoleSystemName))
throw new ArgumentNullException("customerRoleSystemName");
var result = customer.CustomerRoles
.Where(cr => !onlyActiveCustomerRoles || cr.Active)
.Where(cr => cr.SystemName == customerRoleSystemName)
.FirstOrDefault() != null;
return result;
}
/// <summary>
/// Gets a value indicating whether the customer is a built-in record for background tasks
/// </summary>
/// <param name="customer">Customer</param>
/// <returns>Result</returns>
public static bool IsBackgroundTaskAccount(this Customer customer)
{
Guard.ArgumentNotNull(() => customer);
if (!customer.IsSystemAccount || customer.SystemName.IsEmpty())
return false;
var result = customer.SystemName.Equals(SystemCustomerNames.BackgroundTask, StringComparison.InvariantCultureIgnoreCase);
return result;
}
/// <summary>
/// Gets a value indicating whether customer is a search engine
/// </summary>
/// <param name="customer">Customer</param>
/// <returns>Result</returns>
public static bool IsSearchEngineAccount(this Customer customer)
{
Guard.ArgumentNotNull(() => customer);
if (!customer.IsSystemAccount || customer.SystemName.IsEmpty())
return false;
var result = customer.SystemName.Equals(SystemCustomerNames.SearchEngine, StringComparison.InvariantCultureIgnoreCase);
return result;
}
/// <summary>
/// Gets a value indicating whether customer is the pdf converter
/// </summary>
/// <param name="customer">Customer</param>
/// <returns>Result</returns>
public static bool IsPdfConverter(this Customer customer)
{
Guard.ArgumentNotNull(() => customer);
if (!customer.IsSystemAccount || customer.SystemName.IsEmpty())
return false;
var result = customer.SystemName.Equals(SystemCustomerNames.PdfConverter, StringComparison.InvariantCultureIgnoreCase);
return result;
}
/// <summary>
/// Gets a value indicating whether customer is administrator
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
/// <returns>Result</returns>
public static bool IsAdmin(this Customer customer, bool onlyActiveCustomerRoles = true)
{
return IsInCustomerRole(customer, SystemCustomerRoleNames.Administrators, onlyActiveCustomerRoles);
}
/// <summary>
/// Gets a value indicating whether customer is super administrator
/// </summary>
/// <remarks>codehint: sm-add</remarks>
/// <param name="customer">Customer</param>
/// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
/// <returns>Result</returns>
public static bool IsSuperAdmin(this Customer customer, bool onlyActiveCustomerRoles = true) {
return IsInCustomerRole(customer, SystemCustomerRoleNames.SuperAdministrators, onlyActiveCustomerRoles);
}
/// <summary>
/// Gets a value indicating whether customer is a forum moderator
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
/// <returns>Result</returns>
public static bool IsForumModerator(this Customer customer, bool onlyActiveCustomerRoles = true)
{
return IsInCustomerRole(customer, SystemCustomerRoleNames.ForumModerators, onlyActiveCustomerRoles);
}
/// <summary>
/// Gets a value indicating whether customer is registered
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
/// <returns>Result</returns>
public static bool IsRegistered(this Customer customer, bool onlyActiveCustomerRoles = true)
{
return IsInCustomerRole(customer, SystemCustomerRoleNames.Registered, onlyActiveCustomerRoles);
}
/// <summary>
/// Gets a value indicating whether customer is guest
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="onlyActiveCustomerRoles">A value indicating whether we should look only in active customer roles</param>
/// <returns>Result</returns>
public static bool IsGuest(this Customer customer, bool onlyActiveCustomerRoles = true)
{
return IsInCustomerRole(customer, SystemCustomerRoleNames.Guests, onlyActiveCustomerRoles);
}
public static string GetFullName(this Customer customer)
{
if (customer == null)
throw new ArgumentNullException("customer");
var firstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName);
var lastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName);
string fullName = "";
if (!String.IsNullOrWhiteSpace(firstName) && !String.IsNullOrWhiteSpace(lastName))
{
fullName = string.Format("{0} {1}", firstName, lastName);
}
else
{
if (!String.IsNullOrWhiteSpace(firstName))
fullName = firstName;
if (!String.IsNullOrWhiteSpace(lastName))
fullName = lastName;
if (String.IsNullOrWhiteSpace(firstName) && String.IsNullOrWhiteSpace(lastName))
{
var address = customer.Addresses.FirstOrDefault();
if (address != null)
fullName = string.Format("{0} {1}", address.FirstName, address.LastName);
}
}
return fullName;
}
/// <summary>
/// Formats the customer name
/// </summary>
/// <param name="customer">Source</param>
/// <returns>Formatted text</returns>
public static string FormatUserName(this Customer customer)
{
return FormatUserName(customer, false);
}
/// <summary>
/// Formats the customer name
/// </summary>
/// <param name="customer">Source</param>
/// <param name="stripTooLong">Strip too long customer name</param>
/// <returns>Formatted text</returns>
public static string FormatUserName(this Customer customer, bool stripTooLong)
{
if (customer == null)
return string.Empty;
if (customer.IsGuest())
{
return EngineContext.Current.Resolve<ILocalizationService>().GetResource("Customer.Guest");
}
string result = string.Empty;
switch (EngineContext.Current.Resolve<CustomerSettings>().CustomerNameFormat)
{
case CustomerNameFormat.ShowEmails:
result = customer.Email;
break;
case CustomerNameFormat.ShowFullNames:
result = customer.GetFullName();
break;
case CustomerNameFormat.ShowUsernames:
result = customer.Username;
break;
case CustomerNameFormat.ShowFirstName:
result = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName);
break;
case CustomerNameFormat.ShowNameAndCity:
{
var firstName = customer.GetAttribute<string>(SystemCustomerAttributeNames.FirstName);
var lastName = customer.GetAttribute<string>(SystemCustomerAttributeNames.LastName);
var city = customer.GetAttribute<string>(SystemCustomerAttributeNames.City);
if (firstName.IsEmpty())
{
var address = customer.Addresses.FirstOrDefault();
if (address != null)
{
firstName = address.FirstName;
lastName = address.LastName;
city = address.City;
}
}
result = firstName;
if (lastName.HasValue())
{
result = "{0} {1}.".FormatWith(result, lastName.First());
}
if (city.HasValue())
{
var from = EngineContext.Current.Resolve<ILocalizationService>().GetResource("Common.ComingFrom");
result = "{0} {1} {2}".FormatWith(result, from, city);
}
}
break;
default:
break;
}
if (stripTooLong && result.HasValue())
{
int maxLength = EngineContext.Current.Resolve<CustomerSettings>().CustomerNameFormatMaxLength;
if (maxLength > 0 && result.Length > maxLength)
{
result = result.Truncate(maxLength, "...");
}
}
return result;
}
/// <summary>
/// Find any email address of customer
/// </summary>
public static string FindEmail(this Customer customer)
{
if (customer != null)
{
if (customer.Email.HasValue())
return customer.Email;
if (customer.BillingAddress != null && customer.BillingAddress.Email.HasValue())
return customer.BillingAddress.Email;
if (customer.ShippingAddress != null && customer.ShippingAddress.Email.HasValue())
return customer.ShippingAddress.Email;
}
return null;
}
#region Shopping cart
public static int CountProductsInCart(this Customer customer, ShoppingCartType cartType, int? storeId = null)
{
int count = customer.ShoppingCartItems
.Filter(cartType, storeId)
.Where(x => x.ParentItemId == null)
.Sum(x => x.Quantity);
return count;
}
public static List<OrganizedShoppingCartItem> GetCartItems(this Customer customer, ShoppingCartType cartType, int? storeId = null)
{
var rawItems = customer.ShoppingCartItems.Filter(cartType, storeId);
var organizedItems = rawItems
.OrderByDescending(x => x.Id)
.ToList()
.Organize();
return organizedItems.ToList();
}
#endregion
#region Gift cards
/// <summary>
/// Gets coupon codes
/// </summary>
/// <param name="customer">Customer</param>
/// <returns>Coupon codes</returns>
public static string[] ParseAppliedGiftCardCouponCodes(this Customer customer)
{
var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>();
string existingGiftCartCouponCodes = customer.GetAttribute<string>(SystemCustomerAttributeNames.GiftCardCouponCodes,
genericAttributeService);
var couponCodes = new List<string>();
if (String.IsNullOrEmpty(existingGiftCartCouponCodes))
return couponCodes.ToArray();
try
{
var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(existingGiftCartCouponCodes);
var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["Code"] != null)
{
string code = node1.Attributes["Code"].InnerText.Trim();
couponCodes.Add(code);
}
}
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
return couponCodes.ToArray();
}
/// <summary>
/// Adds a coupon code
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="couponCode">Coupon code</param>
/// <returns>New coupon codes document</returns>
public static void ApplyGiftCardCouponCode(this Customer customer, string couponCode)
{
var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>();
string result = string.Empty;
try
{
string existingGiftCartCouponCodes = customer.GetAttribute<string>(SystemCustomerAttributeNames.GiftCardCouponCodes,
genericAttributeService);
couponCode = couponCode.Trim().ToLower();
var xmlDoc = new XmlDocument();
if (String.IsNullOrEmpty(existingGiftCartCouponCodes))
{
var element1 = xmlDoc.CreateElement("GiftCardCouponCodes");
xmlDoc.AppendChild(element1);
}
else
{
xmlDoc.LoadXml(existingGiftCartCouponCodes);
}
var rootElement = (XmlElement)xmlDoc.SelectSingleNode(@"//GiftCardCouponCodes");
XmlElement gcElement = null;
//find existing
var nodeList1 = xmlDoc.SelectNodes(@"//GiftCardCouponCodes/CouponCode");
foreach (XmlNode node1 in nodeList1)
{
if (node1.Attributes != null && node1.Attributes["Code"] != null)
{
string couponCodeAttribute = node1.Attributes["Code"].InnerText.Trim();
if (couponCodeAttribute.ToLower() == couponCode.ToLower())
{
gcElement = (XmlElement)node1;
break;
}
}
}
//create new one if not found
if (gcElement == null)
{
gcElement = xmlDoc.CreateElement("CouponCode");
gcElement.SetAttribute("Code", couponCode);
rootElement.AppendChild(gcElement);
}
result = xmlDoc.OuterXml;
}
catch (Exception exc)
{
Debug.Write(exc.ToString());
}
//apply new value
genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, result);
}
/// <summary>
/// Removes a coupon code
/// </summary>
/// <param name="customer">Customer</param>
/// <param name="couponCode">Coupon code to remove</param>
/// <returns>New coupon codes document</returns>
public static void RemoveGiftCardCouponCode(this Customer customer, string couponCode)
{
//get applied coupon codes
var existingCouponCodes = customer.ParseAppliedGiftCardCouponCodes();
//clear them
var genericAttributeService = EngineContext.Current.Resolve<IGenericAttributeService>();
genericAttributeService.SaveAttribute<string>(customer, SystemCustomerAttributeNames.GiftCardCouponCodes, null);
//save again except removed one
foreach (string existingCouponCode in existingCouponCodes)
if (!existingCouponCode.Equals(couponCode, StringComparison.InvariantCultureIgnoreCase))
customer.ApplyGiftCardCouponCode(existingCouponCode);
}
#endregion
}
}