Subversion Repositories SmartDukaan

Rev

Rev 22689 | Rev 22927 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 22689 Rev 22860
Line 1... Line 1...
1
package com.spice.profitmandi.web.controller;
1
package com.spice.profitmandi.web.controller;
2
 
2
 
3
import java.io.ByteArrayInputStream;
3
import java.io.ByteArrayInputStream;
4
import java.io.ByteArrayOutputStream;
4
import java.io.ByteArrayOutputStream;
5
import java.io.InputStream;
5
import java.io.InputStream;
6
import java.time.DateTimeException;
-
 
7
import java.time.LocalDate;
-
 
8
import java.time.LocalDateTime;
6
import java.time.LocalDateTime;
9
import java.time.format.DateTimeFormatter;
-
 
10
import java.util.ArrayList;
7
import java.util.ArrayList;
11
import java.util.HashMap;
-
 
12
import java.util.HashSet;
8
import java.util.HashSet;
13
import java.util.Iterator;
-
 
14
import java.util.List;
9
import java.util.List;
15
import java.util.Map;
10
import java.util.Map;
16
import java.util.Set;
11
import java.util.Set;
17
 
12
 
18
import javax.servlet.http.HttpServletRequest;
13
import javax.servlet.http.HttpServletRequest;
19
import javax.servlet.http.HttpServletResponse;
14
import javax.servlet.http.HttpServletResponse;
20
 
15
 
21
import org.json.JSONObject;
-
 
22
import org.slf4j.Logger;
16
import org.slf4j.Logger;
23
import org.slf4j.LoggerFactory;
17
import org.slf4j.LoggerFactory;
24
import org.springframework.beans.factory.annotation.Autowired;
18
import org.springframework.beans.factory.annotation.Autowired;
25
import org.springframework.core.io.InputStreamResource;
19
import org.springframework.core.io.InputStreamResource;
26
import org.springframework.http.HttpHeaders;
20
import org.springframework.http.HttpHeaders;
Line 35... Line 29...
35
import org.springframework.web.bind.annotation.RequestMethod;
29
import org.springframework.web.bind.annotation.RequestMethod;
36
import org.springframework.web.bind.annotation.RequestParam;
30
import org.springframework.web.bind.annotation.RequestParam;
37
 
31
 
38
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
32
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
39
import com.spice.profitmandi.common.model.CartFofo;
33
import com.spice.profitmandi.common.model.CartFofo;
40
import com.spice.profitmandi.common.model.CustomAddress;
34
import com.spice.profitmandi.common.model.CreateOrderRequest;
41
import com.spice.profitmandi.common.model.CustomCustomer;
-
 
42
import com.spice.profitmandi.common.model.CustomFofoLineItem;
-
 
43
import com.spice.profitmandi.common.model.CustomFofoOrderItem;
-
 
44
import com.spice.profitmandi.common.model.CustomInsurancePolicy;
-
 
45
import com.spice.profitmandi.common.model.CustomRetailer;
-
 
46
import com.spice.profitmandi.common.model.GadgetCopsInsuranceModel;
-
 
47
import com.spice.profitmandi.common.model.GstRate;
-
 
48
import com.spice.profitmandi.common.model.PdfModel;
35
import com.spice.profitmandi.common.model.PdfModel;
49
import com.spice.profitmandi.common.model.PriceModel;
36
import com.spice.profitmandi.common.model.PriceModel;
50
import com.spice.profitmandi.common.model.ProfitMandiConstants;
37
import com.spice.profitmandi.common.model.ProfitMandiConstants;
51
import com.spice.profitmandi.common.model.SerialNumberDetail;
-
 
52
import com.spice.profitmandi.common.util.InsuranceUtils;
-
 
53
import com.spice.profitmandi.common.util.PdfUtils;
38
import com.spice.profitmandi.common.util.PdfUtils;
54
import com.spice.profitmandi.common.util.StringUtils;
39
import com.spice.profitmandi.common.util.StringUtils;
55
import com.spice.profitmandi.common.util.Utils;
-
 
56
import com.spice.profitmandi.common.web.util.ResponseSender;
40
import com.spice.profitmandi.common.web.util.ResponseSender;
57
import com.spice.profitmandi.dao.entity.catalog.Item;
-
 
58
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
-
 
59
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
41
import com.spice.profitmandi.dao.entity.dtr.InsurancePolicy;
60
import com.spice.profitmandi.dao.entity.dtr.InsuranceProvider;
-
 
61
import com.spice.profitmandi.dao.entity.dtr.PolicyNumberGenerationSequence;
-
 
62
import com.spice.profitmandi.dao.entity.dtr.Retailer;
-
 
63
import com.spice.profitmandi.dao.entity.dtr.User;
-
 
64
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
-
 
65
import com.spice.profitmandi.dao.entity.fofo.Customer;
42
import com.spice.profitmandi.dao.entity.fofo.Customer;
66
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
43
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
67
import com.spice.profitmandi.dao.entity.fofo.FofoItemId;
-
 
68
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
44
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
69
import com.spice.profitmandi.dao.entity.fofo.FofoLineItemSerialNumber;
-
 
70
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
45
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
71
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
-
 
72
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
-
 
73
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
46
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
74
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
-
 
75
import com.spice.profitmandi.dao.entity.user.Address;
-
 
76
import com.spice.profitmandi.dao.entity.user.Counter;
-
 
77
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
-
 
78
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
-
 
79
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
-
 
80
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
47
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
81
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
-
 
82
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
-
 
83
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
-
 
84
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
-
 
85
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
-
 
86
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
-
 
87
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
-
 
88
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
48
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
89
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
49
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
90
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
50
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
91
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemSerialNumberRepository;
-
 
92
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
51
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
93
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
-
 
94
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
-
 
95
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
52
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
96
import com.spice.profitmandi.dao.repository.fofo.ScanRecordRepository;
-
 
97
import com.spice.profitmandi.dao.repository.transaction.OrderRepository;
-
 
98
import com.spice.profitmandi.dao.repository.user.AddressRepository;
-
 
99
import com.spice.profitmandi.dao.repository.user.CounterRepository;
-
 
100
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
-
 
101
import com.spice.profitmandi.service.pricing.PricingService;
53
import com.spice.profitmandi.service.pricing.PricingService;
-
 
54
import com.spice.profitmandi.service.sale.OrderService;
102
import com.spice.profitmandi.web.model.LoginDetails;
55
import com.spice.profitmandi.web.model.LoginDetails;
103
import com.spice.profitmandi.web.request.CreateOrderRequest;
-
 
104
import com.spice.profitmandi.web.request.CustomPaymentOption;
-
 
105
import com.spice.profitmandi.web.response.ItemIdQuantityAvailability;
-
 
106
import com.spice.profitmandi.web.response.Quantity;
-
 
107
import com.spice.profitmandi.web.util.CookiesProcessor;
56
import com.spice.profitmandi.web.util.CookiesProcessor;
108
import com.spice.profitmandi.web.util.MVCResponseSender;
57
import com.spice.profitmandi.web.util.MVCResponseSender;
109
 
58
 
110
import in.shop2020.model.v1.catalog.ItemType;
-
 
111
 
-
 
112
@Controller
59
@Controller
113
@Transactional(rollbackFor=Throwable.class)
60
@Transactional(rollbackFor=Throwable.class)
114
public class OrderController {
61
public class OrderController {
115
 
62
 
116
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
63
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);
117
 
64
 
118
	@Autowired
65
	@Autowired
119
	OrderRepository orderRepository;
-
 
120
 
-
 
121
	@Autowired
-
 
122
	InventoryItemRepository inventoryItemRepository;
-
 
123
 
-
 
124
	@Autowired
-
 
125
	CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
-
 
126
 
-
 
127
	@Autowired
-
 
128
	InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
-
 
129
 
-
 
130
	@Autowired
-
 
131
	CustomerRepository customerRepository;
66
	private CustomerRepository customerRepository;
132
 
-
 
133
	@Autowired
-
 
134
	AddressRepository addressRepository;
-
 
135
 
-
 
136
	@Autowired
-
 
137
	FofoLineItemSerialNumberRepository fofoLineItemSerialNumberRepository;
-
 
138
 
-
 
139
	@Autowired
-
 
140
	FofoLineItemRepository fofoLineItemRepository;
-
 
141
 
-
 
142
	@Autowired
-
 
143
	PaymentOptionRepository paymentOptionRepository;
-
 
144
 
-
 
145
	@Autowired
-
 
146
	ScanRecordRepository scanRecordRepository;
-
 
147
 
-
 
148
	@Autowired
-
 
149
	FofoOrderRepository fofoOrderRepository;
-
 
150
 
67
 
151
	@Autowired
68
	@Autowired
152
	RetailerRepository retailerRepository;
69
	private FofoOrderItemRepository fofoLineItemRepository;
153
 
70
 
154
	@Autowired
71
	@Autowired
155
	UserRepository userRepository;
72
	private PaymentOptionRepository paymentOptionRepository;
156
 
73
 
157
	@Autowired
74
	@Autowired
158
	UserAccountRepository userAccountRepository;
75
	private FofoOrderRepository fofoOrderRepository;
159
 
76
 
160
	@Autowired
77
	@Autowired
161
	RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
-
 
162
 
-
 
163
	@Autowired
-
 
164
	CustomerAddressRepository customerAddressRepository;
78
	private CustomerAddressRepository customerAddressRepository;
165
 
-
 
166
	@Autowired
-
 
167
	ItemRepository itemRepository;
-
 
168
	
-
 
169
	@Autowired
-
 
170
	InsuranceProviderRepository insuranceProviderRepository;
-
 
171
	
79
	
172
	@Autowired
80
	@Autowired
173
	InsurancePolicyRepository insurancePolicyRepository;
81
	private InsurancePolicyRepository insurancePolicyRepository;
174
	
-
 
175
	@Autowired
-
 
176
	PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
-
 
177
 
82
 
178
	@Autowired
83
	@Autowired
179
	MVCResponseSender mvcResponseSender;
84
	private MVCResponseSender mvcResponseSender;
180
 
85
 
181
	@Autowired
86
	@Autowired
182
	CookiesProcessor cookiesProcessor;
87
	private CookiesProcessor cookiesProcessor;
183
	
-
 
184
	@Autowired
-
 
185
	PricingService pricingService;
-
 
186
	
88
	
187
	@Autowired
89
	@Autowired
188
	PrivateDealUserRepository privateDealUserRepository;
90
	private PricingService pricingService;
189
	
91
	
190
	@Autowired
92
	@Autowired
191
	CounterRepository counterRepository;
93
	private OrderService orderService;
192
	
94
	
193
	
95
	
194
	@Autowired
96
	@Autowired
195
	ResponseSender<?> responseSender;
97
	private ResponseSender<?> responseSender;
196
	
98
	
197
    //private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
-
 
198
 
-
 
199
 
-
 
200
	@RequestMapping(value = "/order")
99
	@RequestMapping(value = "/order")
201
	public String orderIndex(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model) throws Exception{
100
	public String orderIndex(HttpServletRequest request, @RequestParam(name = "cartData") String cartData, Model model) throws Throwable{
202
		LoginDetails loginDetails = null;
101
		LoginDetails loginDetails = null;
203
		try {
102
		try {
204
			loginDetails = cookiesProcessor.getCookiesObject(request);
103
			loginDetails = cookiesProcessor.getCookiesObject(request);
205
		} catch (ProfitMandiBusinessException e) {
104
		} catch (ProfitMandiBusinessException e) {
206
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
105
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
207
			return "response";
106
			return "response";
208
		}
107
		}
209
		try{
-
 
210
			JSONObject cartObject = new JSONObject(cartData);
108
		List<CartFofo> cartItems = orderService.cartCheckout(cartData);
211
			Iterator<?> keys = cartObject.keys();
-
 
212
	
-
 
213
			Set<Integer> itemIds = new HashSet<>();
109
		Set<Integer> itemIds = new HashSet<>();
214
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
-
 
215
	
-
 
216
			while( keys.hasNext() ) {
-
 
217
				String key = (String)keys.next();
-
 
218
				if ( cartObject.get(key) instanceof JSONObject ) {
-
 
219
					System.out.println(cartObject.get(key));
-
 
220
				}
-
 
221
				CartFofo cf = new CartFofo();
-
 
222
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
-
 
223
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
-
 
224
				
-
 
225
				if (cf.getQuantity() <= 0){
-
 
226
					continue;
-
 
227
				}
-
 
228
				cartItems.add(cf);
-
 
229
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
-
 
230
			}
-
 
231
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
-
 
232
			if (itemIds.size() > 0){
-
 
233
				List<Item> items = itemRepository.selectByIds(itemIds);
-
 
234
				for (Item i : items){
-
 
235
					itemMap.put(i.getId(), i);
-
 
236
				}
-
 
237
				
-
 
238
			}
-
 
239
			for (CartFofo cf : cartItems){
110
		for(CartFofo cartFofo : cartItems){
240
				Item i = itemMap.get(cf.getItemId());
111
			itemIds.add(cartFofo.getItemId());
241
				if (i == null){
-
 
242
					continue;
-
 
243
				}
-
 
244
				cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
-
 
245
				cf.setItemType(i.getType());
-
 
246
			}
-
 
247
			Map<Integer, PriceModel> mopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, loginDetails.getFofoId());
-
 
248
			LOGGER.info("mopPriceMap {}", mopPriceMap);
-
 
249
			model.addAttribute("cartObj", cartItems);
-
 
250
			model.addAttribute("mopPriceMap", mopPriceMap);
-
 
251
			return "order-index";
-
 
252
		}catch (Exception e) {
-
 
253
			LOGGER.error("Unable to Prepare cart to place order...", e);
-
 
254
			return "error";
-
 
255
		}
112
		}
-
 
113
		Map<Integer, PriceModel> mopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, loginDetails.getFofoId());
-
 
114
		LOGGER.info("mopPriceMap {}", mopPriceMap);
-
 
115
		model.addAttribute("cartObj", cartItems);
-
 
116
		model.addAttribute("mopPriceMap", mopPriceMap);
-
 
117
		return "order-index";
256
	}
118
	}
257
	
119
	
258
	private String getValidName(String name){
-
 
259
		return name!=null?name:"";
-
 
260
	}
-
 
261
	
120
	
262
	@RequestMapping(value = "/insurancePrices", method = RequestMethod.GET)
121
	@RequestMapping(value = "/insurancePrices", method = RequestMethod.GET)
263
	public ResponseEntity<?> getInsurancePrices(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.PRICE) float price){
122
	public ResponseEntity<?> getInsurancePrices(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.PRICE) float price){
264
		LOGGER.info("Request received at url : {}", request.getRequestURI());
123
		LOGGER.info("Request received at url : {}", request.getRequestURI());
265
		try{
124
		try{
Line 281... Line 140...
281
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
140
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
282
			return "response";
141
			return "response";
283
		}
142
		}
284
		try{
143
		try{
285
			FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
144
			FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
286
			List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
145
			List<FofoOrderItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
287
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
146
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
288
			Customer customer  = customerRepository.selectById(fofoOrder.getCustomerId());
147
			Customer customer  = customerRepository.selectById(fofoOrder.getCustomerId());
289
			customerAddress.setPhoneNumber(customer.getMobileNumber());
148
			customerAddress.setPhoneNumber(customer.getMobileNumber());
290
			List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
149
			List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
291
			List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
150
			List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
292
			model.addAttribute("fofoOrder", fofoOrder);
151
			model.addAttribute("fofoOrder", fofoOrder);
293
			model.addAttribute("fofoLineItems", fofoLineItems);
152
			model.addAttribute("fofoLineItems", fofoLineItems);
294
			model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
153
			model.addAttribute("customerBillingAddress", orderService.getBillingAddress(customerAddress));
295
			model.addAttribute("customerBillingAddressObj", customerAddress);
154
			model.addAttribute("customerBillingAddressObj", customerAddress);
296
			model.addAttribute("paymentOptions", paymentOptions);
155
			model.addAttribute("paymentOptions", paymentOptions);
297
			model.addAttribute("insurancePolicies", insurancePolicies);
156
			model.addAttribute("insurancePolicies", insurancePolicies);
298
			return "order-details";
157
			return "order-details";
299
		}catch (Exception e) {
158
		}catch (Exception e) {
Line 312... Line 171...
312
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
171
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
313
			return "response";
172
			return "response";
314
		}
173
		}
315
		try{
174
		try{
316
			FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
175
			FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
317
			List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
176
			List<FofoOrderItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
318
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
177
			CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
319
			List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
178
			List<PaymentOption> paymentOptions = paymentOptionRepository.selectByOrderId(fofoOrder.getId());
320
			List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
179
			List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
321
			model.addAttribute("fofoOrder", fofoOrder);
180
			model.addAttribute("fofoOrder", fofoOrder);
322
			model.addAttribute("fofoLineItems", fofoLineItems);
181
			model.addAttribute("fofoLineItems", fofoLineItems);
323
			model.addAttribute("customerBillingAddress", getBillingAddress(customerAddress));
182
			model.addAttribute("customerBillingAddress", orderService.getBillingAddress(customerAddress));
324
			model.addAttribute("customerBillingAddressObj", customerAddress);
183
			model.addAttribute("customerBillingAddressObj", customerAddress);
325
			model.addAttribute("paymentOptions", paymentOptions);
184
			model.addAttribute("paymentOptions", paymentOptions);
326
			model.addAttribute("insurancePolicies", insurancePolicies);
185
			model.addAttribute("insurancePolicies", insurancePolicies);
327
			return "sale-details";
186
			return "sale-details";
328
		}catch (Exception e) {
187
		}catch (Exception e) {
329
			LOGGER.error("Unble to fetch sale details... ", e);
188
			LOGGER.error("Unble to fetch sale details... ", e);
330
			return "error";
189
			return "error";
331
		}
190
		}
332
	}
191
	}
333
	
192
	
334
	
-
 
335
 
-
 
336
	private String getBillingAddress(CustomerAddress customerAddress) {
-
 
337
		String address = "";
-
 
338
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
-
 
339
			address = address + customerAddress.getLine1();
-
 
340
			address = address + ", ";
-
 
341
		}
-
 
342
 
-
 
343
		if ((customerAddress.getLine2() != null) && (!customerAddress.getLine2().isEmpty())) {
-
 
344
			address = address + customerAddress.getLine2();
-
 
345
			address = address + ", ";
-
 
346
		}
-
 
347
 
-
 
348
		if ((customerAddress.getLandmark() != null) && (!customerAddress.getLandmark().isEmpty())) {
-
 
349
			address = address + customerAddress.getLandmark();
-
 
350
			address = address + ", ";
-
 
351
		}
-
 
352
 
-
 
353
		if ((customerAddress.getCity() != null) && (!customerAddress.getCity().isEmpty())) {
-
 
354
			address = address + customerAddress.getCity();
-
 
355
			address = address + ", ";
-
 
356
		}
-
 
357
 
-
 
358
		if ((customerAddress.getState() != null) && (!customerAddress.getState().isEmpty())) {
-
 
359
			address = address + customerAddress.getState();
-
 
360
		}
-
 
361
 
-
 
362
		if ((customerAddress.getPinCode() != null) && (!customerAddress.getPinCode().isEmpty())) {
-
 
363
			address = address + "- " + customerAddress.getPinCode();
-
 
364
		}
-
 
365
 
-
 
366
		return address;
-
 
367
	}
-
 
368
 
193
 
369
	@RequestMapping(value = "/create-order", method = RequestMethod.POST)
194
	@RequestMapping(value = "/create-order", method = RequestMethod.POST)
370
	public String createOrder(HttpServletRequest request, @RequestBody CreateOrderRequest createOrderRequest, Model model)  throws Throwable{
195
	public String createOrder(HttpServletRequest request, @RequestBody CreateOrderRequest createOrderRequest, Model model)  throws Throwable{
371
		LOGGER.info("request at uri {} body {}", request.getRequestURI(), createOrderRequest);
196
		LOGGER.info("request at uri {} body {}", request.getRequestURI(), createOrderRequest);
372
		LoginDetails fofoDetails;
197
		LoginDetails fofoDetails;
Line 374... Line 199...
374
			fofoDetails = cookiesProcessor.getCookiesObject(request);
199
			fofoDetails = cookiesProcessor.getCookiesObject(request);
375
		} catch (ProfitMandiBusinessException e) {
200
		} catch (ProfitMandiBusinessException e) {
376
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
201
			model.addAttribute("loginResponse", mvcResponseSender.createResponseString("RTLR_1009", false, "/login"));
377
			return "response";
202
			return "response";
378
		}
203
		}
379
		Set<Integer> itemIds = new HashSet<>();
-
 
380
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
-
 
381
		Map<Integer, List<CustomFofoLineItem>> customFofoLineItemMap = new HashMap<>();
-
 
382
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
-
 
383
		
-
 
384
		Map<Integer, Set<String>> itemIdSerialNumbers = new HashMap<>(); // 
-
 
385
		
-
 
386
		float totalAmount = 0;
-
 
387
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
-
 
388
			itemIds.add(customFofoLineItem.getItemId());
-
 
389
			if(!customFofoLineItem.getSerialNumberDetails().isEmpty() && customFofoLineItem.getQuantity() != customFofoLineItem.getSerialNumberDetails().size()){
-
 
390
				itemIdQuantity.put(customFofoLineItem.getItemId(), customFofoLineItem.getQuantity());
-
 
391
			}
-
 
392
			if(!(customFofoLineItem.getSellingPrice() > 0)){
-
 
393
				lineItemPrice.put(customFofoLineItem.getItemId(), customFofoLineItem.getSellingPrice());
-
 
394
			}else{
-
 
395
				totalAmount = totalAmount + customFofoLineItem.getSellingPrice() * customFofoLineItem.getQuantity() - customFofoLineItem.getDiscountAmount();
-
 
396
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
-
 
397
					if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
-
 
398
						totalAmount = totalAmount + serialNumberDetail.getAmount();
-
 
399
					}
-
 
400
				}
-
 
401
			}
-
 
402
			
-
 
403
			List<CustomFofoLineItem> customFofoLineItems;
-
 
404
			if(customFofoLineItemMap.containsKey(customFofoLineItem.getItemId())) {
-
 
405
				customFofoLineItems = customFofoLineItemMap.get(customFofoLineItem.getItemId());
-
 
406
			} else {
-
 
407
				customFofoLineItems = new ArrayList<>();
-
 
408
			}
-
 
409
			customFofoLineItemMap.put(customFofoLineItem.getItemId(), customFofoLineItems);
-
 
410
			
-
 
411
			Set<String> serialNumbers;
-
 
412
			if(!itemIdSerialNumbers.containsKey(customFofoLineItem.getItemId())){
-
 
413
				serialNumbers = new HashSet<>();
-
 
414
			} else {
-
 
415
				serialNumbers = itemIdSerialNumbers.get(customFofoLineItem.getItemId());
-
 
416
			}
-
 
417
			for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
-
 
418
				serialNumbers.add(serialNumberDetail.getSerialNumber());
-
 
419
			}
-
 
420
			itemIdSerialNumbers.put(customFofoLineItem.getItemId(), serialNumbers);
-
 
421
		}
-
 
422
		if(!itemIdQuantity.isEmpty()){
-
 
423
			// if item quantity does not match with given serialnumbers size
-
 
424
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
-
 
425
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "");
-
 
426
			//return "error";
-
 
427
		}
-
 
428
		try{
-
 
429
			this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount);
-
 
430
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
431
			LOGGER.error("Error occured while validating payment options : ", profitMandiBusinessException);
-
 
432
			throw profitMandiBusinessException;
-
 
433
		}
-
 
434
		if(!lineItemPrice.isEmpty()){
-
 
435
			// given fofo line item price must be greater than zero
-
 
436
			LOGGER.error("requested itemId's selling price must greater than 0");
-
 
437
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "");
-
 
438
		}
-
 
439
 
-
 
440
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoDetails.getFofoId(), itemIds);
-
 
441
		if(itemIds.size() != currentInventorySnapshots.size()){
-
 
442
			// error
-
 
443
		}
-
 
444
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
-
 
445
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
-
 
446
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
-
 
447
			List<CustomFofoLineItem> customFofoLineItems = customFofoLineItemMap.get(currentInventorySnapshot.getId().getItemId());
-
 
448
			LOGGER.info("customFofoLineItems "+customFofoLineItems);
-
 
449
			for (CustomFofoLineItem customFofoLineItem : customFofoLineItems) {
-
 
450
				if(customFofoLineItem.getQuantity() > currentInventorySnapshot.getAvailability()){
-
 
451
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
-
 
452
					itemIdQuantityAvailability.setItemId(customFofoLineItem.getItemId());
-
 
453
					Quantity quantity = new Quantity();
-
 
454
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
-
 
455
					quantity.setRequested(customFofoLineItem.getQuantity());
-
 
456
					itemIdQuantityAvailability.setQuantity(quantity);
-
 
457
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
-
 
458
				}
-
 
459
			}
-
 
460
 
-
 
461
		}
-
 
462
 
-
 
463
 
-
 
464
 
-
 
465
		if(!itemIdQuantityAvailabilities.isEmpty()){
-
 
466
			// itemIdQuantity request is not valid
-
 
467
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
-
 
468
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "");
-
 
469
		}
-
 
470
 
-
 
471
 
-
 
472
		Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
-
 
473
		List<Item> items = itemRepository.selectByIds(itemIds);
-
 
474
		for (Item i : items){
-
 
475
			itemMap.put(i.getId(), i);
-
 
476
		}
-
 
477
 
-
 
478
		Set<Integer> nonSerializedItemIds = new HashSet<>();
-
 
479
		Set<String> serialNumbers = new HashSet<>();
-
 
480
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
-
 
481
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
-
 
482
		Map<String, String> serialNumberModelName = new HashMap<>();
-
 
483
		Map<String, String> serialNumberBrand = new HashMap<>();
-
 
484
		for (CustomFofoLineItem cli : createOrderRequest.getFofoLineItems()){
-
 
485
			Item item = itemMap.get(cli.getItemId());
-
 
486
			if (item.getType().equals(ItemType.SERIALIZED)){
-
 
487
				for (SerialNumberDetail serialNumberDetail : cli.getSerialNumberDetails()){
-
 
488
					serialNumbers.add(serialNumberDetail.getSerialNumber());
-
 
489
					if(serialNumberDetail.isInsurance()){
-
 
490
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), cli.getSellingPrice());
-
 
491
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
-
 
492
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(), item.getModelName());
-
 
493
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
-
 
494
					}
-
 
495
				}
-
 
496
			}
-
 
497
			else{
-
 
498
				nonSerializedItemIds.add(cli.getItemId());
-
 
499
			}
-
 
500
		}
-
 
501
 
-
 
502
		Map<Integer, List<InventoryItem>> serializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
-
 
503
		Map<Integer, List<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<Integer, List<InventoryItem>>();
-
 
504
		Map<Integer, List<Float>> itemIdPriceDropAmount = new HashMap<>();
-
 
505
		//Map<String, Float> serialNumberItemPrice = new HashMap<>();
-
 
506
		
-
 
507
		if (!serialNumbers.isEmpty()){
-
 
508
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoDetails.getFofoId(), serialNumbers);
-
 
509
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
-
 
510
			for (InventoryItem it : serializedInventoryItems){
-
 
511
				if (it.getGoodQuantity() == 1){
-
 
512
					if (serializedInventoryItemMap.containsKey(it.getItemId())){
-
 
513
						serializedInventoryItemMap.get(it.getItemId()).add(it);
-
 
514
						itemIdPriceDropAmount.get(it.getItemId()).
-
 
515
						add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
-
 
516
					}
-
 
517
					else{
-
 
518
						ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
-
 
519
						tmp.add(it);
-
 
520
						serializedInventoryItemMap.put(it.getItemId(), tmp);
-
 
521
						ArrayList<Float> priceDropAmouts = new ArrayList<>();
-
 
522
						priceDropAmouts.add(it.getUnitPrice() - (it.getPriceDropAmount()==null?0:it.getPriceDropAmount()));
-
 
523
						itemIdPriceDropAmount.put(it.getItemId(), priceDropAmouts);
-
 
524
					}
-
 
525
				}
-
 
526
			}
-
 
527
		}
-
 
528
 
-
 
529
		if (!nonSerializedItemIds.isEmpty()){
-
 
530
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoDetails.getFofoId(), nonSerializedItemIds);
-
 
531
			for (InventoryItem it : nonSerializedInventoryItems){
-
 
532
				if (it.getGoodQuantity() > 0){
-
 
533
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
-
 
534
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
-
 
535
					}
-
 
536
					else{
-
 
537
						ArrayList<InventoryItem> tmp = new ArrayList<InventoryItem>();
-
 
538
						tmp.add(it);
-
 
539
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
-
 
540
					}
-
 
541
				}
-
 
542
			}
-
 
543
		}
-
 
544
 
-
 
545
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
-
 
546
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
-
 
547
 
-
 
548
		for (Item i : items){
-
 
549
			List<CustomFofoLineItem> customFofoLineItems = customFofoLineItemMap.get(i.getId());
-
 
550
			for(CustomFofoLineItem customFofoLineItem: customFofoLineItems) {
-
 
551
				if (i.getType().equals(ItemType.SERIALIZED)){
-
 
552
					if (customFofoLineItem ==null || customFofoLineItem.getSerialNumberDetails().isEmpty()){
-
 
553
						invalidItemIdSerialNumbers.add(i.getId());
-
 
554
					}
-
 
555
				}
-
 
556
				else{
-
 
557
					if (customFofoLineItem == null || !customFofoLineItem.getSerialNumberDetails().isEmpty()){
-
 
558
						itemIdNonSerializedSerialNumbers.add(i.getId());
-
 
559
					}
-
 
560
				}
-
 
561
			}
-
 
562
		}
-
 
563
 
-
 
564
		if(!invalidItemIdSerialNumbers.isEmpty()){
-
 
565
			LOGGER.error("Invalid itemId's serialNumbers {}", invalidItemIdSerialNumbers);
-
 
566
			// itemId's are serialized you are saying these are not serialized
-
 
567
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "");
-
 
568
		}
-
 
569
 
-
 
570
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
-
 
571
			LOGGER.error("Invalid itemId's serialNumbers {}", itemIdNonSerializedSerialNumbers);
-
 
572
			// itemId's are non serialized you are saying these are serialized
-
 
573
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "");
-
 
574
		}
-
 
575
 
-
 
576
		if(items.size() != itemIds.size()){
-
 
577
			LOGGER.error("Requested ItemIds not found in catalog");
-
 
578
			// invalid itemIds 
-
 
579
			throw new ProfitMandiBusinessException("invalidItemIds", "", "");
-
 
580
		}
-
 
581
 
-
 
582
		Map<Integer, List<InventoryItem>> inventoryItemsToBill = new HashMap<Integer,List<InventoryItem>>();
-
 
583
		Map<Integer, Integer> inventoryItemQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
-
 
584
 
-
 
585
		LOGGER.info("itemMap keys {}", itemMap.keySet());
-
 
586
		//Lets reduce quantity and decide what inventory items to use.
-
 
587
		for (Item i : items){
-
 
588
			if (i.getType().equals(ItemType.SERIALIZED)){
-
 
589
				//TODO:handle null
-
 
590
				if (serializedInventoryItemMap.get(i.getId()) == null || customFofoLineItemMap.get(i.getId()).size() != serializedInventoryItemMap.get(i.getId()).size()){
-
 
591
					//not enough serial numbers
-
 
592
					//LOGGER.info("serialNumbers {}", serialNumbers);
-
 
593
					LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
-
 
594
					LOGGER.info("itemId {}", i.getId());
-
 
595
					LOGGER.error("not enough serial numbers");
-
 
596
					throw new ProfitMandiBusinessException("notEnoughSerialNumbers", "", "");
-
 
597
				}
-
 
598
				List<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(i.getId());
-
 
599
				for (InventoryItem it : inventoryItemsSerializedserialized){
-
 
600
					it.setGoodQuantity(0);
-
 
601
					inventoryItemQuantityUsed.put(it.getId(), 1);
-
 
602
				}
-
 
603
				inventoryItemsToBill.put(i.getId(), inventoryItemsSerializedserialized);
-
 
604
			}
-
 
605
			else{
-
 
606
				List<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(i.getId());
-
 
607
				int quantityToBill = customFofoLineItemMap.get(i.getId()).get(0).getQuantity();
-
 
608
				int totalLeft = quantityToBill;
-
 
609
				List<InventoryItem> inventoryItemsNonSerializedUsed = new ArrayList<InventoryItem>();
-
 
610
				if (inventoryItemsNonSerialized!=null){
-
 
611
					for (InventoryItem it : inventoryItemsNonSerialized){
-
 
612
						if (totalLeft > 0){
-
 
613
							int toUse = Math.min(totalLeft, it.getGoodQuantity());
-
 
614
							inventoryItemQuantityUsed.put(it.getId(), toUse);
-
 
615
							it.setGoodQuantity(it.getGoodQuantity()  - toUse);
-
 
616
							totalLeft = totalLeft - toUse;
-
 
617
							inventoryItemsNonSerializedUsed.add(it);
-
 
618
						}
-
 
619
					}
-
 
620
				}
-
 
621
				
-
 
622
				if (totalLeft > 0){
-
 
623
					//not enough quanity for non-serialized
-
 
624
					LOGGER.error("not enough quanity for non-serialized");
-
 
625
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", "", "");
-
 
626
				}
-
 
627
				inventoryItemsToBill.put(i.getId(), inventoryItemsNonSerializedUsed);
-
 
628
			}
-
 
629
		}
-
 
630
		
-
 
631
		// mop price validation
-
 
632
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
-
 
633
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
-
 
634
		Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoDetails.getFofoId());
-
 
635
		for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
-
 
636
			List<CustomFofoLineItem>customFofoLineItems = customFofoLineItemMap.get(entry.getKey());
-
 
637
			for(CustomFofoLineItem customFofoLineItem : customFofoLineItems) {
-
 
638
				if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoLineItem.getSellingPrice() < entry.getValue().getPrice()){
-
 
639
					invalidMopItemIdPriceMap.put(entry.getKey(), customFofoLineItem.getSellingPrice());
-
 
640
				}
-
 
641
				if(entry.getValue().isMop() && customFofoLineItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
-
 
642
					invalidDiscountAmountMap.put(entry.getKey(), customFofoLineItem.getDiscountAmount());
-
 
643
				}
-
 
644
			}
-
 
645
		}
-
 
646
		
-
 
647
		if(!invalidMopItemIdPriceMap.isEmpty()){
-
 
648
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
-
 
649
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "");
-
 
650
		}
-
 
651
		
-
 
652
		if(!invalidMopItemIdPriceMap.isEmpty()){
-
 
653
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
-
 
654
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "");
-
 
655
		}
-
 
656
 
-
 
657
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
-
 
658
		try{
-
 
659
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoDetails.getFofoId());
-
 
660
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
-
 
661
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
-
 
662
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
663
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
-
 
664
			invoiceNumberGenerationSequence.setFofoId(fofoDetails.getFofoId());
204
		int fofoOrderId = orderService.createOrder(createOrderRequest, fofoDetails.getFofoId());
665
			invoiceNumberGenerationSequence.setPrefix("INVOICE");
-
 
666
			invoiceNumberGenerationSequence.setSequence(1);
-
 
667
			invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
-
 
668
		}
-
 
669
 
-
 
670
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
-
 
671
 
-
 
672
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
-
 
673
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
-
 
674
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "");
-
 
675
		}
-
 
676
 
-
 
677
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
-
 
678
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
-
 
679
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "");
-
 
680
		}
-
 
681
		
-
 
682
		boolean insurance = false;
-
 
683
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
-
 
684
			for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
-
 
685
				if(serialNumberDetail.getAmount() > 0){
-
 
686
					insurance = true;
-
 
687
					break;
-
 
688
				}
-
 
689
			}
-
 
690
		}
-
 
691
		LOGGER.info("insurance [{}] processing ....", insurance);
-
 
692
		
-
 
693
		LocalDate customerDateOfBirth = null;
-
 
694
		if(insurance){
-
 
695
			try{
-
 
696
				customerDateOfBirth = StringUtils.toDate(createOrderRequest.getCustomerDateOfBirth());
-
 
697
			}catch(DateTimeException dateTimeException){
-
 
698
				LOGGER.error("Unable to parse dateOfBirth", dateTimeException);
-
 
699
				throw new ProfitMandiBusinessException("dateOfBirth", createOrderRequest.getCustomerDateOfBirth(), "");
-
 
700
			}
-
 
701
		}
-
 
702
		
-
 
703
		Customer customer = null;
-
 
704
		try{
-
 
705
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
-
 
706
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
707
			LOGGER.error("Error : ", profitMandiBusinessException);
-
 
708
			customer = new Customer();
-
 
709
			customer.setFirstName(customCustomer.getFirstName());
-
 
710
			customer.setLastName(customCustomer.getLastName());
-
 
711
			customer.setEmailId(customCustomer.getEmailId());
-
 
712
			customer.setMobileNumber(customCustomer.getMobileNumber());
-
 
713
			customerRepository.persist(customer);
-
 
714
		}
-
 
715
		//TODO:Check if createOrderRequest contains addressId
-
 
716
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress());
-
 
717
		customerAddress.setCustomerId(customer.getId());
-
 
718
		customerAddressRepository.persist(customerAddress);
-
 
719
 
-
 
720
		FofoOrder fofoOrder = new FofoOrder();
-
 
721
		fofoOrder.setCustomerId(customer.getId());
-
 
722
		fofoOrder.setFofoId(fofoDetails.getFofoId());
-
 
723
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
-
 
724
		fofoOrder.setTotalAmount(totalAmount);
-
 
725
		fofoOrder.setCustomerAddressId(customerAddress.getId());
-
 
726
		fofoOrderRepository.persist(fofoOrder);
-
 
727
 
-
 
728
		for(CustomPaymentOption customPaymentOption : createOrderRequest.getPaymentOptions()){
-
 
729
			PaymentOption paymentOption = new PaymentOption();
-
 
730
			paymentOption.setOrderId(fofoOrder.getId());
-
 
731
			paymentOption.setAmount(customPaymentOption.getAmount());
-
 
732
			paymentOption.setType(customPaymentOption.getType());
-
 
733
			paymentOptionRepository.persist(paymentOption);
-
 
734
		}
-
 
735
 
-
 
736
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoDetails.getFofoId()));
-
 
737
		Map<String, GstRate> gstRateMap = null;
-
 
738
		if(retailerAddress.getState().equals(customerAddress.getState())){
-
 
739
			gstRateMap = Utils.getGstRates(retailerAddress.getState());
-
 
740
		}else{
-
 
741
			LOGGER.info("inter gstRate = true");
-
 
742
			gstRateMap = Utils.getInterGstRates();
-
 
743
		}
-
 
744
		LOGGER.info("gstRateMap {}", gstRateMap);
-
 
745
		for(CustomFofoLineItem customFofoLineItem : createOrderRequest.getFofoLineItems()){
-
 
746
			FofoLineItem fofoLineItem = new FofoLineItem();
-
 
747
			fofoLineItem.setItemId(customFofoLineItem.getItemId());
-
 
748
			fofoLineItem.setQuantity(customFofoLineItem.getQuantity());
-
 
749
			fofoLineItem.setSellingPrice(customFofoLineItem.getSellingPrice());
-
 
750
			fofoLineItem.setOrderId(fofoOrder.getId());
-
 
751
			fofoLineItem.setDp(customFofoLineItem.getSellingPrice());
-
 
752
			fofoLineItem.setDiscount(customFofoLineItem.getDiscountAmount());
-
 
753
			Item item = itemMap.get(customFofoLineItem.getItemId());
-
 
754
			GstRate gstRate = gstRateMap.get(item.getHsnCode());
-
 
755
			fofoLineItem.setIgstRate(gstRate.getIgstRate());
-
 
756
			fofoLineItem.setCgstRate(gstRate.getCgstRate());
-
 
757
			fofoLineItem.setSgstRate(gstRate.getSgstRate());
-
 
758
			fofoLineItem.setHsnCode(gstRate.getHsnCode());
-
 
759
			List<Float> priceDropAmounts = itemIdPriceDropAmount.get(customFofoLineItem.getItemId());
-
 
760
			float cost = 0;
-
 
761
			if (priceDropAmounts!=null){
-
 
762
				for (Float pda : priceDropAmounts){
-
 
763
					cost = cost + pda;
-
 
764
				}
-
 
765
			}
-
 
766
			else{
-
 
767
				cost = customFofoLineItem.getSellingPrice()* customFofoLineItem.getQuantity();
-
 
768
			}
-
 
769
			fofoLineItem.setCost(cost);
-
 
770
			fofoLineItem.setBrand(item.getBrand());
-
 
771
			fofoLineItem.setModelName(item.getModelName());
-
 
772
			fofoLineItem.setModelNumber(item.getModelNumber());
-
 
773
			fofoLineItem.setColor(item.getColor());
-
 
774
			fofoLineItemRepository.persist(fofoLineItem);
-
 
775
			LOGGER.info("\n\n");
-
 
776
			if(!customFofoLineItem.getSerialNumberDetails().isEmpty()){
-
 
777
				for(SerialNumberDetail serialNumberDetail : customFofoLineItem.getSerialNumberDetails()){
-
 
778
					FofoLineItemSerialNumber fofoLineItemSerialNumber = new FofoLineItemSerialNumber();
-
 
779
					fofoLineItemSerialNumber.setFofoLineItemId(fofoLineItem.getId());
-
 
780
					fofoLineItemSerialNumber.setSerialNumber(serialNumberDetail.getSerialNumber());
-
 
781
					fofoLineItemSerialNumberRepository.persist(fofoLineItemSerialNumber);
-
 
782
				}
-
 
783
			}
-
 
784
 
-
 
785
			for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
-
 
786
				FofoItemId fofoItemId = new FofoItemId();
-
 
787
				fofoItemId.setFofoId(fofoDetails.getFofoId());
-
 
788
				fofoItemId.setItemId(fofoLineItem.getItemId());
-
 
789
				if(currentInventorySnapshot.getId().equals(fofoItemId)){
-
 
790
					currentInventorySnapshotRepository.updateAvailabilityByFofoItemId(fofoItemId, currentInventorySnapshot.getAvailability() - customFofoLineItem.getQuantity());
-
 
791
				}
-
 
792
			}
-
 
793
			List<InventoryItem> inventoryItems = inventoryItemsToBill.get(fofoLineItem.getItemId());
-
 
794
			for(InventoryItem inventoryItem : inventoryItems){
-
 
795
				inventoryItem.setLastScanType(ScanType.SALE);
-
 
796
				inventoryItemRepository.persist(inventoryItem);
-
 
797
				ScanRecord scanRecord = new ScanRecord();
-
 
798
				scanRecord.setInventoryItemId(inventoryItem.getId());
-
 
799
				scanRecord.setFofoId(fofoDetails.getFofoId());
-
 
800
				//correct this
-
 
801
				scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
-
 
802
				scanRecord.setType(ScanType.SALE);
-
 
803
				scanRecordRepository.persist(scanRecord);
-
 
804
			}
-
 
805
		}
-
 
806
		
-
 
807
		// insurance calculation is insurance flag is enabled
-
 
808
		if(!insuranceSerialNumberItemPrice.isEmpty()){
-
 
809
			LOGGER.info("Processing for insurence for serialNumbers");
-
 
810
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
-
 
811
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
-
 
812
			
-
 
813
			
-
 
814
			Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
-
 
815
			Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
-
 
816
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
-
 
817
				if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
-
 
818
					invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
-
 
819
				}
-
 
820
				
-
 
821
				if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
-
 
822
					invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
-
 
823
				}
-
 
824
			}
-
 
825
			
-
 
826
			// insurance sale amount can not be lesser than insurance purchase amount
-
 
827
			if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
-
 
828
				LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
-
 
829
				return "error";
-
 
830
			}
-
 
831
			
-
 
832
			if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
-
 
833
				LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
-
 
834
				return "error";
-
 
835
			}
-
 
836
			
-
 
837
			Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
-
 
838
			
-
 
839
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
-
 
840
				int itemId = this.getItemIdFromSerialNumber(itemIdSerialNumbers, entry.getKey());
-
 
841
				LOGGER.info("itemId -->{}", itemId);
-
 
842
				LOGGER.info("itemIdMopPriceMap.get(itemId) -->{}", itemIdMopPriceMap.get(itemId));
-
 
843
				LOGGER.info("itemIdSerialNumbers -->{}", itemIdSerialNumbers);
-
 
844
				LOGGER.info("entry -->{}, {}", entry.getKey(), entry.getValue());
-
 
845
				float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
-
 
846
				float itemSellingPrice = entry.getValue();
-
 
847
				float itemMargin = itemSellingPrice - itemPurchasePrice;
-
 
848
				float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
-
 
849
				float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
-
 
850
				float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
-
 
851
				if(insuranceMargin < (itemMargin * 30 / 100)){
-
 
852
					invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
-
 
853
				}
-
 
854
			}
-
 
855
			
-
 
856
			if(!invalidInsuranceMarginAmount.isEmpty()){
-
 
857
				LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
-
 
858
				return "error";
-
 
859
			}
-
 
860
			
-
 
861
			
-
 
862
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
-
 
863
				PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
-
 
864
				try{
-
 
865
					policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
-
 
866
					policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
-
 
867
					policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
-
 
868
				}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
869
					policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
-
 
870
					policyNumberGenerationSequence.setSequence(1);
-
 
871
					policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
-
 
872
				}
-
 
873
				
-
 
874
				InsurancePolicy insurancePolicy = new InsurancePolicy();
-
 
875
				insurancePolicy.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + invoiceNumberGenerationSequence.getSequence());
-
 
876
				insurancePolicy.setRetailerId(fofoDetails.getFofoId());
-
 
877
				insurancePolicy.setPurchaseAmount(insurancePricesMap.get(entry.getValue()).getDealerPrice());
-
 
878
				insurancePolicy.setSaleAmount(insuranceSerialNumberSaleAmount.get(entry.getKey()));
-
 
879
				insurancePolicy.setSellingPrice(entry.getValue());
-
 
880
				insurancePolicy.setSerialNumber(entry.getKey());
-
 
881
				insurancePolicy.setModelName(serialNumberModelName.get(entry.getKey()));
-
 
882
				insurancePolicy.setBrand(serialNumberBrand.get(entry.getKey()));
-
 
883
				insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence.getSequence()));
-
 
884
				insurancePolicy.setProviderId(insuranceProvider.getId());
-
 
885
				insurancePolicy.setCustomerFirstName(customer.getFirstName());
-
 
886
				insurancePolicy.setCustomerLastName(customer.getLastName());
-
 
887
				insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
-
 
888
				insurancePolicy.setCustomerEmailId(customer.getEmailId());
-
 
889
				insurancePolicy.setCustomerDateOfBirth(customerDateOfBirth);
-
 
890
				insurancePolicy.setCustomerAddress1(customerAddress.getLine1());
-
 
891
				insurancePolicy.setCustomerAddress2(customerAddress.getLine2());
-
 
892
				insurancePolicy.setCustomerCity(customerAddress.getCity());
-
 
893
				insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
-
 
894
				insurancePolicy.setCustomerState(customerAddress.getState());
-
 
895
				
-
 
896
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
-
 
897
				gadgetCopsInsuranceModel.setBrand(serialNumberBrand.get(entry.getKey()));
-
 
898
				gadgetCopsInsuranceModel.setModelName(serialNumberModelName.get(entry.getKey()));
-
 
899
				gadgetCopsInsuranceModel.setSerialNumber(entry.getKey());
-
 
900
				gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
-
 
901
				gadgetCopsInsuranceModel.setCustomerLastName(customer.getLastName());
-
 
902
				gadgetCopsInsuranceModel.setCustomerDateOfBirth(customerDateOfBirth);
-
 
903
				gadgetCopsInsuranceModel.setCustomerMobileNumber(customer.getMobileNumber());
-
 
904
				gadgetCopsInsuranceModel.setCustomerEmailId(customer.getEmailId());
-
 
905
				gadgetCopsInsuranceModel.setCustomerAddress1(customerAddress.getLine1());
-
 
906
				gadgetCopsInsuranceModel.setCustomerAddress2(customerAddress.getLine2());
-
 
907
				gadgetCopsInsuranceModel.setCustomerCity(customerAddress.getCity());
-
 
908
				gadgetCopsInsuranceModel.setCustomerPinCode(customerAddress.getPinCode());
-
 
909
				gadgetCopsInsuranceModel.setCustomerState(customerAddress.getState());
-
 
910
				gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
-
 
911
				gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
-
 
912
				gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
-
 
913
				
-
 
914
				try{
-
 
915
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
-
 
916
					insurancePolicy.setPosted(true);
-
 
917
				}catch (ProfitMandiBusinessException profitMandiBusinessException) {
-
 
918
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
-
 
919
				}
-
 
920
				insurancePolicyRepository.persist(insurancePolicy);
-
 
921
			}
-
 
922
		}
-
 
923
		LOGGER.info("Order has been created successfully...");
205
		LOGGER.info("Order has been created successfully...");
924
		return "redirect:/get-order/?orderId="+fofoOrder.getId();
206
		return "redirect:/get-order/?orderId="+fofoOrderId;
925
	}
-
 
926
	
-
 
927
	private int getItemIdFromSerialNumber(Map<Integer, Set<String>> itemIdSerialNumbers, String serialNumber){
-
 
928
		for(Map.Entry<Integer, Set<String>> entry : itemIdSerialNumbers.entrySet()){
-
 
929
			if(entry.getValue().contains(serialNumber)){
-
 
930
				return entry.getKey();
-
 
931
			}
-
 
932
		}
-
 
933
		return 0;
-
 
934
	}
-
 
935
 
-
 
936
	private CustomerAddress createCustomerAddress(CustomAddress customAddress){
-
 
937
		CustomerAddress customerAddress = new CustomerAddress();
-
 
938
		customerAddress.setName(customAddress.getName());
-
 
939
		customerAddress.setLine1(customAddress.getLine1());
-
 
940
		customerAddress.setLine2(customAddress.getLine2());
-
 
941
		customerAddress.setLandmark(customAddress.getLandmark());
-
 
942
		customerAddress.setCity(customAddress.getCity());
-
 
943
		customerAddress.setPinCode(customAddress.getPinCode());
-
 
944
		customerAddress.setState(customAddress.getState());
-
 
945
		customerAddress.setCountry(customAddress.getCountry());
-
 
946
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
-
 
947
		return customerAddress;
-
 
948
	}
-
 
949
 
-
 
950
	private CustomAddress createCustomAddress(Address address){
-
 
951
		CustomAddress customAddress = new CustomAddress();
-
 
952
		customAddress.setName(address.getName());
-
 
953
		customAddress.setLine1(address.getLine1());
-
 
954
		customAddress.setLine2(address.getLine2());
-
 
955
		customAddress.setLandmark(address.getLandmark());
-
 
956
		customAddress.setCity(address.getCity());
-
 
957
		customAddress.setPinCode(address.getPinCode());
-
 
958
		customAddress.setState(address.getState());
-
 
959
		customAddress.setCountry(address.getCountry());
-
 
960
		customAddress.setPhoneNumber(address.getPhoneNumber());
-
 
961
		return customAddress;
-
 
962
	}
-
 
963
 
-
 
964
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
-
 
965
		CustomAddress customAddress = new CustomAddress();
-
 
966
		customAddress.setName(customerAddress.getName());
-
 
967
		customAddress.setLine1(customerAddress.getLine1());
-
 
968
		customAddress.setLine2(customerAddress.getLine2());
-
 
969
		customAddress.setLandmark(customerAddress.getLandmark());
-
 
970
		customAddress.setCity(customerAddress.getCity());
-
 
971
		customAddress.setPinCode(customerAddress.getPinCode());
-
 
972
		customAddress.setState(customerAddress.getState());
-
 
973
		customAddress.setCountry(customerAddress.getCountry());
-
 
974
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
-
 
975
		return customAddress;
-
 
976
	}
-
 
977
 
-
 
978
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
-
 
979
	{
-
 
980
		float calculatedAmount = 0;
-
 
981
		Set<String> paymentOptionTypes = new HashSet<>();
-
 
982
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
-
 
983
			if(paymentOptionTypes.contains(customPaymentOption.getType().name())){
-
 
984
				throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_TYPE, customPaymentOption.getType().name(), "");
-
 
985
			}else{
-
 
986
				paymentOptionTypes.add(customPaymentOption.getType().name());
-
 
987
				calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
-
 
988
			}
-
 
989
		}
-
 
990
		if(calculatedAmount != totalAmount){
-
 
991
			LOGGER.error("PaymentOptionCalculatedAmount [{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
-
 
992
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "");
-
 
993
		}
-
 
994
	}
207
	}
995
 
208
 
996
 
209
 
997
	@RequestMapping(value = "/generateInvoice")
210
	@RequestMapping(value = "/generateInvoice")
998
	public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws Throwable{
211
	public ResponseEntity<?> generateInvoice(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = ProfitMandiConstants.ORDER_ID) int orderId) throws Throwable{
999
		LOGGER.info("Request received at url {} with params [{}={}] ", request.getRequestURI(), ProfitMandiConstants.ORDER_ID, orderId);
212
		LOGGER.info("Request received at url {} with params [{}={}] ", request.getRequestURI(), ProfitMandiConstants.ORDER_ID, orderId);
1000
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
213
		LoginDetails fofoDetails = cookiesProcessor.getCookiesObject(request);
1001
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoDetails.getFofoId(), orderId);
-
 
1002
		
-
 
1003
		PdfModel pdfModel = new PdfModel();
-
 
1004
		pdfModel.setAuther("profitmandi");
-
 
1005
		pdfModel.setTitle("Retailer Invoice");
-
 
1006
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
-
 
1007
		
214
 
1008
		// insurance calculation
-
 
1009
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerInvoiceNumber(fofoDetails.getFofoId(), fofoOrder.getInvoiceNumber());
-
 
1010
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
-
 
1011
		final float totalInsuranceTaxRate = 18;
-
 
1012
		for(InsurancePolicy insurancePolicy : insurancePolicies){
-
 
1013
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
-
 
1014
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
-
 
1015
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #" + insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
-
 
1016
			customInsurancePolicy.setHsnCode("998716");
-
 
1017
			customInsurancePolicy.setRate(taxableInsurancePrice);
-
 
1018
			customInsurancePolicy.setIgstRate(18);
-
 
1019
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
-
 
1020
			customInsurancePolicy.setCgstRate(18);
-
 
1021
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 /100);
-
 
1022
			customInsurancePolicy.setSgstRate(9);
-
 
1023
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 /100);
-
 
1024
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
-
 
1025
			customInsurancePolicies.add(customInsurancePolicy);
-
 
1026
		}
-
 
1027
		pdfModel.setInsurancePolicies(customInsurancePolicies);
-
 
1028
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
-
 
1029
		CustomCustomer customCustomer = new CustomCustomer();
-
 
1030
		customCustomer.setFirstName(customer.getFirstName());
-
 
1031
		customCustomer.setLastName(customer.getLastName());
-
 
1032
		customCustomer.setEmailId(customer.getEmailId());
-
 
1033
		customCustomer.setMobileNumber(customer.getMobileNumber());
-
 
1034
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
-
 
1035
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
-
 
1036
		pdfModel.setCustomer(customCustomer);
-
 
1037
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
-
 
1038
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
-
 
1039
		
-
 
1040
		Retailer retailer = retailerRepository.selectById(fofoDetails.getFofoId());
215
		PdfModel pdfModel = orderService.getInvoicePdfModel(fofoDetails.getFofoId(), orderId);
1041
		PrivateDealUser privateDealUser = null;
-
 
1042
		try{
-
 
1043
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
-
 
1044
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
-
 
1045
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
-
 
1046
		}
-
 
1047
		
-
 
1048
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
-
 
1049
		CustomRetailer customRetailer = new CustomRetailer();
-
 
1050
		customRetailer.setBusinessName(retailer.getName());
-
 
1051
		customRetailer.setMobileNumber(user.getMobileNumber());
-
 
1052
		customRetailer.setTinNumber(retailer.getNumber());
-
 
1053
		if(privateDealUser == null){
-
 
1054
			customRetailer.setGstNumber(null);
-
 
1055
		}else{
-
 
1056
			if(null != privateDealUser.getCounterId()){
-
 
1057
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
-
 
1058
				customRetailer.setGstNumber(counter.getGstin());
-
 
1059
			}else{
-
 
1060
				customRetailer.setGstNumber(null);
-
 
1061
			}
-
 
1062
		}
-
 
1063
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
-
 
1064
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
-
 
1065
		pdfModel.setRetailer(customRetailer);
-
 
1066
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByOrderId(fofoOrder.getId());
-
 
1067
		
216
		
1068
		Set<CustomFofoOrderItem> customerFofoOrderItems = new HashSet<>();
-
 
1069
		for(FofoLineItem fofoLineItem : fofoLineItems){
-
 
1070
			CustomFofoOrderItem customFofoOrderItem = new CustomFofoOrderItem();
-
 
1071
			float totalTaxRate = fofoLineItem.getIgstRate() + fofoLineItem.getSgstRate() + fofoLineItem.getCgstRate();
-
 
1072
			float taxableSellingPrice = fofoLineItem.getSellingPrice() / (1 + totalTaxRate / 100);
-
 
1073
			float taxableDiscountPrice = fofoLineItem.getDiscount() / (1 + totalTaxRate / 100);
-
 
1074
			
-
 
1075
			customFofoOrderItem.setAmount(fofoLineItem.getQuantity() * (taxableSellingPrice-taxableDiscountPrice));
-
 
1076
			customFofoOrderItem.setDescription(fofoLineItem.getBrand() + " " + fofoLineItem.getModelName() + " " + fofoLineItem.getModelNumber() + "-" + fofoLineItem.getColor() + "\n IMEIS - " + String.join(", ",this.toSerialNumbers(fofoLineItem.getFofoLineItemSerialNumbers())));
-
 
1077
			customFofoOrderItem.setRate(taxableSellingPrice);
-
 
1078
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
-
 
1079
			customFofoOrderItem.setQuantity(fofoLineItem.getQuantity());
-
 
1080
			customFofoOrderItem.setNetAmount((fofoLineItem.getSellingPrice()-fofoLineItem.getDiscount())*fofoLineItem.getQuantity());
-
 
1081
			float igstAmount = (customFofoOrderItem.getAmount() * fofoLineItem.getIgstRate()) / 100;
-
 
1082
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoLineItem.getCgstRate()) / 100;
-
 
1083
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoLineItem.getSgstRate()) / 100;
-
 
1084
			customFofoOrderItem.setIgstRate(fofoLineItem.getIgstRate());
-
 
1085
			customFofoOrderItem.setIgstAmount(igstAmount);
-
 
1086
			customFofoOrderItem.setCgstRate(fofoLineItem.getCgstRate());
-
 
1087
			customFofoOrderItem.setCgstAmount(cgstAmount);
-
 
1088
			customFofoOrderItem.setSgstRate(fofoLineItem.getSgstRate());
-
 
1089
			customFofoOrderItem.setSgstAmount(sgstAmount);
-
 
1090
			customFofoOrderItem.setHsnCode(fofoLineItem.getHsnCode());
-
 
1091
			customerFofoOrderItems.add(customFofoOrderItem);
-
 
1092
		}
-
 
1093
		pdfModel.setOrderItems(customerFofoOrderItems);
-
 
1094
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
217
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
1095
		PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
218
		PdfUtils.generateAndWrite(pdfModel, byteArrayOutputStream);
1096
		//final MediaType mediaType=MediaType.parseMediaType(profilePhotoModel.getContentType().getValue());
-
 
1097
		LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
219
		LOGGER.info("Pdf Stream length {}", byteArrayOutputStream.toByteArray().length);
1098
        final HttpHeaders headers=new HttpHeaders();
220
        final HttpHeaders headers=new HttpHeaders();
1099
        headers.setContentType(MediaType.APPLICATION_PDF);
221
        headers.setContentType(MediaType.APPLICATION_PDF);
1100
        headers.set("Content-disposition", "inline; filename=invoice-" + fofoOrder.getInvoiceNumber() + ".pdf");
222
        headers.set("Content-disposition", "inline; filename=invoice-" + pdfModel.getInvoiceNumber() + ".pdf");
1101
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
223
        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
1102
        final InputStream inputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
224
        final InputStream inputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
1103
        final InputStreamResource inputStreamResource=new InputStreamResource(inputStream);
225
        final InputStreamResource inputStreamResource=new InputStreamResource(inputStream);
1104
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
226
        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
1105
	}
227
	}
1106
 
-
 
1107
	private Set<String> toSerialNumbers(Set<FofoLineItemSerialNumber> fofoLineItemSerialNumbers){
-
 
1108
		Set<String> serialNumbers = new HashSet<>(fofoLineItemSerialNumbers.size());
-
 
1109
		for(FofoLineItemSerialNumber fofoLineItemSerialNumber : fofoLineItemSerialNumbers){
-
 
1110
			serialNumbers.add(fofoLineItemSerialNumber.getSerialNumber());
-
 
1111
		}
-
 
1112
		return serialNumbers;
-
 
1113
	}
-
 
1114
	
228
	
1115
	@RequestMapping(value = "/saleHistory")
229
	@RequestMapping(value = "/saleHistory")
1116
	public String saleHistory(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = ProfitMandiConstants.INVOICE_NUMBER, defaultValue = "") String invoiceNumber, @RequestParam(name = "searchType",defaultValue="") String searchType, Model model) throws Exception{
230
	public String saleHistory(HttpServletRequest request, @RequestParam(name = ProfitMandiConstants.START_TIME, required = false) String startTimeString, @RequestParam(name = ProfitMandiConstants.END_TIME, required = false) String endTimeString, @RequestParam(name = "offset", defaultValue = "0") int offset, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = ProfitMandiConstants.INVOICE_NUMBER, defaultValue = "") String invoiceNumber, @RequestParam(name = "searchType",defaultValue="") String searchType, Model model) throws Exception{
1117
		LoginDetails loginDetails = null;
231
		LoginDetails loginDetails = null;
1118
		try {
232
		try {
Line 1132... Line 246...
1132
				fofoOrders.add(fofoOrder);
246
				fofoOrders.add(fofoOrder);
1133
			} catch (ProfitMandiBusinessException e) {
247
			} catch (ProfitMandiBusinessException e) {
1134
				LOGGER.info("Sale history not found : ", e);
248
				LOGGER.info("Sale history not found : ", e);
1135
			}
249
			}
1136
		}else{
250
		}else{
1137
			fofoOrders = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(),startDateTime, endDateTime, offset, limit);
251
			fofoOrders = fofoOrderRepository.selectByFofoId(loginDetails.getFofoId(), startDateTime, endDateTime, offset, limit);
1138
			countItems = fofoOrderRepository.selectCount(loginDetails.getFofoId(), startDateTime, endDateTime, invoiceNumber, searchType);
252
			countItems = fofoOrderRepository.selectCount(loginDetails.getFofoId(), startDateTime, endDateTime, invoiceNumber, searchType);
1139
		}
253
		}
1140
		
254
		
1141
		model.addAttribute("saleHistories", fofoOrders);
255
		model.addAttribute("saleHistories", fofoOrders);
1142
		model.addAttribute("start", offset + 1);
256
		model.addAttribute("start", offset + 1);