/
OrderService.groovy
335 lines (287 loc) · 10.1 KB
/
OrderService.groovy
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
/**
* Copyright (c) 2012 Partners In Health. All rights reserved.
* The use and distribution terms for this software are covered by the
* Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
* which can be found in the file epl-v10.html at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
package org.pih.warehouse.order
import grails.validation.ValidationException
import org.pih.warehouse.core.*
import org.pih.warehouse.inventory.InventoryItem
import org.pih.warehouse.product.Product
import org.pih.warehouse.receiving.Receipt
import org.pih.warehouse.shipping.Shipment
import org.pih.warehouse.shipping.ShipmentException
import org.pih.warehouse.shipping.ShipmentItem
class OrderService {
boolean transactional = true
def productService
def shipmentService;
def identifierService
def inventoryService
List<Order> getOrdersPlacedByLocation(Location orderPlacedBy, Location orderPlacedWith, User orderedBy, OrderStatus status, Date orderedFromDate, Date orderedToDate) {
def orders = Order.withCriteria {
and {
eq("destination", orderPlacedBy)
if (orderPlacedWith) { eq("origin", orderPlacedWith) }
if (status) { eq("status", status) }
if (orderedFromDate) { ge("dateOrdered", orderedFromDate) }
if (orderedToDate) { le("dateOrdered", orderedToDate) }
if (orderedBy) { eq("orderedBy", orderedBy)}
}
}
return orders
}
/**
* @param location
* @return a list of pending incoming order into the given location
*/
List<Order> getIncomingOrders(Location location) {
return Order.findAllByDestination(location);//.findAll { it.isPending() }
}
/**
* @param location
* @return a list of pending outgoing order from the given location
*/
List<Order> getOutgoingOrders(Location location) {
return Order.findAllByOrigin(location);//.findAll { it.isPending() }
}
/**
* @return a list of suppliers
*/
List<Location> getSuppliers() {
def suppliers = []
LocationType supplierType = LocationType.findById(Constants.SUPPLIER_LOCATION_TYPE_ID);
if (supplierType) {
suppliers = Location.findAllByLocationType(supplierType);
}
return suppliers;
}
/**
* @param id an identifier for the order
* @param recipientId
* @return an command object based on an order with the given
*/
OrderCommand getOrder(String id, String recipientId) {
def orderCommand = new OrderCommand();
def orderInstance = Order.get(id)
if (!orderInstance)
throw new Exception("Unable to locate order with ID " + id)
if (recipientId) {
orderCommand.recipient = Person.get(recipientId)
}
orderCommand.origin = Location.get(orderInstance?.origin?.id)
orderCommand.destination = Location.get(orderInstance?.destination?.id)
orderCommand.orderedBy = Person.get(orderInstance?.orderedBy?.id)
orderCommand.dateOrdered = orderInstance?.dateOrdered
orderCommand.order = orderInstance;
orderInstance?.listOrderItems()?.each {
def orderItemCommand = new OrderItemCommand();
orderItemCommand.primary = true;
orderItemCommand.orderItem = it
orderItemCommand.type = it.orderItemType
orderItemCommand.description = it.description
orderItemCommand.productReceived = it.product
orderItemCommand.quantityOrdered = it.quantity;
//orderItemCommand.quantityReceived = it.quantity
orderCommand?.orderItems << orderItemCommand
}
return orderCommand;
}
/**
*
* @param orderCommand
* @return
*/
OrderCommand saveOrderShipment(OrderCommand orderCommand) {
def shipmentInstance = new Shipment()
def shipments = orderCommand?.order?.listShipments();
def numberOfShipments = (shipments) ? shipments?.size() + 1 : 1;
shipmentInstance.name = orderCommand?.order?.description + " - " + "Shipment #" + numberOfShipments
shipmentInstance.shipmentType = orderCommand?.shipmentType;
shipmentInstance.origin = orderCommand?.order?.origin;
shipmentInstance.destination = orderCommand?.order?.destination;
shipmentInstance.expectedDeliveryDate = orderCommand?.deliveredOn;
shipmentInstance.expectedShippingDate = orderCommand?.shippedOn;
orderCommand?.shipment = shipmentInstance
orderCommand?.orderItems.each { orderItemCommand ->
// Ignores any null order items and makes sure that the order item has a product and quantity
if (orderItemCommand && orderItemCommand.productReceived && orderItemCommand?.quantityReceived) {
// Find or create a new inventory item based on the product and lot number provided
def inventoryItem = null
// Need to use new session here otherwise it flushes the current session and causes an error
InventoryItem.withNewSession {
inventoryItem = inventoryService.findOrCreateInventoryItem(orderItemCommand.productReceived, orderItemCommand.lotNumber, orderItemCommand.expirationDate)
}
def shipmentItem = new ShipmentItem();
shipmentItem.lotNumber = orderItemCommand.lotNumber
shipmentItem.expirationDate = orderItemCommand.expirationDate
shipmentItem.product = orderItemCommand.productReceived;
shipmentItem.quantity = orderItemCommand.quantityReceived;
shipmentItem.recipient = orderCommand?.recipient;
shipmentItem.inventoryItem = inventoryItem
shipmentInstance.addToShipmentItems(shipmentItem)
def orderShipment = new OrderShipment(shipmentItem:shipmentItem, orderItem:orderItemCommand?.orderItem)
shipmentItem.addToOrderShipments(orderShipment)
orderItemCommand?.orderItem.addToOrderShipments(orderShipment)
}
}
// Validate the shipment and save it if there are no errors
if (shipmentInstance.validate() && !shipmentInstance.hasErrors()) {
shipmentService.saveShipment(shipmentInstance);
}
else {
log.info("Errors with shipment " + shipmentInstance?.errors)
throw new ShipmentException(message: "Validation errors on shipment ", shipment: shipmentInstance)
}
// Send shipment, receive shipment, and add
if (shipmentInstance) {
// Send shipment
log.info "Sending shipment " + shipmentInstance?.name
shipmentService.sendShipment(shipmentInstance, "", orderCommand?.currentUser, orderCommand?.currentLocation, orderCommand?.shippedOn);
// Receive shipment
log.info "Receiving shipment " + shipmentInstance?.name
Receipt receiptInstance = shipmentService.createReceipt(shipmentInstance, orderCommand?.deliveredOn)
// FIXME
// receiptInstance.validate() && !receiptInstance.hasErrors()
if (!receiptInstance.hasErrors() && receiptInstance.save()) {
shipmentService.receiveShipment(shipmentInstance?.id, null, orderCommand?.currentUser?.id, orderCommand?.currentLocation?.id, true);
}
else {
throw new ShipmentException(message: "Unable to save receipt ", shipment: shipmentInstance)
}
saveOrder(orderCommand?.order);
}
return orderCommand;
}
/**
*
* @param order
* @return
*/
Order saveOrder(Order order) {
// update the status of the order before saving
order.updateStatus()
if (!order.orderNumber) {
order.orderNumber = identifierService.generateOrderIdentifier()
}
if (!order.hasErrors() && order.save()) {
return order;
}
else {
println order.errors
throw new OrderException(message: "Unable to save order due to errors", order: order)
}
}
Order placeOrder(String id) {
def orderInstance = Order.get(id)
if (orderInstance) {
if (orderInstance?.status >= OrderStatus.PLACED) {
orderInstance.errors.rejectValue("status", "order.hasAlreadyBeenPlaced.message")
}
else {
if (orderInstance?.orderItems?.size() > 0) {
orderInstance.status = OrderStatus.PLACED;
if (!orderInstance.hasErrors() && orderInstance.save(flush: true)) {
return orderInstance
}
} else {
orderInstance.errors.rejectValue("orderItems", "order.mustContainAtLeastOneItem.message")
}
}
}
return orderInstance
}
/**
*
* @param location
* @return
*/
List<Order> getPendingOrders(Location location) {
def orders = Order.withCriteria {
or {
eq("origin", location)
eq("destination", location)
}
}
return orders; //.findAll { it.isPending() }
}
/**
*
* @param location
* @param product
* @return
*/
List<OrderItem> getPendingOrderItemsWithProduct(Location location, Product product) {
def orderItems = []
def orders = getPendingOrders(location);
orders.each {
def orderItemList = it.orderItems.findAll { it.product == product }
orderItemList.each { orderItems << it; }
}
return orderItems;
}
/**
*
* @param location
* @return
*/
Map getIncomingQuantityByProduct(Location location, List<Product> products) {
return getQuantityByProduct(getIncomingOrders(location), products)
}
/**
* Returns a list of outgoing quantity per product given location.
* @param location
* @return
*/
Map getOutgoingQuantityByProduct(Location location, List<Product> products) {
return getQuantityByProduct(getOutgoingOrders(location), products)
}
/**
* Returns a map of order quantities per product given a list of orders.
*
* @param orders
* @return
*/
Map getQuantityByProduct(def orders, List<Product> products) {
def quantityMap = [:]
orders.each { order ->
order.orderItems.each { orderItem ->
def product = orderItem.product
if (product) {
if (products.contains(product)) {
def quantity = quantityMap[product];
if (!quantity) quantity = 0;
quantity += orderItem.quantity;
quantityMap[product] = quantity
}
}
}
}
return quantityMap;
}
/**
*
* @param shipments
* @return
*/
Map<EventType, ListCommand> getOrdersByStatus(List orders) {
def orderMap = new TreeMap<OrderStatus, ListCommand>();
OrderStatus.list().each {
orderMap[it] = [];
}
orders.each {
def key = it.status;
def orderList = orderMap[key];
if (!orderList) {
orderList = new ListCommand(category: key, objectList: new ArrayList());
}
orderList.objectList.add(it);
orderMap.put(key, orderList)
}
return orderMap;
}
}