source: StockMaster/Services/PurchaseOrderService.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: 3.4 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 PurchaseOrderService : IPurchaseOrderService
12 {
13 private readonly StockDbContext _context;
14
15 public PurchaseOrderService(StockDbContext context)
16 {
17 _context = context;
18 }
19
20 public async Task<List<PurchaseOrder>> GetAllPurchaseOrdersAsync()
21 {
22 return await _context.PurchaseOrders
23 .Include(po => po.Supplier)
24 .Include(po => po.Warehouse)
25 .Include(po => po.PurchaseOrderItems)
26 .ThenInclude(poi => poi.Product)
27 .OrderByDescending(po => po.OrderDate)
28 .ToListAsync();
29 }
30
31 public async Task<PurchaseOrder> GetPurchaseOrderByIdAsync(int id)
32 {
33 return await _context.PurchaseOrders
34 .Include(po => po.Supplier)
35 .Include(po => po.Warehouse)
36 .Include(po => po.PurchaseOrderItems)
37 .ThenInclude(poi => poi.Product)
38 .FirstOrDefaultAsync(po => po.PoId == id);
39 }
40
41
42
43 public async Task<bool> CreatePurchaseOrderAsync(PurchaseOrder po)
44 {
45 using var transaction = await _context.Database.BeginTransactionAsync();
46 try
47 {
48 _context.PurchaseOrders.Add(po);
49 await _context.SaveChangesAsync();
50
51 await transaction.CommitAsync();
52 return true;
53 }
54 catch
55 {
56 await transaction.RollbackAsync();
57 return false;
58 }
59 }
60
61 public async Task<bool> ReceivePurchaseOrderAsync(int poId)
62 {
63 using var transaction = await _context.Database.BeginTransactionAsync();
64 try
65 {
66 var po = await GetPurchaseOrderByIdAsync(poId);
67 if (po == null || po.Status == "Received")
68 return false;
69
70
71 foreach (var item in po.PurchaseOrderItems)
72 {
73 var stock = await _context.WarehouseStocks
74 .FirstOrDefaultAsync(ws => ws.WarehouseId == po.WarehouseId && ws.ProductId == item.ProductId);
75
76 if (stock == null)
77 {
78 stock = new WarehouseStock
79 {
80 WarehouseId = po.WarehouseId,
81 ProductId = item.ProductId,
82 QuantityOnHand = item.Quantity
83 };
84 _context.WarehouseStocks.Add(stock);
85 }
86 else
87 {
88 stock.QuantityOnHand += item.Quantity;
89 }
90
91 stock.LastUpdated = DateTime.Now;
92 item.ReceivedQuantity = item.Quantity;
93 }
94
95 po.Status = "Received";
96 po.ActualDeliveryDate = DateTime.Now.Date;
97
98 await _context.SaveChangesAsync();
99 await transaction.CommitAsync();
100 return true;
101 }
102 catch
103 {
104 await transaction.RollbackAsync();
105 return false;
106 }
107 }
108 }
109}
Note: See TracBrowser for help on using the repository browser.