/
ProductService.cs
620 lines (546 loc) · 21.5 KB
/
ProductService.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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
namespace Merchello.Core.Services
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Models;
using Persistence.Querying;
using Persistence.UnitOfWork;
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.Querying;
using umbraco.presentation.actions;
using RepositoryFactory = Merchello.Core.Persistence.RepositoryFactory;
/// <summary>
/// Represents the Product Service
/// </summary>
public class ProductService : PageCachedServiceBase<IProduct>, IProductService
{
/// <summary>
/// The locker.
/// </summary>
private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
/// <summary>
/// The valid sort fields.
/// </summary>
private static readonly string[] ValidSortFields = { "sku", "name", "price" };
/// <summary>
/// The uow provider.
/// </summary>
private readonly IDatabaseUnitOfWorkProvider _uowProvider;
/// <summary>
/// The repository factory.
/// </summary>
private readonly RepositoryFactory _repositoryFactory;
/// <summary>
/// The product variant service.
/// </summary>
private readonly IProductVariantService _productVariantService;
/// <summary>
/// Initializes a new instance of the <see cref="ProductService"/> class.
/// </summary>
public ProductService()
: this(new RepositoryFactory(), new ProductVariantService())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ProductService"/> class.
/// </summary>
/// <param name="repositoryFactory">
/// The repository factory.
/// </param>
/// <param name="productVariantService">
/// The product variant service.
/// </param>
public ProductService(RepositoryFactory repositoryFactory, IProductVariantService productVariantService)
: this(new PetaPocoUnitOfWorkProvider(), repositoryFactory, productVariantService)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ProductService"/> class.
/// </summary>
/// <param name="provider">
/// The provider.
/// </param>
/// <param name="repositoryFactory">
/// The repository factory.
/// </param>
/// <param name="productVariantService">
/// The product variant service.
/// </param>
public ProductService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, IProductVariantService productVariantService)
{
Mandate.ParameterNotNull(provider, "provider");
Mandate.ParameterNotNull(repositoryFactory, "repositoryFactory");
Mandate.ParameterNotNull(productVariantService, "productVariantService");
_uowProvider = provider;
_repositoryFactory = repositoryFactory;
// included the ProductVariantService so that events will trigger if variants
// need to be deleted due to a product save removing attributes
_productVariantService = productVariantService;
}
#region Event Handlers
/// <summary>
/// Occurs after Create
/// </summary>
public static event TypedEventHandler<IProductService, Events.NewEventArgs<IProduct>> Creating;
/// <summary>
/// Occurs after Create
/// </summary>
public static event TypedEventHandler<IProductService, Events.NewEventArgs<IProduct>> Created;
/// <summary>
/// Occurs before Save
/// </summary>
public static event TypedEventHandler<IProductService, SaveEventArgs<IProduct>> Saving;
/// <summary>
/// Occurs after Save
/// </summary>
public static event TypedEventHandler<IProductService, SaveEventArgs<IProduct>> Saved;
/// <summary>
/// Occurs before Delete
/// </summary>
public static event TypedEventHandler<IProductService, DeleteEventArgs<IProduct>> Deleting;
/// <summary>
/// Occurs after Delete
/// </summary>
public static event TypedEventHandler<IProductService, DeleteEventArgs<IProduct>> Deleted;
#endregion
/// <summary>
/// Creates a Product without saving it to the database
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="sku">
/// The SKU.
/// </param>
/// <param name="price">
/// The price.
/// </param>
/// <returns>
/// The <see cref="IProduct"/>.
/// </returns>
public IProduct CreateProduct(string name, string sku, decimal price)
{
var templateVariant = new ProductVariant(name, sku, price);
var product = new Product(templateVariant);
if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs<IProduct>(product), this))
{
product.WasCancelled = true;
return product;
}
Created.RaiseEvent(new Events.NewEventArgs<IProduct>(product), this);
return product;
}
/// <summary>
/// Creates and saves a <see cref="IProduct"/> to the database
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <param name="sku">
/// The SKU.
/// </param>
/// <param name="price">
/// The price.
/// </param>
/// <returns>
/// The <see cref="IProduct"/>.
/// </returns>
public IProduct CreateProductWithKey(string name, string sku, decimal price)
{
var templateVariant = new ProductVariant(name, sku, price);
var product = new Product(templateVariant);
if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs<IProduct>(product), this))
{
product.WasCancelled = true;
return product;
}
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateProductRepository(uow))
{
repository.AddOrUpdate(product);
uow.Commit();
}
}
Created.RaiseEvent(new Events.NewEventArgs<IProduct>(product), this);
return product;
}
/// <summary>
/// Saves a single <see cref="IProduct"/> object
/// </summary>
/// <param name="product">The <see cref="IProductVariant"/> to save</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events.</param>
public void Save(IProduct product, bool raiseEvents = true)
{
if (raiseEvents)
{
if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IProduct>(product), this))
{
((Product)product).WasCancelled = true;
return;
}
}
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateProductRepository(uow))
{
repository.AddOrUpdate(product);
uow.Commit();
}
// Synchronize product variants
this.EnsureVariants(product);
}
if (raiseEvents) Saved.RaiseEvent(new SaveEventArgs<IProduct>(product), this);
// verify that all variants of this product still have attributes - or delete them
_productVariantService.EnsureProductVariantsHaveAttributes(product);
// save any remaining variants changes in the variants collection
if (product.ProductVariants.Any())
_productVariantService.Save(product.ProductVariants);
}
/// <summary>
/// Saves a collection of <see cref="IProduct"/> objects.
/// </summary>
/// <param name="productList">Collection of <see cref="ProductVariant"/> to save</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param>
public void Save(IEnumerable<IProduct> productList, bool raiseEvents = true)
{
var productArray = productList as IProduct[] ?? productList.ToArray();
if (raiseEvents) Saving.RaiseEvent(new SaveEventArgs<IProduct>(productArray), this);
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateProductRepository(uow))
{
foreach (var product in productArray)
{
repository.AddOrUpdate(product);
}
uow.Commit();
}
// Synchronize the products array
EnsureVariants(productArray);
}
if (raiseEvents) Saved.RaiseEvent(new SaveEventArgs<IProduct>(productArray), this);
// verify that all variants of these products still have attributes - or delete them
_productVariantService.EnsureProductVariantsHaveAttributes(productArray);
}
/// <summary>
/// Deletes a single <see cref="IProduct"/> object
/// </summary>
/// <param name="product">The <see cref="IProduct"/> to delete</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param>
public void Delete(IProduct product, bool raiseEvents = true)
{
if (raiseEvents)
{
if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IProduct>(product), this))
{
((Product)product).WasCancelled = true;
return;
}
}
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateProductRepository(uow))
{
repository.Delete(product);
uow.Commit();
}
}
if (raiseEvents) Deleted.RaiseEvent(new DeleteEventArgs<IProduct>(product), this);
}
/// <summary>
/// Deletes a collection <see cref="IProduct"/> objects
/// </summary>
/// <param name="productList">Collection of <see cref="IProduct"/> to delete</param>
/// <param name="raiseEvents">Optional boolean indicating whether or not to raise events</param>
public void Delete(IEnumerable<IProduct> productList, bool raiseEvents = true)
{
var productArray = productList as IProduct[] ?? productList.ToArray();
if (raiseEvents) Deleting.RaiseEvent(new DeleteEventArgs<IProduct>(productArray), this);
using (new WriteLock(Locker))
{
var uow = _uowProvider.GetUnitOfWork();
using (var repository = _repositoryFactory.CreateProductRepository(uow))
{
foreach (var product in productArray)
{
repository.Delete(product);
}
uow.Commit();
}
}
if (raiseEvents) Deleted.RaiseEvent(new DeleteEventArgs<IProduct>(productArray), this);
}
/// <summary>
/// Gets a Product by its unique id - pk
/// </summary>
/// <param name="key">Guid key for the Product</param>
/// <returns><see cref="IProductVariant"/></returns>
public override IProduct GetByKey(Guid key)
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Get(key);
}
}
/// <summary>
/// Gets a page of <see cref="IProduct"/>
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="Page{IProduct}"/>.
/// </returns>
public override Page<IProduct> GetPage(long page, long itemsPerPage, string sortBy = "", SortDirection sortDirection = SortDirection.Descending)
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetPage(page, itemsPerPage, null, ValidateSortByField(sortBy), sortDirection);
}
}
/// <summary>
/// The count.
/// </summary>
/// <param name="query">
/// The query.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
internal override int Count(IQuery<IProduct> query)
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Count(query);
}
}
/// <summary>
/// The count.
/// </summary>
/// <param name="query">
/// The query.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
internal int Count(IQuery<IProductVariant> query)
{
using (var repository = _repositoryFactory.CreateProductVariantRepository(_uowProvider.GetUnitOfWork()))
{
return repository.Count(query);
}
}
/// <summary>
/// Gets a page of product keys
/// </summary>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="Page{Guid}"/>.
/// </returns>
internal override Page<Guid> GetPagedKeys(long page, long itemsPerPage, string sortBy = "", SortDirection sortDirection = SortDirection.Descending)
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetPagedKeys(page, itemsPerPage, null, ValidateSortByField(sortBy), sortDirection);
}
}
/// <summary>
/// The get paged keys.
/// </summary>
/// <param name="searchTerm">
/// The search term.
/// </param>
/// <param name="page">
/// The page.
/// </param>
/// <param name="itemsPerPage">
/// The items per page.
/// </param>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <param name="sortDirection">
/// The sort direction.
/// </param>
/// <returns>
/// The <see cref="Page{Guid}"/>.
/// </returns>
internal Page<Guid> GetPagedKeys(string searchTerm, long page, long itemsPerPage, string sortBy = "", SortDirection sortDirection = SortDirection.Descending)
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.SearchKeys(searchTerm, page, itemsPerPage, ValidateSortByField(sortBy), sortDirection);
}
}
/// <summary>
/// The validate sort by field.
/// </summary>
/// <param name="sortBy">
/// The sort by.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
protected override string ValidateSortByField(string sortBy)
{
return ValidSortFields.Contains(sortBy.ToLowerInvariant()) ? sortBy : "name";
}
/// <summary>
/// Gets a list of Product give a list of unique keys
/// </summary>
/// <param name="keys">
/// List of unique keys
/// </param>
/// <returns>
/// A collection of <see cref="IProduct"/>.
/// </returns>
public IEnumerable<IProduct> GetByKeys(IEnumerable<Guid> keys)
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAll(keys.ToArray());
}
}
/// <summary>
/// Gets a <see cref="IProductVariant"/> by it's key.
/// </summary>
/// <param name="productVariantKey">
/// The product variant key.
/// </param>
/// <returns>
/// The <see cref="IProductVariant"/>.
/// </returns>
public IProductVariant GetProductVariantByKey(Guid productVariantKey)
{
return _productVariantService.GetByKey(productVariantKey);
}
/// <summary>
/// The get product variants by product key.
/// </summary>
/// <param name="productKey">
/// The product key.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IProductVariant}"/>.
/// </returns>
public IEnumerable<IProductVariant> GetProductVariantsByProductKey(Guid productKey)
{
return _productVariantService.GetByProductKey(productKey);
}
/// <summary>
/// Returns the count of all products
/// </summary>
/// <returns>
/// The total product count.
/// </returns>
[Obsolete("Only used in ProductQuery")]
public int ProductsCount()
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
var query = Persistence.Querying.Query<IProduct>.Builder.Where(x => x.Key != Guid.Empty);
return repository.Count(query);
}
}
/// <summary>
/// True/false indicating whether or not a SKU is already exists in the database
/// </summary>
/// <param name="sku">
/// The SKU to be tested
/// </param>
/// <returns>
/// A value indicating whether or not a SKU exists
/// </returns>
public bool SkuExists(string sku)
{
return _productVariantService.SkuExists(sku);
}
/// <summary>
/// Gets all the products
/// </summary>
/// <returns>
/// A collection of all <see cref="IProduct"/>.
/// </returns>
public IEnumerable<IProduct> GetAll()
{
using (var repository = _repositoryFactory.CreateProductRepository(_uowProvider.GetUnitOfWork()))
{
return repository.GetAll();
}
}
/// <summary>
/// Ensures that variants are created for each option and option choice combination
/// </summary>
/// <param name="products">
/// The collection of products.
/// </param>
private void EnsureVariants(IEnumerable<IProduct> products)
{
products.ForEach(this.EnsureVariants);
}
/// <summary>
/// Ensures that variants are created for each option and option choice combination
/// </summary>
/// <param name="product">
/// The product.
/// </param>
private void EnsureVariants(IProduct product)
{
// Create the product varaints
if (!product.ProductOptions.Any()) return;
var attributeLists = product.GetPossibleProductAttributeCombinations().ToArray();
if (attributeLists.Any())
{
// delete any variants that don't have the correct number of attributes
var attCount = attributeLists.First().Count();
var removers = product.ProductVariants.Where(x => x.Attributes.Count() != attCount);
foreach (var remover in removers.ToArray())
{
product.ProductVariants.Remove(remover.Sku);
_productVariantService.Delete(remover);
}
}
foreach (var list in attributeLists)
{
// Check to see if the variant exists
var productAttributes = list as IProductAttribute[] ?? list.ToArray();
if (product.GetProductVariantForPurchase(productAttributes) != null) continue;
var variant = this._productVariantService.CreateProductVariantWithKey(product, productAttributes.ToProductAttributeCollection(), false);
foreach (var inv in product.CatalogInventories)
{
variant.AddToCatalogInventory(inv.CatalogKey);
_productVariantService.Save(variant, false);
}
}
}
}
}