source: WineTrackerFinal/WineTrackerWebApi/Controllers/WarehouseController.cs

main
Last change on this file was 17d6948, checked in by Nikola Mishevski <Nikola.Mishevski@…>, 6 days ago

initial commit WineTracker Project

  • Property mode set to 100644
File size: 9.6 KB
Line 
1using System.Data;
2using Microsoft.AspNetCore.Mvc;
3using Microsoft.EntityFrameworkCore;
4using Npgsql;
5using WineTrackerWebApi.Models.Warehouse;
6using Dapper;
7using WineTrackerWebApi.Models.Address;
8using WineTrackerWebApi.Models.ErrorHandle;
9using WineTrackerWebApi.Helpers;
10
11namespace WineTrackerWebApi.Controllers
12{
13 [Route("api/[controller]")]
14 [ApiController]
15 public class WarehouseController : ControllerBase
16 {
17 private readonly string _connectionString;
18
19 public WarehouseController(IConfiguration configuration)
20 {
21 _connectionString = configuration.GetConnectionString("DefaultConnection");
22 }
23
24 // GET: api/Warehouse
25 [HttpGet]
26 public async Task<ActionResult<IEnumerable<WarehouseDetails>>> GetWarehouse()
27 {
28 using (IDbConnection db = new NpgsqlConnection(_connectionString)) // Use NpgsqlConnection for PostgreSQL
29 {
30 const string query = $@"
31 select
32 w.warehouse_Id as WarehouseId,
33 a.address_Id as AddressId,
34 w.warehouse_name as WarehouseName,
35 concat(a.street,' ', a.building_number, ', ', a.city, ' ', a.postcode) as WarehouseAddress
36 from warehouse w
37 join address a on w.address_id = a.address_id";
38 var warehouses = await db.QueryAsync<WarehouseDetails>(query);
39 return Ok(warehouses);
40 }
41 }
42
43 // GET: api/Warehouse/5
44 [HttpGet("{id}")]
45 public async Task<ActionResult<Warehouse>> GetWarehouse(int id)
46 {
47 using (IDbConnection db = new NpgsqlConnection(_connectionString)) // Use NpgsqlConnection for PostgreSQL
48 {
49 var parameters = new { id = id };
50
51 string query = $@"
52 select
53 w.warehouse_Id as WarehouseId,
54 w.warehouse_name as WarehouseName,
55 a.address_Id as AddressId,
56 a.street as Street,
57 a.building_number as BuildingNumber,
58 a.city as City,
59 a.postcode as PostCode
60 from warehouse w
61 join address a on w.address_id = a.address_id
62 where w.warehouse_id = @id";
63
64 var result = await db.QueryFirstAsync<dynamic>(query, parameters);
65
66 var warehouse = new Warehouse
67 {
68 WarehouseId = result.warehouseid,
69 WarehouseName = result.warehousename,
70 Address = new Address
71 {
72 AddressId = result.addressid,
73 Street = result.street,
74 BuildingNumber = result.buildingnumber,
75 City = result.city,
76 PostCode = result.postcode
77 }
78 };
79
80 return Ok(warehouse);
81 }
82 }
83
84 // PUT: api/Warehouse/5
85 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
86 [HttpPut]
87 public async Task<IActionResult> PutWarehouse([FromBody] Warehouse warehouse)
88 {
89 try
90 {
91 using (IDbConnection db = new NpgsqlConnection(_connectionString)) // Use NpgsqlConnection for PostgreSQL
92 {
93 db.Open();
94 using (var transaction = db.BeginTransaction()) // Start a transaction
95 {
96 var parameters = new
97 {
98 WarehouseName = warehouse.WarehouseName.Trim(),
99 Street = warehouse.Address.Street.Trim(),
100 BuildingNumber = warehouse.Address.BuildingNumber,
101 City = warehouse.Address.City.Trim(),
102 Postcode = warehouse.Address.PostCode.Trim(),
103 WarehouseId = warehouse.WarehouseId,
104 AddressId = warehouse.Address.AddressId,
105 };
106
107 await ModelValidation.DoesEntityExistByName((NpgsqlConnection)db, (NpgsqlTransaction)transaction, "Warehouse", parameters.WarehouseName, entityId: parameters.WarehouseId);
108
109 string updateWarehouse = $@"update warehouse set warehouse_Name = @WarehouseName where warehouse_Id = @WarehouseId";
110 await db.ExecuteAsync(updateWarehouse, parameters, transaction: transaction);
111
112 string updateAddress = $@"
113 update Address
114 set
115 Street = @Street,
116 Building_Number = @BuildingNumber,
117 City = @City,
118 PostCode = @Postcode
119 where Address_Id = @AddressId";
120
121 await db.ExecuteAsync(updateAddress, parameters, transaction: transaction);
122
123 transaction.Commit();
124 return Ok();
125 }
126 }
127 }
128 catch (Exception ex)
129 {
130 return BadRequest(new ErrorHandler { Name = "Error", Description = ex.Message });
131 }
132 }
133
134 // POST: api/Warehouse
135 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
136 [HttpPost]
137 public async Task<IActionResult> PostWarehouse([FromBody] Warehouse warehouse)
138 {
139 try
140 {
141 using (IDbConnection db = new NpgsqlConnection(_connectionString)) // Use NpgsqlConnection for PostgreSQL
142 {
143 db.Open();
144 using (var transaction = db.BeginTransaction()) // Start a transaction
145 {
146 var parameters = new {
147 WarehouseName = warehouse.WarehouseName.Trim(),
148 Street = warehouse.Address.Street.Trim(),
149 BuildingNumber = warehouse.Address.BuildingNumber,
150 City = warehouse.Address.City.Trim(),
151 Postcode = warehouse.Address.PostCode.Trim()
152 };
153
154 await ModelValidation.DoesEntityExistByName((NpgsqlConnection)db, (NpgsqlTransaction)transaction, "Warehouse", parameters.WarehouseName);
155
156 string addAddress = @"INSERT INTO public.Address (Street, Building_Number, City, PostCode) VALUES (@Street, @BuildingNumber, @City, @Postcode) RETURNING Address_Id;";
157 var addressId = await db.ExecuteScalarAsync<int>(addAddress, parameters, transaction: transaction);
158
159 string addWarehouse = $@"INSERT INTO public.Warehouse (Warehouse_Name, Address_Id) VALUES (@WarehouseName, {addressId});";
160 await db.ExecuteAsync(addWarehouse, parameters, transaction: transaction);
161
162 transaction.Commit();
163
164 return Ok();
165 }
166 }
167 }
168 catch (Exception ex)
169 {
170 return BadRequest(new ErrorHandler { Name = "Error", Description = ex.Message });
171 }
172 }
173
174 // DELETE: api/Warehouse/5
175 [HttpDelete("{warehouseId}/{addressId}")]
176 public async Task<IActionResult> DeleteWarehouse(int warehouseId, int addressId)
177 {
178 try
179 {
180 //Check if there is an employee linked to the warehouse we are trying to delete, if so return a message and dont let the user delete the warehouse.
181 using (IDbConnection db = new NpgsqlConnection(_connectionString)) // Use NpgsqlConnection for PostgreSQL
182 {
183 db.Open();
184 using (var transaction = db.BeginTransaction()) // Start a transaction
185 {
186 var parameters = new { warehouseId = warehouseId, addressId = addressId };
187
188 string warehouseLinkToEmployeeQuery = $@"
189 select count(*)
190 from warehouse w
191 join employee e on w.warehouse_id = e.warehouse_id
192 where e.warehouse_id = @warehouseId";
193
194 var isWarehouseLinkedToEmployee = await db.QueryFirstAsync<int>(warehouseLinkToEmployeeQuery, parameters, transaction: transaction);
195 if (isWarehouseLinkedToEmployee > 0)
196 return BadRequest(new ErrorHandler { Name = "Warehouse Cannot Be Deleted", Description = "Warehouse cannot be deleted because it is linked to an employee" });
197
198 string deleteWarehouse = $@"delete from warehouse where warehouse_id = @warehouseId";
199 string deleteAddress = $@"delete from address where address_Id = @addressId";
200
201 await db.ExecuteAsync(deleteWarehouse, parameters, transaction: transaction);
202 await db.ExecuteAsync(deleteAddress, parameters, transaction: transaction);
203
204 transaction.Commit();
205 return Ok();
206 }
207 }
208 }
209 catch (Exception ex)
210 {
211 return BadRequest(new ErrorHandler { Name = "Error", Description = ex.Message });
212 }
213 }
214 }
215}
Note: See TracBrowser for help on using the repository browser.