source: StockMaster/Services/SaleService.cs

main
Last change on this file was dfe03b8, checked in by Ceyda <ceyda.huseini@…>, 2 days ago

Initialize StockMaster project

  • Property mode set to 100644
File size: 2.9 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Threading.Tasks;
5using StockMaster.Data;
6using StockMaster.Models;
7using Microsoft.EntityFrameworkCore;
8
9namespace StockMaster.Services
10{
11 public class SaleService : ISaleService
12 {
13 private readonly StockDbContext _context;
14
15 public SaleService(StockDbContext context)
16 {
17 _context = context;
18 }
19
20 public async Task<List<Sale>> GetAllSalesAsync()
21 {
22 return await _context.Sales
23 .Include(s => s.Customer)
24 .Include(s => s.User)
25 .Include(s => s.Warehouse)
26 .Include(s => s.SaleItems)
27 .ThenInclude(si => si.Product)
28 .OrderByDescending(s => s.DateTime)
29 .ToListAsync();
30 }
31
32 public async Task<Sale> GetSaleByIdAsync(int id)
33 {
34 return await _context.Sales
35 .Include(s => s.Customer)
36 .Include(s => s.User)
37 .Include(s => s.Warehouse)
38 .Include(s => s.SaleItems)
39 .ThenInclude(si => si.Product)
40 .FirstOrDefaultAsync(s => s.SaleId == id);
41 }
42
43
44
45 public async Task<bool> CreateSaleAsync(Sale sale)
46 {
47 using var transaction = await _context.Database.BeginTransactionAsync();
48 try
49 {
50 _context.Sales.Add(sale);
51 await _context.SaveChangesAsync();
52
53 foreach (var item in sale.SaleItems)
54 {
55 var stock = await _context.WarehouseStocks
56 .FirstOrDefaultAsync(ws => ws.WarehouseId == sale.WarehouseId
57 && ws.ProductId == item.ProductId);
58
59 if (stock == null || stock.QuantityOnHand < item.Quantity)
60 {
61 throw new Exception("Insufficient Stock");
62 }
63
64 stock.QuantityOnHand -= item.Quantity;
65 stock.LastUpdated = DateTime.Now;
66 }
67
68 await _context.SaveChangesAsync();
69 await transaction.CommitAsync();
70
71 return true;
72 }
73 catch
74 {
75 await transaction.RollbackAsync();
76 return false;
77 }
78 }
79
80 public async Task<decimal> GetTotalSalesAmountAsync(DateTime? startDate = null, DateTime? endDate = null)
81 {
82 var query = _context.Sales.AsQueryable();
83
84 if (startDate.HasValue)
85 query = query.Where(s => s.DateTime >= startDate.Value);
86
87 if (endDate.HasValue)
88 query = query.Where(s => s.DateTime <= endDate.Value);
89
90 return await query.SumAsync(s => (decimal?)s.TotalAmount) ?? 0;
91 }
92 }
93}
Note: See TracBrowser for help on using the repository browser.