Subversion Repositories SmartDukaan

Rev

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

Rev 23638 Rev 23650
Line 21... Line 21...
21
import org.json.JSONObject;
21
import org.json.JSONObject;
22
import org.springframework.beans.factory.annotation.Autowired;
22
import org.springframework.beans.factory.annotation.Autowired;
23
import org.springframework.stereotype.Component;
23
import org.springframework.stereotype.Component;
24
 
24
 
25
import com.spice.profitmandi.common.ResponseCodeHolder;
25
import com.spice.profitmandi.common.ResponseCodeHolder;
26
import com.spice.profitmandi.common.enumuration.PurchaseReturnStatus;
-
 
27
import com.spice.profitmandi.common.enumuration.SearchType;
26
import com.spice.profitmandi.common.enumuration.SearchType;
28
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
27
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
29
import com.spice.profitmandi.common.model.BadReturnRequest;
28
import com.spice.profitmandi.common.model.BadReturnRequest;
30
import com.spice.profitmandi.common.model.CartFofo;
29
import com.spice.profitmandi.common.model.CartFofo;
31
import com.spice.profitmandi.common.model.CreateOrderRequest;
30
import com.spice.profitmandi.common.model.CreateOrderRequest;
Line 44... Line 43...
44
import com.spice.profitmandi.common.model.PdfModel;
43
import com.spice.profitmandi.common.model.PdfModel;
45
import com.spice.profitmandi.common.model.PriceModel;
44
import com.spice.profitmandi.common.model.PriceModel;
46
import com.spice.profitmandi.common.model.ProfitMandiConstants;
45
import com.spice.profitmandi.common.model.ProfitMandiConstants;
47
import com.spice.profitmandi.common.model.Quantity;
46
import com.spice.profitmandi.common.model.Quantity;
48
import com.spice.profitmandi.common.model.SerialNumberDetail;
47
import com.spice.profitmandi.common.model.SerialNumberDetail;
-
 
48
import com.spice.profitmandi.common.util.FormattingUtils;
49
import com.spice.profitmandi.common.util.InsuranceUtils;
49
import com.spice.profitmandi.common.util.InsuranceUtils;
50
import com.spice.profitmandi.common.util.StringUtils;
50
import com.spice.profitmandi.common.util.StringUtils;
51
import com.spice.profitmandi.common.util.Utils;
51
import com.spice.profitmandi.common.util.Utils;
52
import com.spice.profitmandi.dao.entity.catalog.Item;
52
import com.spice.profitmandi.dao.entity.catalog.Item;
53
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
53
import com.spice.profitmandi.dao.entity.dtr.GadgetCopsInsuranceCalc;
Line 59... Line 59...
59
import com.spice.profitmandi.dao.entity.dtr.Retailer;
59
import com.spice.profitmandi.dao.entity.dtr.Retailer;
60
import com.spice.profitmandi.dao.entity.dtr.User;
60
import com.spice.profitmandi.dao.entity.dtr.User;
61
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
61
import com.spice.profitmandi.dao.entity.fofo.CurrentInventorySnapshot;
62
import com.spice.profitmandi.dao.entity.fofo.Customer;
62
import com.spice.profitmandi.dao.entity.fofo.Customer;
63
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
63
import com.spice.profitmandi.dao.entity.fofo.CustomerAddress;
64
import com.spice.profitmandi.dao.entity.fofo.DebitNote;
64
import com.spice.profitmandi.dao.entity.fofo.CustomerCreditNote;
-
 
65
import com.spice.profitmandi.dao.entity.fofo.CustomerReturnItem;
65
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
66
import com.spice.profitmandi.dao.entity.fofo.FofoLineItem;
66
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
67
import com.spice.profitmandi.dao.entity.fofo.FofoOrder;
67
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
68
import com.spice.profitmandi.dao.entity.fofo.FofoOrderItem;
68
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
69
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
69
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
70
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
70
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
71
import com.spice.profitmandi.dao.entity.fofo.InvoiceNumberGenerationSequence;
71
import com.spice.profitmandi.dao.entity.fofo.PrebookingListing;
72
import com.spice.profitmandi.dao.entity.fofo.PrebookingListing;
72
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;
73
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrder;
73
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrderItem;
74
import com.spice.profitmandi.dao.entity.fofo.PrebookingOrderItem;
74
import com.spice.profitmandi.dao.entity.fofo.PurchaseReturnItem;
-
 
75
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
75
import com.spice.profitmandi.dao.entity.fofo.ScanRecord;
76
import com.spice.profitmandi.dao.entity.user.Address;
76
import com.spice.profitmandi.dao.entity.user.Address;
77
import com.spice.profitmandi.dao.entity.user.Counter;
77
import com.spice.profitmandi.dao.entity.user.Counter;
78
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
78
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
79
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
79
import com.spice.profitmandi.dao.enumuration.dtr.OtpType;
80
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
80
import com.spice.profitmandi.dao.enumuration.dtr.PaymentOptionReferenceType;
-
 
81
import com.spice.profitmandi.dao.enumuration.fofo.ReturnType;
81
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
82
import com.spice.profitmandi.dao.enumuration.fofo.ScanType;
82
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
83
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
83
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
84
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
84
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
85
import com.spice.profitmandi.dao.repository.dtr.InsurancePolicyRepository;
85
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
86
import com.spice.profitmandi.dao.repository.dtr.InsuranceProviderRepository;
Line 88... Line 89...
88
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
89
import com.spice.profitmandi.dao.repository.dtr.PolicyNumberGenerationSequenceRepository;
89
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
90
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
90
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
91
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
91
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
92
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
92
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
93
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
-
 
94
import com.spice.profitmandi.dao.repository.fofo.BadInventorySnapshotRepository;
93
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
95
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
94
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
96
import com.spice.profitmandi.dao.repository.fofo.CustomerAddressRepository;
-
 
97
import com.spice.profitmandi.dao.repository.fofo.CustomerCreditNoteRepository;
95
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
98
import com.spice.profitmandi.dao.repository.fofo.CustomerRepository;
-
 
99
import com.spice.profitmandi.dao.repository.fofo.CustomerReturnItemRepository;
96
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
100
import com.spice.profitmandi.dao.repository.fofo.FofoLineItemRepository;
97
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
101
import com.spice.profitmandi.dao.repository.fofo.FofoOrderItemRepository;
98
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
102
import com.spice.profitmandi.dao.repository.fofo.FofoOrderRepository;
99
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
103
import com.spice.profitmandi.dao.repository.fofo.InventoryItemRepository;
100
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
104
import com.spice.profitmandi.dao.repository.fofo.InvoiceNumberGenerationSequenceRepository;
Line 120... Line 124...
120
 
124
 
121
	private static final Logger LOGGER = LogManager.getLogger(OrderServiceImpl.class);
125
	private static final Logger LOGGER = LogManager.getLogger(OrderServiceImpl.class);
122
 
126
 
123
	@Autowired
127
	@Autowired
124
	private InventoryItemRepository inventoryItemRepository;
128
	private InventoryItemRepository inventoryItemRepository;
125
	
129
 
126
	@Autowired
130
	@Autowired
127
	private WalletService walletService;
131
	private WalletService walletService;
128
 
132
 
129
	@Autowired
133
	@Autowired
130
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
134
	private CurrentInventorySnapshotRepository currentInventorySnapshotRepository;
Line 132... Line 136...
132
	@Autowired
136
	@Autowired
133
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
137
	private InvoiceNumberGenerationSequenceRepository invoiceNumberGenerationSequenceRepository;
134
 
138
 
135
	@Autowired
139
	@Autowired
136
	private CustomerRepository customerRepository;
140
	private CustomerRepository customerRepository;
137
	
141
 
138
	@Autowired
142
	@Autowired
139
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
143
	private PurchaseReturnItemRepository purchaseReturnItemRepository;
140
 
144
 
141
	@Autowired
145
	@Autowired
142
	private AddressRepository addressRepository;
146
	private AddressRepository addressRepository;
Line 144... Line 148...
144
	@Autowired
148
	@Autowired
145
	private FofoLineItemRepository fofoLineItemRepository;
149
	private FofoLineItemRepository fofoLineItemRepository;
146
 
150
 
147
	@Autowired
151
	@Autowired
148
	private FofoOrderItemRepository fofoOrderItemRepository;
152
	private FofoOrderItemRepository fofoOrderItemRepository;
149
	
153
 
150
	@Autowired
154
	@Autowired
151
	private PaymentOptionRepository paymentOptionRepository;
155
	private PaymentOptionRepository paymentOptionRepository;
152
 
156
 
153
	@Autowired
157
	@Autowired
-
 
158
	private CustomerReturnItemRepository customerReturnItemRepository;
-
 
159
 
-
 
160
	@Autowired
154
	private ScanRecordRepository scanRecordRepository;
161
	private ScanRecordRepository scanRecordRepository;
155
 
162
 
156
	@Autowired
163
	@Autowired
157
	private FofoOrderRepository fofoOrderRepository;
164
	private FofoOrderRepository fofoOrderRepository;
158
 
165
 
Line 161... Line 168...
161
 
168
 
162
	@Autowired
169
	@Autowired
163
	private UserRepository userRepository;
170
	private UserRepository userRepository;
164
 
171
 
165
	@Autowired
172
	@Autowired
-
 
173
	private BadInventorySnapshotRepository badInventorySnapshotRepository;
-
 
174
 
-
 
175
	@Autowired
166
	private UserAccountRepository userAccountRepository;
176
	private UserAccountRepository userAccountRepository;
167
 
177
 
168
	@Autowired
178
	@Autowired
169
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
179
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
170
 
180
 
171
	@Autowired
181
	@Autowired
172
	private CustomerAddressRepository customerAddressRepository;
182
	private CustomerAddressRepository customerAddressRepository;
173
 
183
 
174
	@Autowired
184
	@Autowired
175
	private ItemRepository itemRepository;
185
	private ItemRepository itemRepository;
176
	
186
 
177
	@Autowired
187
	@Autowired
178
	private InsuranceProviderRepository insuranceProviderRepository;
188
	private InsuranceProviderRepository insuranceProviderRepository;
179
	
189
 
180
	@Autowired
190
	@Autowired
181
	private InsurancePolicyRepository insurancePolicyRepository;
191
	private InsurancePolicyRepository insurancePolicyRepository;
182
	
192
 
183
	@Autowired
193
	@Autowired
184
	private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
194
	private PolicyNumberGenerationSequenceRepository policyNumberGenerationSequenceRepository;
185
	
195
 
186
	@Autowired
196
	@Autowired
187
	private PricingService pricingService;
197
	private PricingService pricingService;
188
	
198
 
189
	@Autowired
199
	@Autowired
190
	private PrivateDealUserRepository privateDealUserRepository;
200
	private PrivateDealUserRepository privateDealUserRepository;
191
	
201
 
192
	@Autowired
202
	@Autowired
193
	private CounterRepository counterRepository;
203
	private CounterRepository counterRepository;
194
	
204
 
195
	@Autowired
205
	@Autowired
196
	private FofoStoreRepository fofoStoreRepository;
206
	private FofoStoreRepository fofoStoreRepository;
197
	
207
 
198
	@Autowired
208
	@Autowired
199
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
209
	private PaymentOptionTransactionRepository paymentOptionTransactionRepository;
200
	
210
 
201
	@Autowired
211
	@Autowired
202
	private PrebookingListingRepository prebookingListingRepository;
212
	private PrebookingListingRepository prebookingListingRepository;
203
	
213
 
204
	@Autowired
214
	@Autowired
205
	private PrebookingOrderRepository prebookingOrderRepository;
215
	private PrebookingOrderRepository prebookingOrderRepository;
206
	
216
 
207
	@Autowired
217
	@Autowired
208
	private PrebookingOrderItemRepository prebookingOrderItemRepository;
218
	private PrebookingOrderItemRepository prebookingOrderItemRepository;
209
	
219
 
210
	@Autowired
220
	@Autowired
211
	private SchemeService schemeService;
221
	private SchemeService schemeService;
212
	
222
 
213
	@Autowired
223
	@Autowired
214
	private InventoryService inventoryService;
224
	private InventoryService inventoryService;
-
 
225
 
-
 
226
	@Autowired
-
 
227
	private CustomerCreditNoteRepository customerCreditNoteRepository;
215
	
228
 
216
	@Autowired
229
	@Autowired
217
	private OtpRepository otpRepository;
230
	private OtpRepository otpRepository;
218
	
231
 
219
	@Override
232
	@Override
220
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) throws ProfitMandiBusinessException {
233
	public int createOrder(CreateOrderRequest createOrderRequest, int fofoId) throws ProfitMandiBusinessException {
221
		
234
 
222
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
235
		CustomCustomer customCustomer = createOrderRequest.getCustomer();
223
 
236
 
224
		if(!StringUtils.isValidEmailAddress(customCustomer.getEmailId())){
237
		if (!StringUtils.isValidEmailAddress(customCustomer.getEmailId())) {
225
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
238
			LOGGER.error("invalid customer emailId {} ", customCustomer.getEmailId());
226
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(), "VE_1016");
239
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customCustomer.getEmailId(),
-
 
240
					"VE_1016");
227
		}
241
		}
228
 
242
 
229
		if(!StringUtils.isValidMobile(customCustomer.getMobileNumber())){
243
		if (!StringUtils.isValidMobile(customCustomer.getMobileNumber())) {
230
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
244
			LOGGER.error("invalid customer mobileNumber {} ", customCustomer.getMobileNumber());
231
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(), "VE_1071");
245
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customCustomer.getMobileNumber(),
-
 
246
					"VE_1071");
232
		}
247
		}
233
		
248
 
234
		if(!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
249
		if (!StringUtils.isValidGstNumber(customCustomer.getGstNumber())) {
235
			LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
250
			LOGGER.error("invalid customer gstNumber {} ", customCustomer.getGstNumber());
236
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER, customCustomer.getGstNumber(), "VE_1072");
251
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_GST_NUMBER,
-
 
252
					customCustomer.getGstNumber(), "VE_1072");
237
		}
253
		}
238
		
254
 
239
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); //this is for error
255
		Map<Integer, Integer> itemIdQuantity = new HashMap<>(); // this is for error
240
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
256
		Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap = new HashMap<>();
241
		Map<Integer, Float> lineItemPrice = new HashMap<>(); //this is for pricing error
257
		Map<Integer, Float> lineItemPrice = new HashMap<>(); // this is for pricing error
242
		
258
 
243
		Map<Integer, Integer> prebookingOrderItemIdQuantityMap = new HashMap<>(); // for prebooking order adjustment
259
		Map<Integer, Integer> prebookingOrderItemIdQuantityMap = new HashMap<>(); // for prebooking order adjustment
244
		
260
 
245
		float totalAmount = 0;
261
		float totalAmount = 0;
246
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
262
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
247
			//itemIds.add(customFofoOrderItem.getItemId());
263
			// itemIds.add(customFofoOrderItem.getItemId());
248
			if(customFofoOrderItem.isPrebookingOrder()) {
264
			if (customFofoOrderItem.isPrebookingOrder()) {
249
				prebookingOrderItemIdQuantityMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
265
				prebookingOrderItemIdQuantityMap.put(customFofoOrderItem.getItemId(),
-
 
266
						customFofoOrderItem.getQuantity());
250
			}
267
			}
-
 
268
			Set<String> serialNumbers = this
251
			Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
269
					.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
252
			if(!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.size()){
270
			if (!serialNumbers.isEmpty() && customFofoOrderItem.getQuantity() != serialNumbers.size()) {
253
				itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
271
				itemIdQuantity.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
254
			}
272
			}
255
			if(!(customFofoOrderItem.getSellingPrice() > 0)){
273
			if (!(customFofoOrderItem.getSellingPrice() > 0)) {
256
				lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
274
				lineItemPrice.put(customFofoOrderItem.getItemId(), customFofoOrderItem.getSellingPrice());
257
			}else{
275
			} else {
258
				totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
276
				totalAmount = totalAmount + customFofoOrderItem.getSellingPrice() * customFofoOrderItem.getQuantity();
259
				totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
277
				totalAmount = totalAmount - customFofoOrderItem.getDiscountAmount() * customFofoOrderItem.getQuantity();
260
				for(SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
278
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
261
					if(serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0){
279
					if (serialNumberDetail.isInsurance() && serialNumberDetail.getAmount() > 0) {
262
						totalAmount = totalAmount + serialNumberDetail.getAmount();
280
						totalAmount = totalAmount + serialNumberDetail.getAmount();
263
					}
281
					}
264
				}
282
				}
265
			}
283
			}
266
			
284
 
267
			itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
285
			itemIdCustomFofoOrderItemMap.put(customFofoOrderItem.getItemId(), customFofoOrderItem);
268
		}
286
		}
269
		if(!itemIdQuantity.isEmpty()){
287
		if (!itemIdQuantity.isEmpty()) {
270
			// if item quantity does not match with given serialnumbers size
288
			// if item quantity does not match with given serialnumbers size
271
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
289
			LOGGER.error("itemId's quantity should be equal to given serialnumber size {} ", itemIdQuantity);
272
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
290
			throw new ProfitMandiBusinessException("itemIdQuantity", itemIdQuantity, "FFORDR_1001");
273
			//return "error";
291
			// return "error";
274
		}
292
		}
275
		
293
 
276
		List<PrebookingListing> prebookingListings = new ArrayList<>();
294
		List<PrebookingListing> prebookingListings = new ArrayList<>();
277
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap  = new HashMap<>();
295
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
278
		List<PrebookingOrder> prebookingOrders = new ArrayList<>();
296
		List<PrebookingOrder> prebookingOrders = new ArrayList<>();
279
		float prebookingOrdersTotalAmount = 0;
297
		float prebookingOrdersTotalAmount = 0;
280
		if(!prebookingOrderItemIdQuantityMap.isEmpty()) {
298
		if (!prebookingOrderItemIdQuantityMap.isEmpty()) {
-
 
299
			prebookingListings = prebookingListingRepository
281
			prebookingListings = prebookingListingRepository.selectAllByItemIds(prebookingOrderItemIdQuantityMap.keySet());
300
					.selectAllByItemIds(prebookingOrderItemIdQuantityMap.keySet());
282
			itemIdPrebookingListingMap = this.prebookingListingsToItemIdPrebookingListingMap(prebookingListings);
301
			itemIdPrebookingListingMap = this.prebookingListingsToItemIdPrebookingListingMap(prebookingListings);
283
			prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId, customCustomer.getMobileNumber(), prebookingOrderItemIdQuantityMap.keySet());
302
			prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId,
-
 
303
					customCustomer.getMobileNumber(), prebookingOrderItemIdQuantityMap.keySet());
284
			prebookingOrdersTotalAmount = this.calculatePrebookingOrdersAmount(prebookingOrders, prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);
304
			prebookingOrdersTotalAmount = this.calculatePrebookingOrdersAmount(prebookingOrders,
-
 
305
					prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);
285
		}
306
		}
286
		
307
 
287
		this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(), totalAmount - prebookingOrdersTotalAmount);
308
		this.validatePaymentOptionsAndTotalAmount(createOrderRequest.getPaymentOptions(),
-
 
309
				totalAmount - prebookingOrdersTotalAmount);
288
		
310
 
289
		if(!lineItemPrice.isEmpty()){
311
		if (!lineItemPrice.isEmpty()) {
290
			// given fofo line item price must be greater than zero
312
			// given fofo line item price must be greater than zero
291
			LOGGER.error("requested itemId's selling price must greater than 0");
313
			LOGGER.error("requested itemId's selling price must greater than 0");
292
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
314
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PRICE, lineItemPrice, "FFORDR_1002");
293
		}
315
		}
294
 
316
 
295
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
317
		List<CurrentInventorySnapshot> currentInventorySnapshots = currentInventorySnapshotRepository
296
		
-
 
297
		this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
318
				.selectByFofoItemIds(fofoId, itemIdCustomFofoOrderItemMap.keySet());
298
 
319
 
-
 
320
		this.validateCurrentInventorySnapshotQuantities(currentInventorySnapshots, itemIdCustomFofoOrderItemMap);
299
 
321
 
300
		List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
322
		List<Item> items = itemRepository.selectByIds(itemIdCustomFofoOrderItemMap.keySet());
301
		if(items.size() != itemIdCustomFofoOrderItemMap.keySet().size()){
323
		if (items.size() != itemIdCustomFofoOrderItemMap.keySet().size()) {
302
			LOGGER.error("Requested ItemIds not found in catalog");
324
			LOGGER.error("Requested ItemIds not found in catalog");
303
			// invalid itemIds 
325
			// invalid itemIds
304
			throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(), "FFORDR_1003");
326
			throw new ProfitMandiBusinessException("invalidItemIds", itemIdCustomFofoOrderItemMap.keySet(),
-
 
327
					"FFORDR_1003");
305
		}
328
		}
306
		
329
 
307
		Map<Integer, Item>  itemMap = this.toItemMap(items);
330
		Map<Integer, Item> itemMap = this.toItemMap(items);
308
		
331
 
309
		Set<Integer> nonSerializedItemIds = new HashSet<>();
332
		Set<Integer> nonSerializedItemIds = new HashSet<>();
310
		Set<String> serialNumbers = new HashSet<>();
333
		Set<String> serialNumbers = new HashSet<>();
311
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
334
		Map<String, Float> insuranceSerialNumberItemPrice = new HashMap<>();
312
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
335
		Map<String, Float> insuranceSerialNumberSaleAmount = new HashMap<>();
313
		Map<String, String> serialNumberModelName = new HashMap<>();
336
		Map<String, String> serialNumberModelName = new HashMap<>();
314
		Map<String, String> serialNumberBrand = new HashMap<>();
337
		Map<String, String> serialNumberBrand = new HashMap<>();
315
		for (CustomFofoOrderItem customFofoOrderItem: createOrderRequest.getFofoOrderItems()){
338
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
316
			Item item = itemMap.get(customFofoOrderItem.getItemId());
339
			Item item = itemMap.get(customFofoOrderItem.getItemId());
317
			if (item.getType().equals(ItemType.SERIALIZED)){
340
			if (item.getType().equals(ItemType.SERIALIZED)) {
318
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()){
341
				for (SerialNumberDetail serialNumberDetail : customFofoOrderItem.getSerialNumberDetails()) {
319
					serialNumbers.add(serialNumberDetail.getSerialNumber());
342
					serialNumbers.add(serialNumberDetail.getSerialNumber());
320
					if(serialNumberDetail.isInsurance()){
343
					if (serialNumberDetail.isInsurance()) {
321
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(), customFofoOrderItem.getSellingPrice());
344
						insuranceSerialNumberItemPrice.put(serialNumberDetail.getSerialNumber(),
-
 
345
								customFofoOrderItem.getSellingPrice());
322
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(), serialNumberDetail.getAmount());
346
						insuranceSerialNumberSaleAmount.put(serialNumberDetail.getSerialNumber(),
-
 
347
								serialNumberDetail.getAmount());
323
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(), (item.getModelName() + item.getModelNumber()).trim());
348
						serialNumberModelName.put(serialNumberDetail.getSerialNumber(),
-
 
349
								(item.getModelName() + item.getModelNumber()).trim());
324
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
350
						serialNumberBrand.put(serialNumberDetail.getSerialNumber(), item.getBrand());
325
					}
351
					}
326
				}
352
				}
327
			}
-
 
328
			else{
353
			} else {
329
				nonSerializedItemIds.add(customFofoOrderItem.getItemId());
354
				nonSerializedItemIds.add(customFofoOrderItem.getItemId());
330
			}
355
			}
331
		}
356
		}
332
		
357
 
333
		Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
358
		Map<Integer, Set<InventoryItem>> serializedInventoryItemMap = new HashMap<>();
334
		Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
359
		Map<Integer, Set<InventoryItem>> nonSerializedInventoryItemMap = new HashMap<>();
335
		//Map<String, Float> serialNumberItemPrice = new HashMap<>();
360
		// Map<String, Float> serialNumberItemPrice = new HashMap<>();
336
		
361
 
337
		if (!serialNumbers.isEmpty()){
362
		if (!serialNumbers.isEmpty()) {
338
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId, serialNumbers);
363
			List<InventoryItem> serializedInventoryItems = inventoryItemRepository.selectByFofoIdSerialNumbers(fofoId,
-
 
364
					serialNumbers);
339
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
365
			LOGGER.info("serializedInventoryItems {}", serializedInventoryItems);
340
			for (InventoryItem inventoryItem : serializedInventoryItems){
366
			for (InventoryItem inventoryItem : serializedInventoryItems) {
341
				if (inventoryItem.getGoodQuantity() == 1){
367
				if (inventoryItem.getGoodQuantity() == 1) {
342
					if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())){
368
					if (serializedInventoryItemMap.containsKey(inventoryItem.getItemId())) {
343
						serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
369
						serializedInventoryItemMap.get(inventoryItem.getItemId()).add(inventoryItem);
344
					}else{
370
					} else {
345
						Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
371
						Set<InventoryItem> itemIdInventoryItems = new HashSet<>();
346
						itemIdInventoryItems.add(inventoryItem);
372
						itemIdInventoryItems.add(inventoryItem);
347
						serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
373
						serializedInventoryItemMap.put(inventoryItem.getItemId(), itemIdInventoryItems);
348
					}
374
					}
349
				}
375
				}
350
			}
376
			}
351
		}
377
		}
352
 
378
 
353
		if (!nonSerializedItemIds.isEmpty()){
379
		if (!nonSerializedItemIds.isEmpty()) {
354
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId, nonSerializedItemIds);
380
			List<InventoryItem> nonSerializedInventoryItems = inventoryItemRepository.selectByFofoIdItemIds(fofoId,
-
 
381
					nonSerializedItemIds);
355
			LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
382
			LOGGER.info("nonSerializedInventoryItems {}", nonSerializedInventoryItems);
356
			for (InventoryItem it : nonSerializedInventoryItems){
383
			for (InventoryItem it : nonSerializedInventoryItems) {
357
				if (it.getGoodQuantity() > 0){
384
				if (it.getGoodQuantity() > 0) {
358
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())){
385
					if (nonSerializedInventoryItemMap.containsKey(it.getItemId())) {
359
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
386
						nonSerializedInventoryItemMap.get(it.getItemId()).add(it);
360
					}else{
387
					} else {
361
						Set<InventoryItem> tmp = new HashSet<>();
388
						Set<InventoryItem> tmp = new HashSet<>();
362
						tmp.add(it);
389
						tmp.add(it);
363
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
390
						nonSerializedInventoryItemMap.put(it.getItemId(), tmp);
364
					}
391
					}
365
				}
392
				}
366
			}
393
			}
367
		}
394
		}
368
		
395
 
369
		this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);
396
		this.validateItemsSerializedNonSerialized(items, itemIdCustomFofoOrderItemMap);
370
 
397
 
371
		Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
398
		Map<Integer, Set<InventoryItem>> inventoryItemsToBill = new HashMap<>();
372
		Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); //to keep track of inventoryitem quanity used for scan records insertion
399
		Map<Integer, Integer> inventoryItemIdQuantityUsed = new HashMap<>(); // to keep track of inventoryitem quanity
-
 
400
																				// used for scan records insertion
373
 
401
 
374
		LOGGER.info("itemMap keys {}", itemMap.keySet());
402
		LOGGER.info("itemMap keys {}", itemMap.keySet());
375
		//Lets reduce quantity and decide what inventory items to use.
403
		// Lets reduce quantity and decide what inventory items to use.
376
		for (Item item : items){
404
		for (Item item : items) {
377
			if (item.getType().equals(ItemType.SERIALIZED)){
405
			if (item.getType().equals(ItemType.SERIALIZED)) {
378
				//TODO:handle null
406
				// TODO:handle null
-
 
407
				if (serializedInventoryItemMap.get(item.getId()) == null
379
				if (serializedInventoryItemMap.get(item.getId()) == null || itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().size() != serializedInventoryItemMap.get(item.getId()).size()){
408
						|| itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails()
-
 
409
								.size() != serializedInventoryItemMap.get(item.getId()).size()) {
380
					//not enough serial numbers
410
					// not enough serial numbers
381
					//LOGGER.info("serialNumbers {}", serialNumbers);
411
					// LOGGER.info("serialNumbers {}", serialNumbers);
382
					//LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
412
					// LOGGER.info("serializedInventoryItemMap {}", serializedInventoryItemMap);
383
					LOGGER.error("itemId {} => mismatch size of requested serial numbers", item.getId());
413
					LOGGER.error("itemId {} => mismatch size of requested serial numbers", item.getId());
384
					Function<SerialNumberDetail, String> serialNumberDetailToSerialNumberFunction = new Function<SerialNumberDetail, String>() {
414
					Function<SerialNumberDetail, String> serialNumberDetailToSerialNumberFunction = new Function<SerialNumberDetail, String>() {
385
						@Override
415
						@Override
386
						public String apply(SerialNumberDetail serialNumberDetail) {
416
						public String apply(SerialNumberDetail serialNumberDetail) {
387
							return serialNumberDetail.getSerialNumber();
417
							return serialNumberDetail.getSerialNumber();
388
						}
418
						}
389
					};
419
					};
-
 
420
					throw new ProfitMandiBusinessException("invalidSerialNumbers",
390
					throw new ProfitMandiBusinessException("invalidSerialNumbers", itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream().map(serialNumberDetailToSerialNumberFunction).collect(Collectors.toList()), "FFORDR_1004");
421
							itemIdCustomFofoOrderItemMap.get(item.getId()).getSerialNumberDetails().stream()
-
 
422
									.map(serialNumberDetailToSerialNumberFunction).collect(Collectors.toList()),
-
 
423
							"FFORDR_1004");
391
				}
424
				}
392
				Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
425
				Set<InventoryItem> inventoryItemsSerializedserialized = serializedInventoryItemMap.get(item.getId());
393
				for (InventoryItem inventoryItem : inventoryItemsSerializedserialized){
426
				for (InventoryItem inventoryItem : inventoryItemsSerializedserialized) {
394
					inventoryItem.setGoodQuantity(0);
427
					inventoryItem.setGoodQuantity(0);
395
					inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
428
					inventoryItemIdQuantityUsed.put(inventoryItem.getId(), 1);
396
				}
429
				}
397
				inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
430
				inventoryItemsToBill.put(item.getId(), inventoryItemsSerializedserialized);
398
			}
-
 
399
			else{
431
			} else {
400
				Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
432
				Set<InventoryItem> inventoryItemsNonSerialized = nonSerializedInventoryItemMap.get(item.getId());
401
				int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
433
				int quantityToBill = itemIdCustomFofoOrderItemMap.get(item.getId()).getQuantity();
402
				int totalLeft = quantityToBill;
434
				int totalLeft = quantityToBill;
403
				Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
435
				Set<InventoryItem> inventoryItemsNonSerializedUsed = new HashSet<>();
404
				if (inventoryItemsNonSerialized!=null){
436
				if (inventoryItemsNonSerialized != null) {
405
					for (InventoryItem inventoryItem : inventoryItemsNonSerialized){
437
					for (InventoryItem inventoryItem : inventoryItemsNonSerialized) {
406
						if (totalLeft > 0){
438
						if (totalLeft > 0) {
407
							int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
439
							int toUse = Math.min(totalLeft, inventoryItem.getGoodQuantity());
408
							inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
440
							inventoryItemIdQuantityUsed.put(inventoryItem.getId(), toUse);
409
							inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity()  - toUse);
441
							inventoryItem.setGoodQuantity(inventoryItem.getGoodQuantity() - toUse);
410
							totalLeft = totalLeft - toUse;
442
							totalLeft = totalLeft - toUse;
411
							inventoryItemsNonSerializedUsed.add(inventoryItem);
443
							inventoryItemsNonSerializedUsed.add(inventoryItem);
412
						}
444
						}
413
					}
445
					}
414
				}
446
				}
415
				
447
 
416
				if (totalLeft > 0){
448
				if (totalLeft > 0) {
417
					//not enough quanity for non-serialized
449
					// not enough quanity for non-serialized
418
					LOGGER.error("not enough quanity for non-serialized");
450
					LOGGER.error("not enough quanity for non-serialized");
419
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft, "FFORDR_1005");
451
					throw new ProfitMandiBusinessException("notEnoughQuantityForNonSerialized", totalLeft,
-
 
452
							"FFORDR_1005");
420
				}
453
				}
421
				inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
454
				inventoryItemsToBill.put(item.getId(), inventoryItemsNonSerializedUsed);
422
			}
455
			}
423
		}
456
		}
424
		
457
 
-
 
458
		Map<Integer, PriceModel> itemIdMopPriceMap = pricingService
425
		Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
459
				.getPurchasePriceMopPriceNotFound(itemIdCustomFofoOrderItemMap.keySet(), fofoId);
426
		
460
 
427
		this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
461
		this.validateMopPrice(itemIdMopPriceMap, itemIdCustomFofoOrderItemMap);
428
		
462
 
429
		String fofoStoreCode = this.getFofoStoreCode(fofoId);
463
		String fofoStoreCode = this.getFofoStoreCode(fofoId);
430
 
464
 
431
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);
465
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = this
-
 
466
				.createAndGetInvoiceNumberGenerationSequence(fofoId, fofoStoreCode);
432
		
467
 
433
		Customer customer = this.createAndGetCustomer(customCustomer);
468
		Customer customer = this.createAndGetCustomer(customCustomer);
434
		
469
 
435
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());
470
		CustomerAddress customerAddress = this.createCustomerAddress(customCustomer.getAddress(), customer.getId());
436
		
471
 
437
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId, invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
472
		FofoOrder fofoOrder = this.createAndGetFofoOrder(customer.getId(), customCustomer.getGstNumber(), fofoId,
-
 
473
				invoiceNumberGenerationSequence, totalAmount, customerAddress.getId());
438
		
474
 
439
		this.createPaymentOptions(fofoOrder, createOrderRequest.getPaymentOptions());
475
		this.createPaymentOptions(fofoOrder, createOrderRequest.getPaymentOptions());
440
		
476
 
441
		this.processPrebookingOrders(fofoId, fofoOrder.getId(), prebookingOrders, prebookingOrderItemIdQuantityMap, itemIdPrebookingListingMap);
477
		this.processPrebookingOrders(fofoId, fofoOrder.getId(), prebookingOrders, prebookingOrderItemIdQuantityMap,
-
 
478
				itemIdPrebookingListingMap);
442
		
479
 
443
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
480
		int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(fofoId);
444
		
481
 
445
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
482
		Address retailerAddress = addressRepository.selectById(retailerAddressId);
446
		
483
 
447
		Integer stateId = null;
484
		Integer stateId = null;
448
		if(customerAddress.getState().equals(retailerAddress.getState())){
485
		if (customerAddress.getState().equals(retailerAddress.getState())) {
449
			try{
486
			try {
450
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
487
				stateId = Long.valueOf(Utils.getStateInfo(customerAddress.getState()).getId()).intValue();
451
			}catch(Exception e){
488
			} catch (Exception e) {
452
				LOGGER.error("Unable to get state rates");
489
				LOGGER.error("Unable to get state rates");
453
			}
490
			}
454
		}
491
		}
455
		
492
 
456
		for(CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()){
493
		for (CustomFofoOrderItem customFofoOrderItem : createOrderRequest.getFofoOrderItems()) {
457
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(), itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), stateId);
494
			FofoOrderItem fofoOrderItem = this.createAndGetFofoOrderItem(customFofoOrderItem, fofoOrder.getId(),
-
 
495
					itemMap, inventoryItemsToBill.get(customFofoOrderItem.getItemId()), stateId);
458
			
496
 
459
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
497
			Set<InventoryItem> inventoryItems = inventoryItemsToBill.get(customFofoOrderItem.getItemId());
460
			
498
 
461
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
499
			this.createFofoLineItem(fofoOrderItem.getId(), inventoryItems, inventoryItemIdQuantityUsed);
462
			
500
 
463
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(), customFofoOrderItem.getQuantity());
501
			this.updateCurrentInventorySnapshot(currentInventorySnapshots, fofoId, customFofoOrderItem.getItemId(),
-
 
502
					customFofoOrderItem.getQuantity());
464
			
503
 
465
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
504
			this.updateInventoryItemsAndScanRecord(inventoryItems, fofoId, inventoryItemIdQuantityUsed);
466
		}
505
		}
467
		
506
 
468
		// insurance calculation is insurance flag is enabled
507
		// insurance calculation is insurance flag is enabled
469
		if(!insuranceSerialNumberItemPrice.isEmpty()){
508
		if (!insuranceSerialNumberItemPrice.isEmpty()) {
470
			LOGGER.info("Processing for insurence for serialNumbers");
509
			LOGGER.info("Processing for insurence for serialNumbers");
471
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
510
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap = pricingService.getInsurancePrices(
-
 
511
					new HashSet<>(insuranceSerialNumberItemPrice.values()), ProfitMandiConstants.GADGET_COPS);
472
			InsuranceProvider insuranceProvider = insuranceProviderRepository.selectByName(ProfitMandiConstants.GADGET_COPS);
512
			InsuranceProvider insuranceProvider = insuranceProviderRepository
-
 
513
					.selectByName(ProfitMandiConstants.GADGET_COPS);
473
			
514
 
474
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount, insurancePricesMap);
515
			this.validateInsuranceAmount(insuranceSerialNumberItemPrice, insuranceSerialNumberSaleAmount,
-
 
516
					insurancePricesMap);
475
			
517
 
476
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap, itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
518
			this.validateInsuranceMargin(insuranceSerialNumberItemPrice, itemIdCustomFofoOrderItemMap,
-
 
519
					itemIdMopPriceMap, insurancePricesMap, insuranceSerialNumberSaleAmount);
477
			
520
 
-
 
521
			LocalDate customerDateOfBirth = this
478
			LocalDate customerDateOfBirth = this.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
522
					.validateCustomerDateOfBirth(createOrderRequest.getCustomerDateOfBirth());
479
			
523
 
480
			for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
524
			for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
481
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this.createPolicyNumberGenerationSequence();
525
				PolicyNumberGenerationSequence policyNumberGenerationSequence = this
-
 
526
						.createPolicyNumberGenerationSequence();
482
				
527
 
483
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(
528
				InsurancePolicy insurancePolicy = this.createInsurancePolicy(fofoOrder.getInvoiceNumber(), fofoId,
484
						fofoOrder.getInvoiceNumber(), fofoId,
-
 
485
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
529
						insurancePricesMap.get(entry.getValue()).getDealerPrice(),
486
						insuranceSerialNumberSaleAmount.get(entry.getKey()),entry.getValue(),
530
						insuranceSerialNumberSaleAmount.get(entry.getKey()), entry.getValue(), entry.getKey(),
487
						entry.getKey(), serialNumberModelName.get(entry.getKey()),
531
						serialNumberModelName.get(entry.getKey()), serialNumberBrand.get(entry.getKey()),
488
						serialNumberBrand.get(entry.getKey()), policyNumberGenerationSequence.getSequence(),
532
						policyNumberGenerationSequence.getSequence(), insuranceProvider.getId(), customer,
489
						insuranceProvider.getId(), customer, customerDateOfBirth, customerAddress);
533
						customerDateOfBirth, customerAddress);
490
				
534
 
-
 
535
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(
-
 
536
						serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()),
491
				GadgetCopsInsuranceModel gadgetCopsInsuranceModel = this.createGadgetCopsInsuranceModel(serialNumberBrand.get(entry.getKey()), serialNumberModelName.get(entry.getKey()), entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
537
						entry.getKey(), customerDateOfBirth, customer, customerAddress, insurancePolicy);
492
				String walletDescription = "Sale of " + insurancePolicy.getPolicyNumber() 
538
				String walletDescription = "Sale of " + insurancePolicy.getPolicyNumber() + " for "
493
				+ " for " + fofoOrder.getInvoiceNumber();
539
						+ fofoOrder.getInvoiceNumber();
494
				walletService.consumeAmountFromWallet(fofoId, insurancePolicy.getId(), 
540
				walletService.consumeAmountFromWallet(fofoId, insurancePolicy.getId(),
495
						WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getPurchaseAmount());
541
						WalletReferenceType.DAMAGE_PROTECTION, walletDescription, insurancePolicy.getPurchaseAmount());
496
				
542
 
497
				try{
543
				try {
498
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
544
					InsuranceUtils.submitToGadgetCops(gadgetCopsInsuranceModel);
499
					insurancePolicy.setPosted(true);
545
					insurancePolicy.setPosted(true);
500
				}catch (ProfitMandiBusinessException profitMandiBusinessException) {
546
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
501
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(), profitMandiBusinessException);
547
					LOGGER.info("Unable to submit insurance policy details to {}", insuranceProvider.getName(),
-
 
548
							profitMandiBusinessException);
502
				}
549
				}
503
				insurancePolicyRepository.persist(insurancePolicy);
550
				insurancePolicyRepository.persist(insurancePolicy);
504
			}
551
			}
505
		}
552
		}
506
		schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
553
		schemeService.processSchemeOut(fofoOrder.getId(), fofoId);
507
		
554
 
508
		return fofoOrder.getId();
555
		return fofoOrder.getId();
509
	}
556
	}
510
	
557
 
511
	private float calculatePrebookingOrdersAmount(List<PrebookingOrder> prebookingOrders, Map<Integer, Integer> prebookingOrderItemIdQuantityMap, Map<Integer, PrebookingListing> itemIdPrebookingListingMap) {
558
	private float calculatePrebookingOrdersAmount(List<PrebookingOrder> prebookingOrders,
-
 
559
			Map<Integer, Integer> prebookingOrderItemIdQuantityMap,
-
 
560
			Map<Integer, PrebookingListing> itemIdPrebookingListingMap) {
-
 
561
		// List<PrebookingOrder> prebookingOrders =
512
		//List<PrebookingOrder> prebookingOrders = prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId, customerMobileNumber, prebookingOrderItemIdQuantityMap.keySet());
562
		// prebookingOrderRepository.selectByFofoIdCustomerMobileNumberItemIds(fofoId,
-
 
563
		// customerMobileNumber, prebookingOrderItemIdQuantityMap.keySet());
513
		float totalAmount = 0;
564
		float totalAmount = 0;
514
		for(PrebookingOrder prebookingOrder : prebookingOrders) {
565
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
515
			int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
566
			int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
516
			PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
567
			PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
517
			if(requestedQuantity < prebookingOrder.getAvailableQuantity()) {
568
			if (requestedQuantity < prebookingOrder.getAvailableQuantity()) {
518
				LOGGER.info("when requestedQuantity < then requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity, prebookingListing.getAdvanceAmount());
569
				LOGGER.info("when requestedQuantity < then requestedQuantity [{}] * advanceAmount [{}]",
-
 
570
						requestedQuantity, prebookingListing.getAdvanceAmount());
519
				totalAmount = totalAmount + (requestedQuantity * prebookingListing.getAdvanceAmount());
571
				totalAmount = totalAmount + (requestedQuantity * prebookingListing.getAdvanceAmount());
520
			}else if(requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
572
			} else if (requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
521
				LOGGER.info("else requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity, prebookingListing.getAdvanceAmount());
573
				LOGGER.info("else requestedQuantity [{}] * advanceAmount [{}]", requestedQuantity,
-
 
574
						prebookingListing.getAdvanceAmount());
-
 
575
				totalAmount = totalAmount
522
				totalAmount = totalAmount + (prebookingOrder.getAvailableQuantity() * prebookingListing.getAdvanceAmount());
576
						+ (prebookingOrder.getAvailableQuantity() * prebookingListing.getAdvanceAmount());
523
			}
577
			}
524
		}
578
		}
525
		return totalAmount;
579
		return totalAmount;
526
	}
580
	}
527
	
581
 
528
	private void processPrebookingOrders(int fofoId, int orderId, List<PrebookingOrder> prebookingOrders, Map<Integer, Integer> prebookingOrderItemIdQuantityMap, Map<Integer, PrebookingListing> itemIdPrebookingListingMap) 
582
	private void processPrebookingOrders(int fofoId, int orderId, List<PrebookingOrder> prebookingOrders,
-
 
583
			Map<Integer, Integer> prebookingOrderItemIdQuantityMap,
529
	throws ProfitMandiBusinessException{
584
			Map<Integer, PrebookingListing> itemIdPrebookingListingMap) throws ProfitMandiBusinessException {
-
 
585
		// Map<Integer, PrebookingOrder> prebookingOrderIdPrebookingOrderMap =
530
		//Map<Integer, PrebookingOrder> prebookingOrderIdPrebookingOrderMap = this.prebookingOrdersToPrebookingOrderIdPrebookingOrderMap(prebookingOrders);
586
		// this.prebookingOrdersToPrebookingOrderIdPrebookingOrderMap(prebookingOrders);
531
		
587
 
532
		for(PrebookingOrder prebookingOrder : prebookingOrders) {
588
		for (PrebookingOrder prebookingOrder : prebookingOrders) {
533
			if(prebookingOrder.getCompleteTimestamp() == null) {
589
			if (prebookingOrder.getCompleteTimestamp() == null) {
534
				int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
590
				int requestedQuantity = prebookingOrderItemIdQuantityMap.get(prebookingOrder.getItemId());
535
				
591
 
536
				PrebookingOrderItem prebookingOrderItem = new PrebookingOrderItem();
592
				PrebookingOrderItem prebookingOrderItem = new PrebookingOrderItem();
537
				if(requestedQuantity < prebookingOrder.getAvailableQuantity()) {
593
				if (requestedQuantity < prebookingOrder.getAvailableQuantity()) {
538
					prebookingOrder.setAvailableQuantity(prebookingOrder.getAvailableQuantity() - requestedQuantity);
594
					prebookingOrder.setAvailableQuantity(prebookingOrder.getAvailableQuantity() - requestedQuantity);
539
					prebookingOrderItem.setQuantity(requestedQuantity);
595
					prebookingOrderItem.setQuantity(requestedQuantity);
540
				}else if(requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
596
				} else if (requestedQuantity >= prebookingOrder.getAvailableQuantity()) {
541
					prebookingOrderItem.setQuantity(prebookingOrder.getAvailableQuantity());
597
					prebookingOrderItem.setQuantity(prebookingOrder.getAvailableQuantity());
542
					prebookingOrder.setAvailableQuantity(0);
598
					prebookingOrder.setAvailableQuantity(0);
543
				}
599
				}
544
				if(prebookingOrder.getAvailableQuantity() == 0) {
600
				if (prebookingOrder.getAvailableQuantity() == 0) {
545
					prebookingOrder.setCompleteTimestamp(LocalDateTime.now());
601
					prebookingOrder.setCompleteTimestamp(LocalDateTime.now());
546
				}
602
				}
547
				prebookingOrderRepository.persist(prebookingOrder);
603
				prebookingOrderRepository.persist(prebookingOrder);
548
				
604
 
549
				prebookingOrderItem.setOrderId(orderId);
605
				prebookingOrderItem.setOrderId(orderId);
550
				prebookingOrderItem.setItemId(prebookingOrder.getItemId());
606
				prebookingOrderItem.setItemId(prebookingOrder.getItemId());
551
				PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
607
				PrebookingListing prebookingListing = itemIdPrebookingListingMap.get(prebookingOrder.getItemId());
552
				prebookingOrderItem.setAdvanceAmount(prebookingListing.getAdvanceAmount());
608
				prebookingOrderItem.setAdvanceAmount(prebookingListing.getAdvanceAmount());
553
				
609
 
554
				prebookingOrderItemRepository.persist(prebookingOrderItem);
610
				prebookingOrderItemRepository.persist(prebookingOrderItem);
555
				
611
 
556
				walletService.addAmountToWallet(fofoId, prebookingOrder.getId(), WalletReferenceType.PREBOOKING_ORDER, "Advance Amount credited for Prebooking Order", prebookingListing.getAdvanceAmount());
612
				walletService.addAmountToWallet(fofoId, prebookingOrder.getId(), WalletReferenceType.PREBOOKING_ORDER,
-
 
613
						"Advance Amount credited for Prebooking Order", prebookingListing.getAdvanceAmount());
557
			}
614
			}
558
			
615
 
559
		}
616
		}
560
	}
617
	}
561
	
618
 
562
	private Map<Integer, PrebookingListing> prebookingListingsToItemIdPrebookingListingMap(List<PrebookingListing> prebookingListings){
619
	private Map<Integer, PrebookingListing> prebookingListingsToItemIdPrebookingListingMap(
-
 
620
			List<PrebookingListing> prebookingListings) {
563
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
621
		Map<Integer, PrebookingListing> itemIdPrebookingListingMap = new HashMap<>();
564
		for(PrebookingListing prebookingListing : prebookingListings) {
622
		for (PrebookingListing prebookingListing : prebookingListings) {
565
			itemIdPrebookingListingMap.put(prebookingListing.getItemId(), prebookingListing);
623
			itemIdPrebookingListingMap.put(prebookingListing.getItemId(), prebookingListing);
566
		}
624
		}
567
		return itemIdPrebookingListingMap;
625
		return itemIdPrebookingListingMap;
568
	}
626
	}
569
	
-
 
570
	
627
 
571
	private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails){
628
	private Set<String> serialNumberDetailsToSerialNumbers(Set<SerialNumberDetail> serialNumberDetails) {
572
		Set<String> serialNumbers = new HashSet<>();
629
		Set<String> serialNumbers = new HashSet<>();
573
		for(SerialNumberDetail serialNumberDetail : serialNumberDetails) {
630
		for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
574
			if(serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
631
			if (serialNumberDetail.getSerialNumber() != null && !serialNumberDetail.getSerialNumber().isEmpty()) {
575
				serialNumbers.add(serialNumberDetail.getSerialNumber());
632
				serialNumbers.add(serialNumberDetail.getSerialNumber());
576
			}
633
			}
577
		}
634
		}
578
		return serialNumbers;
635
		return serialNumbers;
579
	}
636
	}
580
	
637
 
581
	@Override
638
	@Override
582
	public PdfModel getInvoicePdfModel(int orderId) throws ProfitMandiBusinessException {
639
	public PdfModel getInvoicePdfModel(int orderId) throws ProfitMandiBusinessException {
583
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
640
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(orderId);
584
		return this.getInvoicePdfModel(fofoOrder);
641
		return this.getInvoicePdfModel(fofoOrder);
585
	}
642
	}
586
	
643
 
587
	private PdfModel getInvoicePdfModel(FofoOrder fofoOrder) throws ProfitMandiBusinessException{
644
	private PdfModel getInvoicePdfModel(FofoOrder fofoOrder) throws ProfitMandiBusinessException {
588
		
645
 
589
		List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
646
		List<PaymentOptionTransaction> paymentOptionTransactions = paymentOptionTransactionRepository
-
 
647
				.selectByReferenceIdAndType(fofoOrder.getId(), PaymentOptionReferenceType.ORDER);
590
		
648
 
591
		List<CustomPaymentOption> paymentOptions = new ArrayList<>();
649
		List<CustomPaymentOption> paymentOptions = new ArrayList<>();
592
 
650
 
593
		PdfModel pdfModel = new PdfModel();
651
		PdfModel pdfModel = new PdfModel();
594
		
652
 
595
		for(PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
653
		for (PaymentOptionTransaction paymentOptionTransaction : paymentOptionTransactions) {
596
			CustomPaymentOption cpi = new CustomPaymentOption();
654
			CustomPaymentOption cpi = new CustomPaymentOption();
597
			cpi.setAmount(paymentOptionTransaction.getAmount());
655
			cpi.setAmount(paymentOptionTransaction.getAmount());
-
 
656
			cpi.setPaymentOption(
598
			cpi.setPaymentOption(paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());
657
					paymentOptionRepository.selectById(paymentOptionTransaction.getPaymentOptionId()).getName());
599
			paymentOptions.add(cpi);
658
			paymentOptions.add(cpi);
600
		}
659
		}
601
		pdfModel.setPaymentOptions(paymentOptions);
660
		pdfModel.setPaymentOptions(paymentOptions);
602
		pdfModel.setAuther("profitmandi");
661
		pdfModel.setAuther("profitmandi");
603
		pdfModel.setTitle("Retailer Invoice");
662
		pdfModel.setTitle("Retailer Invoice");
604
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
663
		pdfModel.setInvoiceDate(fofoOrder.getFormattedDate());
605
		
664
 
606
		// insurance calculation
665
		// insurance calculation
-
 
666
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository
607
		List<InsurancePolicy> insurancePolicies = insurancePolicyRepository.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
667
				.selectByRetailerIdInvoiceNumber(fofoOrder.getFofoId(), fofoOrder.getInvoiceNumber());
608
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
668
		Set<CustomInsurancePolicy> customInsurancePolicies = new HashSet<>();
609
		final float totalInsuranceTaxRate = 18;
669
		final float totalInsuranceTaxRate = 18;
610
		for(InsurancePolicy insurancePolicy : insurancePolicies){
670
		for (InsurancePolicy insurancePolicy : insurancePolicies) {
611
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
671
			float taxableInsurancePrice = insurancePolicy.getSaleAmount() / (1 + totalInsuranceTaxRate / 100);
612
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
672
			CustomInsurancePolicy customInsurancePolicy = new CustomInsurancePolicy();
-
 
673
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #"
613
			customInsurancePolicy.setDescription("Damage Protection Plan for device IMEI #" + insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
674
					+ insurancePolicy.getSerialNumber() + "\n Certificate No. " + insurancePolicy.getPolicyNumber());
614
			customInsurancePolicy.setHsnCode("998716");
675
			customInsurancePolicy.setHsnCode("998716");
615
			customInsurancePolicy.setRate(taxableInsurancePrice);
676
			customInsurancePolicy.setRate(taxableInsurancePrice);
616
			customInsurancePolicy.setIgstRate(18);
677
			customInsurancePolicy.setIgstRate(18);
617
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 /100);
678
			customInsurancePolicy.setIgstAmount(taxableInsurancePrice * 18 / 100);
618
			customInsurancePolicy.setCgstRate(9);
679
			customInsurancePolicy.setCgstRate(9);
619
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 /100);
680
			customInsurancePolicy.setCgstAmount(taxableInsurancePrice * 9 / 100);
620
			customInsurancePolicy.setSgstRate(9);
681
			customInsurancePolicy.setSgstRate(9);
621
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 /100);
682
			customInsurancePolicy.setSgstAmount(taxableInsurancePrice * 9 / 100);
622
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
683
			customInsurancePolicy.setNetAmount(insurancePolicy.getSaleAmount());
623
			customInsurancePolicies.add(customInsurancePolicy);
684
			customInsurancePolicies.add(customInsurancePolicy);
624
		}
685
		}
625
		pdfModel.setInsurancePolicies(customInsurancePolicies);
686
		pdfModel.setInsurancePolicies(customInsurancePolicies);
626
		List<String> tncs = new ArrayList<>();
687
		List<String> tncs = new ArrayList<>();
627
		tncs.add("I agree that goods received are in good working condition");
688
		tncs.add("I agree that goods received are in good working condition");
628
		tncs.add("Goods once sold cannot be exchanged or taken back");
689
		tncs.add("Goods once sold cannot be exchanged or taken back");
629
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
690
		tncs.add("Warranty for the goods received by me is the responsibility of the manufacturer only.");
630
        if(pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
691
		if (pdfModel.getInsurancePolicies() != null && pdfModel.getInsurancePolicies().size() > 0) {
631
        		tncs.add("Damage protection provided is the responisibility of Protection Provider only");
692
			tncs.add("Damage protection provided is the responisibility of Protection Provider only");
632
        }
693
		}
633
		pdfModel.setTncs(tncs);
694
		pdfModel.setTncs(tncs);
634
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
695
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
635
		CustomCustomer customCustomer = new CustomCustomer();
696
		CustomCustomer customCustomer = new CustomCustomer();
636
		customCustomer.setFirstName(customer.getFirstName());
697
		customCustomer.setFirstName(customer.getFirstName());
637
		customCustomer.setLastName(customer.getLastName());
698
		customCustomer.setLastName(customer.getLastName());
638
		customCustomer.setEmailId(customer.getEmailId());
699
		customCustomer.setEmailId(customer.getEmailId());
639
		customCustomer.setMobileNumber(customer.getMobileNumber());
700
		customCustomer.setMobileNumber(customer.getMobileNumber());
640
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
701
		customCustomer.setGstNumber(fofoOrder.getCustomerGstNumber());
641
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId()); 
702
		CustomerAddress customerAddress = customerAddressRepository.selectById(fofoOrder.getCustomerAddressId());
642
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
703
		customCustomer.setAddress(this.createCustomAddress(customerAddress));
643
		pdfModel.setCustomer(customCustomer);
704
		pdfModel.setCustomer(customCustomer);
644
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
705
		pdfModel.setInvoiceNumber(fofoOrder.getInvoiceNumber());
645
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
706
		pdfModel.setTotalAmount(fofoOrder.getTotalAmount());
646
		
707
 
647
		Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
708
		Retailer retailer = retailerRepository.selectById(fofoOrder.getFofoId());
648
		PrivateDealUser privateDealUser = null;
709
		PrivateDealUser privateDealUser = null;
649
		try{
710
		try {
650
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
711
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
651
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
712
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
652
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
713
			LOGGER.error("Private Deal User not found : ", profitMandiBusinessException);
653
		}
714
		}
654
		
715
 
655
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
716
		User user = userRepository.selectById(userAccountRepository.selectUserIdByRetailerId(retailer.getId()));
656
		CustomRetailer customRetailer = new CustomRetailer();
717
		CustomRetailer customRetailer = new CustomRetailer();
657
		customRetailer.setBusinessName(retailer.getName());
718
		customRetailer.setBusinessName(retailer.getName());
658
		customRetailer.setMobileNumber(user.getMobileNumber());
719
		customRetailer.setMobileNumber(user.getMobileNumber());
659
		//customRetailer.setTinNumber(retailer.getNumber());
720
		// customRetailer.setTinNumber(retailer.getNumber());
660
		if(privateDealUser == null){
721
		if (privateDealUser == null) {
661
			customRetailer.setGstNumber(null);
722
			customRetailer.setGstNumber(null);
662
		}else{
723
		} else {
663
			if(null != privateDealUser.getCounterId()){
724
			if (null != privateDealUser.getCounterId()) {
664
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
725
				Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
665
				customRetailer.setGstNumber(counter.getGstin());
726
				customRetailer.setGstNumber(counter.getGstin());
666
			}else{
727
			} else {
667
				customRetailer.setGstNumber(null);
728
				customRetailer.setGstNumber(null);
668
			}
729
			}
669
		}
730
		}
-
 
731
		Address retailerAddress = addressRepository
670
		Address retailerAddress = addressRepository.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
732
				.selectById(retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailer.getId()));
671
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
733
		customRetailer.setAddress(this.createCustomAddress(retailerAddress));
672
		pdfModel.setRetailer(customRetailer);
734
		pdfModel.setRetailer(customRetailer);
673
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
735
		List<FofoOrderItem> fofoOrderItems = this.getByOrderId(fofoOrder.getId());
674
		
736
 
675
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
737
		Set<CustomOrderItem> customerFofoOrderItems = new HashSet<>();
676
		for(FofoOrderItem fofoOrderItem : fofoOrderItems){
738
		for (FofoOrderItem fofoOrderItem : fofoOrderItems) {
677
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
739
			CustomOrderItem customFofoOrderItem = new CustomOrderItem();
678
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate() + fofoOrderItem.getCgstRate();
740
			float totalTaxRate = fofoOrderItem.getIgstRate() + fofoOrderItem.getSgstRate()
-
 
741
					+ fofoOrderItem.getCgstRate();
679
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
742
			float taxableSellingPrice = fofoOrderItem.getSellingPrice() / (1 + totalTaxRate / 100);
680
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
743
			float taxableDiscountPrice = fofoOrderItem.getDiscount() / (1 + totalTaxRate / 100);
681
			
744
 
682
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
745
			customFofoOrderItem.setAmount(fofoOrderItem.getQuantity() * (taxableSellingPrice - taxableDiscountPrice));
683
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " " + fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
746
			customFofoOrderItem.setDescription(fofoOrderItem.getBrand() + " " + fofoOrderItem.getModelName() + " "
-
 
747
					+ fofoOrderItem.getModelNumber() + "-" + fofoOrderItem.getColor());
684
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
748
			Set<String> serialNumbers = this.toSerialNumbers(fofoOrderItem.getFofoLineItems());
685
			//LOGGER.info("serialNumbers {}", serialNumbers);
749
			// LOGGER.info("serialNumbers {}", serialNumbers);
686
			//LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
750
			// LOGGER.info("serialNumbers is empty {}", serialNumbers.isEmpty());
687
			if(!serialNumbers.isEmpty()) {
751
			if (!serialNumbers.isEmpty()) {
-
 
752
				customFofoOrderItem.setDescription(
688
				customFofoOrderItem.setDescription(customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
753
						customFofoOrderItem.getDescription() + "\n IMEIS - " + String.join(", ", serialNumbers));
689
			}
754
			}
690
			customFofoOrderItem.setRate(taxableSellingPrice);
755
			customFofoOrderItem.setRate(taxableSellingPrice);
691
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
756
			customFofoOrderItem.setDiscount(taxableDiscountPrice);
692
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
757
			customFofoOrderItem.setQuantity(fofoOrderItem.getQuantity());
-
 
758
			customFofoOrderItem.setNetAmount(
693
			customFofoOrderItem.setNetAmount((fofoOrderItem.getSellingPrice()-fofoOrderItem.getDiscount())*fofoOrderItem.getQuantity());
759
					(fofoOrderItem.getSellingPrice() - fofoOrderItem.getDiscount()) * fofoOrderItem.getQuantity());
694
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
760
			float igstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getIgstRate()) / 100;
695
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
761
			float cgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getCgstRate()) / 100;
696
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
762
			float sgstAmount = (customFofoOrderItem.getAmount() * fofoOrderItem.getSgstRate()) / 100;
697
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
763
			customFofoOrderItem.setIgstRate(fofoOrderItem.getIgstRate());
698
			customFofoOrderItem.setIgstAmount(igstAmount);
764
			customFofoOrderItem.setIgstAmount(igstAmount);
Line 703... Line 769...
703
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
769
			customFofoOrderItem.setHsnCode(fofoOrderItem.getHsnCode());
704
			customerFofoOrderItems.add(customFofoOrderItem);
770
			customerFofoOrderItems.add(customFofoOrderItem);
705
		}
771
		}
706
		pdfModel.setOrderItems(customerFofoOrderItems);
772
		pdfModel.setOrderItems(customerFofoOrderItems);
707
		return pdfModel;
773
		return pdfModel;
708
	
774
 
709
	}
775
	}
710
	
776
 
711
	@Override
777
	@Override
712
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
778
	public PdfModel getInvoicePdfModel(int fofoId, int orderId) throws ProfitMandiBusinessException {
713
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
779
		FofoOrder fofoOrder = fofoOrderRepository.selectByFofoIdAndOrderId(fofoId, orderId);
714
		return this.getInvoicePdfModel(fofoOrder);
780
		return this.getInvoicePdfModel(fofoOrder);
715
	}
781
	}
716
	
782
 
717
	public String getBillingAddress(CustomerAddress customerAddress) {
783
	public String getBillingAddress(CustomerAddress customerAddress) {
718
		StringBuilder address = new StringBuilder();
784
		StringBuilder address = new StringBuilder();
719
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
785
		if ((customerAddress.getLine1() != null) && (!customerAddress.getLine1().isEmpty())) {
720
			address.append(customerAddress.getLine1());
786
			address.append(customerAddress.getLine1());
721
			address.append(", ");
787
			address.append(", ");
Line 745... Line 811...
745
			address.append(customerAddress.getPinCode());
811
			address.append(customerAddress.getPinCode());
746
		}
812
		}
747
 
813
 
748
		return address.toString();
814
		return address.toString();
749
	}
815
	}
750
	
816
 
751
	@Override
817
	@Override
752
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException{
818
	public List<CartFofo> cartCheckout(String cartJson) throws ProfitMandiBusinessException {
753
		try{
819
		try {
754
			JSONObject cartObject = new JSONObject(cartJson);
820
			JSONObject cartObject = new JSONObject(cartJson);
755
			Iterator<?> keys = cartObject.keys();
821
			Iterator<?> keys = cartObject.keys();
756
	
822
 
757
			Set<Integer> itemIds = new HashSet<>();
823
			Set<Integer> itemIds = new HashSet<>();
758
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
824
			List<CartFofo> cartItems = new ArrayList<CartFofo>();
759
	
825
 
760
			while( keys.hasNext() ) {
826
			while (keys.hasNext()) {
761
				String key = (String)keys.next();
827
				String key = (String) keys.next();
762
				if ( cartObject.get(key) instanceof JSONObject ) {
828
				if (cartObject.get(key) instanceof JSONObject) {
763
					LOGGER.info(cartObject.get(key).toString());
829
					LOGGER.info(cartObject.get(key).toString());
764
				}
830
				}
765
				CartFofo cf = new CartFofo();
831
				CartFofo cf = new CartFofo();
766
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
832
				cf.setItemId(cartObject.getJSONObject(key).getInt("itemId"));
767
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
833
				cf.setQuantity(cartObject.getJSONObject(key).getInt("quantity"));
768
				
834
 
769
				if (cf.getQuantity() <= 0){
835
				if (cf.getQuantity() <= 0) {
770
					continue;
836
					continue;
771
				}
837
				}
772
				cartItems.add(cf);
838
				cartItems.add(cf);
773
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
839
				itemIds.add(cartObject.getJSONObject(key).getInt("itemId"));
774
			}
840
			}
775
			Map<Integer, Item>  itemMap = new HashMap<Integer, Item>();
841
			Map<Integer, Item> itemMap = new HashMap<Integer, Item>();
776
			if (itemIds.size() > 0){
842
			if (itemIds.size() > 0) {
777
				List<Item> items = itemRepository.selectByIds(itemIds);
843
				List<Item> items = itemRepository.selectByIds(itemIds);
778
				for (Item i : items){
844
				for (Item i : items) {
779
					itemMap.put(i.getId(), i);
845
					itemMap.put(i.getId(), i);
780
				}
846
				}
781
				
847
 
782
			}
848
			}
783
			for (CartFofo cf : cartItems){
849
			for (CartFofo cf : cartItems) {
784
				Item i = itemMap.get(cf.getItemId());
850
				Item i = itemMap.get(cf.getItemId());
785
				if (i == null){
851
				if (i == null) {
786
					continue;
852
					continue;
787
				}
853
				}
-
 
854
				cf.setDisplayName(getValidName(i.getBrand()) + " " + getValidName(i.getModelName()) + " "
788
				cf.setDisplayName(getValidName(i.getBrand())+" "+getValidName(i.getModelName())+" "+getValidName(i.getModelNumber())+" "+getValidName(i.getColor()).replaceAll("\\s+", " "));
855
						+ getValidName(i.getModelNumber()) + " " + getValidName(i.getColor()).replaceAll("\\s+", " "));
789
				cf.setItemType(i.getType());
856
				cf.setItemType(i.getType());
790
			}
857
			}
791
			return cartItems;
858
			return cartItems;
792
		}catch (Exception e) {
859
		} catch (Exception e) {
793
			LOGGER.error("Unable to Prepare cart to place order...", e);
860
			LOGGER.error("Unable to Prepare cart to place order...", e);
794
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
861
			throw new ProfitMandiBusinessException("cartData", cartJson, "FFORDR_1006");
795
		}
862
		}
796
	}
863
	}
797
	
864
 
798
	@Override
865
	@Override
799
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue, String startTimeString,
866
	public Map<String, Object> getSaleHistory(int fofoId, SearchType searchType, String searchValue,
800
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
867
			String startTimeString, String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
801
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
868
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
802
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
869
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
803
		long countItems = 0;
870
		long countItems = 0;
804
		List<FofoOrder> fofoOrders = new ArrayList<>();
871
		List<FofoOrder> fofoOrders = new ArrayList<>();
805
		
872
 
806
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
873
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
807
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
874
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime,
-
 
875
					endDateTime, offset, limit);
808
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime);
876
			countItems = fofoOrderRepository.selectCountByCustomerMobileNumber(fofoId, searchValue, startDateTime,
-
 
877
					endDateTime);
809
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
878
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
810
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
879
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime,
-
 
880
					endDateTime, offset, limit);
811
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);
881
			countItems = fofoOrderRepository.selectCountByCustomerName(fofoId, searchValue, startDateTime, endDateTime);
812
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
882
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
813
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
883
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime,
-
 
884
					endDateTime, offset, limit);
814
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);
885
			countItems = fofoOrderRepository.selectCountBySerialNumber(fofoId, searchValue, startDateTime, endDateTime);
815
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
886
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
816
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
887
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime,
-
 
888
					offset, limit);
817
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);
889
			countItems = fofoOrderRepository.selectCountByItemName(fofoId, searchValue, startDateTime, endDateTime);
818
		}else{
890
		} else {
819
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
891
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
820
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);
892
			countItems = fofoOrderRepository.selectCountByFofoId(fofoId, startDateTime, endDateTime);
821
		}
893
		}
822
		Map<String, Object> map = new HashMap<>();
894
		Map<String, Object> map = new HashMap<>();
823
		
895
 
824
		map.put("saleHistories", fofoOrders);
896
		map.put("saleHistories", fofoOrders);
825
		map.put("start", offset + 1);
897
		map.put("start", offset + 1);
826
		map.put("size", countItems);
898
		map.put("size", countItems);
827
		map.put("searchType", searchType);
899
		map.put("searchType", searchType);
828
		map.put("searchTypes", SearchType.values());
900
		map.put("searchTypes", SearchType.values());
829
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
901
		map.put(ProfitMandiConstants.START_TIME, startTimeString);
830
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
902
		map.put(ProfitMandiConstants.END_TIME, endTimeString);
831
		if (fofoOrders.size() < limit){
903
		if (fofoOrders.size() < limit) {
832
			map.put("end", offset + fofoOrders.size());
904
			map.put("end", offset + fofoOrders.size());
833
		}
-
 
834
		else{
905
		} else {
835
			map.put("end", offset + limit);
906
			map.put("end", offset + limit);
836
		}
907
		}
837
		return map;
908
		return map;
838
	}
909
	}
839
 
910
 
840
	@Override
911
	@Override
841
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue, String startTimeString,
912
	public Map<String, Object> getSaleHistoryPaginated(int fofoId, SearchType searchType, String searchValue,
842
			String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
913
			String startTimeString, String endTimeString, int offset, int limit) throws ProfitMandiBusinessException {
843
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
914
		LocalDateTime startDateTime = StringUtils.toDateTime(startTimeString);
844
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
915
		LocalDateTime endDateTime = StringUtils.toDateTime(endTimeString);
845
		List<FofoOrder> fofoOrders = new ArrayList<>();
916
		List<FofoOrder> fofoOrders = new ArrayList<>();
846
		
917
 
847
		if(searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()){
918
		if (searchType == SearchType.CUSTOMER_MOBILE_NUMBER && !searchValue.isEmpty()) {
848
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
919
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerMobileNumber(fofoId, searchValue, startDateTime,
-
 
920
					endDateTime, offset, limit);
849
		}else if(searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()){
921
		} else if (searchType == SearchType.CUSTOMER_NAME && !searchValue.isEmpty()) {
850
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
922
			fofoOrders = fofoOrderRepository.selectByFofoIdAndCustomerName(fofoId, searchValue, startDateTime,
-
 
923
					endDateTime, offset, limit);
851
		}else if(searchType == SearchType.IMEI && !searchValue.isEmpty()){
924
		} else if (searchType == SearchType.IMEI && !searchValue.isEmpty()) {
852
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
925
			fofoOrders = fofoOrderRepository.selectByFofoIdAndSerialNumber(fofoId, searchValue, startDateTime,
-
 
926
					endDateTime, offset, limit);
853
		}else if(searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()){
927
		} else if (searchType == SearchType.ITEM_NAME && !searchValue.isEmpty()) {
854
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime, offset, limit);
928
			fofoOrders = fofoOrderRepository.selectByFofoIdAndItemName(fofoId, searchValue, startDateTime, endDateTime,
-
 
929
					offset, limit);
855
		}else{
930
		} else {
856
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
931
			fofoOrders = fofoOrderRepository.selectByFofoId(fofoId, startDateTime, endDateTime, offset, limit);
857
		}
932
		}
858
		Map<String, Object> map = new HashMap<>();
933
		Map<String, Object> map = new HashMap<>();
859
		
934
 
860
		map.put("saleHistories", fofoOrders);
935
		map.put("saleHistories", fofoOrders);
861
		return map;
936
		return map;
862
	}
937
	}
863
	
938
 
864
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException{
939
	private String getFofoStoreCode(int fofoId) throws ProfitMandiBusinessException {
865
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
940
		FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(fofoId);
866
		return fofoStore.getCode();
941
		return fofoStore.getCode();
867
	}
942
	}
868
	
-
 
869
	
943
 
870
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId){
944
	private CustomerAddress createCustomerAddress(CustomAddress customAddress, int customerId) {
871
		CustomerAddress customerAddress = null;
945
		CustomerAddress customerAddress = null;
872
		try{
946
		try {
873
			//CustomAddress customAddress = customCustomer.getAddress();
947
			// CustomAddress customAddress = customCustomer.getAddress();
874
			customerAddress = customerAddressRepository.selectByParams(
948
			customerAddress = customerAddressRepository.selectByParams(customAddress.getName(),
875
					customAddress.getName(), customAddress.getLine1(), customAddress.getLine2(),
949
					customAddress.getLine1(), customAddress.getLine2(), customAddress.getLandmark(),
876
					customAddress.getLandmark(),customAddress.getCity(), customAddress.getPinCode(),
950
					customAddress.getCity(), customAddress.getPinCode(), customAddress.getState(),
877
					customAddress.getState(), customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
951
					customAddress.getPhoneNumber(), customAddress.getCountry(), customerId);
878
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
952
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
879
			LOGGER.warn("Customer address not found with [{}]", customAddress);
953
			LOGGER.warn("Customer address not found with [{}]", customAddress);
880
			customerAddress = new CustomerAddress();
954
			customerAddress = new CustomerAddress();
881
			this.setCustomerAddress(customerAddress, customAddress);
955
			this.setCustomerAddress(customerAddress, customAddress);
882
			customerAddress.setCustomerId(customerId);
956
			customerAddress.setCustomerId(customerId);
883
		}
957
		}
884
		customerAddressRepository.persist(customerAddress);
958
		customerAddressRepository.persist(customerAddress);
885
		return customerAddress;
959
		return customerAddress;
886
	}
960
	}
887
	
961
 
888
	private String getValidName(String name){
962
	private String getValidName(String name) {
889
		return name!=null?name:"";
963
		return name != null ? name : "";
890
	}
964
	}
891
	
965
 
892
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems){
966
	private Set<String> toSerialNumbers(Set<FofoLineItem> fofoLineItems) {
893
		Set<String> serialNumbers = new HashSet<>();
967
		Set<String> serialNumbers = new HashSet<>();
894
		for(FofoLineItem fofoLineItem : fofoLineItems) {
968
		for (FofoLineItem fofoLineItem : fofoLineItems) {
895
			if(fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
969
			if (fofoLineItem.getSerialNumber() != null && !fofoLineItem.getSerialNumber().isEmpty()) {
896
				serialNumbers.add(fofoLineItem.getSerialNumber());
970
				serialNumbers.add(fofoLineItem.getSerialNumber());
897
			}
971
			}
898
		}
972
		}
899
		return serialNumbers;
973
		return serialNumbers;
900
	}
974
	}
901
	
-
 
902
	
975
 
903
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence(){
976
	private PolicyNumberGenerationSequence createPolicyNumberGenerationSequence() {
904
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
977
		PolicyNumberGenerationSequence policyNumberGenerationSequence = null;
905
		try{
978
		try {
906
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
979
			policyNumberGenerationSequence = policyNumberGenerationSequenceRepository.select();
907
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
980
			policyNumberGenerationSequence.setSequence(policyNumberGenerationSequence.getSequence() + 1);
908
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
981
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
909
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
982
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
910
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
983
			policyNumberGenerationSequence = new PolicyNumberGenerationSequence();
911
			policyNumberGenerationSequence.setSequence(1);
984
			policyNumberGenerationSequence.setSequence(1);
912
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
985
			policyNumberGenerationSequenceRepository.persist(policyNumberGenerationSequence);
913
		}
986
		}
914
		return policyNumberGenerationSequence;
987
		return policyNumberGenerationSequence;
915
	}
988
	}
916
	
989
 
917
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber, LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress, InsurancePolicy insurancePolicy){
990
	private GadgetCopsInsuranceModel createGadgetCopsInsuranceModel(String brand, String modelName, String serialNumber,
-
 
991
			LocalDate customerDateOfBirth, Customer customer, CustomerAddress customerAddress,
-
 
992
			InsurancePolicy insurancePolicy) {
918
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
993
		GadgetCopsInsuranceModel gadgetCopsInsuranceModel = new GadgetCopsInsuranceModel();
919
		gadgetCopsInsuranceModel.setBrand(brand);
994
		gadgetCopsInsuranceModel.setBrand(brand);
920
		gadgetCopsInsuranceModel.setModelName(modelName);
995
		gadgetCopsInsuranceModel.setModelName(modelName);
921
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
996
		gadgetCopsInsuranceModel.setSerialNumber(serialNumber);
922
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
997
		gadgetCopsInsuranceModel.setCustomerFirstName(customer.getFirstName());
Line 932... Line 1007...
932
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
1007
		gadgetCopsInsuranceModel.setPrice(insurancePolicy.getSellingPrice());
933
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
1008
		gadgetCopsInsuranceModel.setInvoiceNumber(insurancePolicy.getInvoiceNumber());
934
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
1009
		gadgetCopsInsuranceModel.setPolicyNumber(insurancePolicy.getPolicyNumber());
935
		return gadgetCopsInsuranceModel;
1010
		return gadgetCopsInsuranceModel;
936
	}
1011
	}
937
	
1012
 
938
	private InsurancePolicy createInsurancePolicy(String invoiceNumber, int retailerId, float purchaseAmount, float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand, int policyNumberGenerationSequence, int insuranceProviderId, Customer customer, LocalDate customerDateOfBirth, CustomerAddress customerAddress){
1013
	private InsurancePolicy createInsurancePolicy(String invoiceNumber, int retailerId, float purchaseAmount,
-
 
1014
			float saleAmount, float sellingPrice, String serialNumber, String modelName, String brand,
-
 
1015
			int policyNumberGenerationSequence, int insuranceProviderId, Customer customer,
-
 
1016
			LocalDate customerDateOfBirth, CustomerAddress customerAddress) {
939
		InsurancePolicy insurancePolicy = new InsurancePolicy();
1017
		InsurancePolicy insurancePolicy = new InsurancePolicy();
940
		insurancePolicy.setInvoiceNumber(invoiceNumber);
1018
		insurancePolicy.setInvoiceNumber(invoiceNumber);
941
		insurancePolicy.setRetailerId(retailerId);
1019
		insurancePolicy.setRetailerId(retailerId);
942
		insurancePolicy.setPurchaseAmount(purchaseAmount);
1020
		insurancePolicy.setPurchaseAmount(purchaseAmount);
943
		insurancePolicy.setSaleAmount(saleAmount);
1021
		insurancePolicy.setSaleAmount(saleAmount);
944
		insurancePolicy.setSellingPrice(sellingPrice);
1022
		insurancePolicy.setSellingPrice(sellingPrice);
945
		insurancePolicy.setSerialNumber(serialNumber);
1023
		insurancePolicy.setSerialNumber(serialNumber);
946
		insurancePolicy.setModelName(modelName);
1024
		insurancePolicy.setModelName(modelName);
947
		insurancePolicy.setBrand(brand);
1025
		insurancePolicy.setBrand(brand);
948
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX, policyNumberGenerationSequence));
1026
		insurancePolicy.setPolicyNumber(StringUtils.generatePolicyNumber(ProfitMandiConstants.POLICY_NUMBER_PREFIX,
-
 
1027
				policyNumberGenerationSequence));
949
		insurancePolicy.setProviderId(insuranceProviderId);
1028
		insurancePolicy.setProviderId(insuranceProviderId);
950
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
1029
		insurancePolicy.setCustomerFirstName(customer.getFirstName());
951
		insurancePolicy.setCustomerLastName(customer.getLastName());
1030
		insurancePolicy.setCustomerLastName(customer.getLastName());
952
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
1031
		insurancePolicy.setCustomerMobileNumber(customer.getMobileNumber());
953
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
1032
		insurancePolicy.setCustomerEmailId(customer.getEmailId());
Line 957... Line 1036...
957
		insurancePolicy.setCustomerCity(customerAddress.getCity());
1036
		insurancePolicy.setCustomerCity(customerAddress.getCity());
958
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
1037
		insurancePolicy.setCustomerPinCode(customerAddress.getPinCode());
959
		insurancePolicy.setCustomerState(customerAddress.getState());
1038
		insurancePolicy.setCustomerState(customerAddress.getState());
960
		return insurancePolicy;
1039
		return insurancePolicy;
961
	}
1040
	}
962
	
1041
 
963
	private void validateInsuranceMargin(Map<String, Float> insuranceSerialNumberItemPrice, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, Map<Integer, PriceModel> itemIdMopPriceMap, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap, Map<String, Float> insuranceSerialNumberSaleAmount) throws ProfitMandiBusinessException{
1042
	private void validateInsuranceMargin(Map<String, Float> insuranceSerialNumberItemPrice,
-
 
1043
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, Map<Integer, PriceModel> itemIdMopPriceMap,
-
 
1044
			Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap, Map<String, Float> insuranceSerialNumberSaleAmount)
-
 
1045
			throws ProfitMandiBusinessException {
964
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
1046
		Map<Float, Float> invalidInsuranceMarginAmount = new HashMap<>();
965
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
1047
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
966
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
1048
			int itemId = this.getItemIdFromSerialNumber(itemIdCustomFofoOrderItemMap, entry.getKey());
967
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
1049
			float itemPurchasePrice = itemIdMopPriceMap.get(itemId).getPrice();
968
			float itemSellingPrice = entry.getValue();
1050
			float itemSellingPrice = entry.getValue();
969
			float itemMargin = itemSellingPrice - itemPurchasePrice;
1051
			float itemMargin = itemSellingPrice - itemPurchasePrice;
970
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
1052
			float insurancePurchasePrice = insurancePricesMap.get(entry.getValue()).getDealerPrice();
971
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
1053
			float insuranceSellingPrice = insuranceSerialNumberSaleAmount.get(entry.getKey());
972
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
1054
			float insuranceMargin = insuranceSellingPrice - insurancePurchasePrice;
973
			if(insuranceMargin < (itemMargin * 30 / 100)){
1055
			if (insuranceMargin < (itemMargin * 30 / 100)) {
974
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
1056
				invalidInsuranceMarginAmount.put(insuranceMargin, (itemMargin * 30 / 100));
975
			}
1057
			}
976
		}
1058
		}
977
		if(!invalidInsuranceMarginAmount.isEmpty()){
1059
		if (!invalidInsuranceMarginAmount.isEmpty()) {
-
 
1060
			LOGGER.error(
978
			LOGGER.error("insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}", invalidInsuranceMarginAmount);
1061
					"insurance marging should be greater than equal to item profit margin insuranceMarginItemIdMargin {}",
-
 
1062
					invalidInsuranceMarginAmount);
979
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount, "FFORDR_1007");
1063
			throw new ProfitMandiBusinessException("invalidInsuranceMarginAmount", invalidInsuranceMarginAmount,
-
 
1064
					"FFORDR_1007");
980
		}
1065
		}
981
	}
1066
	}
982
	
1067
 
-
 
1068
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice,
983
	private void validateInsuranceAmount(Map<String, Float> insuranceSerialNumberItemPrice, Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap) throws ProfitMandiBusinessException{
1069
			Map<String, Float> insuranceSerialNumberSaleAmount, Map<Float, GadgetCopsInsuranceCalc> insurancePricesMap)
-
 
1070
			throws ProfitMandiBusinessException {
984
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
1071
		Map<Float, Float> invalidInsurancePurchaseSaleAmount = new HashMap<>();
985
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
1072
		Map<Float, Float> invalidInsuranceSalePurchaseAmount = new HashMap<>();
986
		for(Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()){
1073
		for (Map.Entry<String, Float> entry : insuranceSerialNumberItemPrice.entrySet()) {
987
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue()).getDealerPrice()){
1074
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) < insurancePricesMap.get(entry.getValue())
-
 
1075
					.getDealerPrice()) {
988
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(), insuranceSerialNumberSaleAmount.get(entry.getKey()));
1076
				invalidInsurancePurchaseSaleAmount.put(insurancePricesMap.get(entry.getValue()).getDealerPrice(),
-
 
1077
						insuranceSerialNumberSaleAmount.get(entry.getKey()));
989
			}
1078
			}
990
			
1079
 
991
			if(insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue()).getSellingPrice()){
1080
			if (insuranceSerialNumberSaleAmount.get(entry.getKey()) > insurancePricesMap.get(entry.getValue())
-
 
1081
					.getSellingPrice()) {
992
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()), insurancePricesMap.get(entry.getValue()).getDealerPrice());
1082
				invalidInsuranceSalePurchaseAmount.put(insuranceSerialNumberSaleAmount.get(entry.getKey()),
-
 
1083
						insurancePricesMap.get(entry.getValue()).getDealerPrice());
993
			}
1084
			}
994
		}
1085
		}
995
		
1086
 
996
		// insurance sale amount can not be lesser than insurance purchase amount
1087
		// insurance sale amount can not be lesser than insurance purchase amount
997
		if(!invalidInsurancePurchaseSaleAmount.isEmpty()){
1088
		if (!invalidInsurancePurchaseSaleAmount.isEmpty()) {
-
 
1089
			LOGGER.error(
998
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount", invalidInsurancePurchaseSaleAmount);
1090
					"Invalid Insurance prices [{}], insurance sale amount can not be lesser than insurance purchase amount",
-
 
1091
					invalidInsurancePurchaseSaleAmount);
999
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount", invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
1092
			throw new ProfitMandiBusinessException("invalidInsurancePurchaseSaleAmount",
-
 
1093
					invalidInsurancePurchaseSaleAmount, "FFORDR_1008");
1000
		}
1094
		}
1001
		
1095
 
1002
		if(!invalidInsuranceSalePurchaseAmount.isEmpty()){
1096
		if (!invalidInsuranceSalePurchaseAmount.isEmpty()) {
-
 
1097
			LOGGER.error(
1003
			LOGGER.error("Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount", invalidInsuranceSalePurchaseAmount);
1098
					"Invalid Insurance prices [{}], insurance sale amount can not be greater than than insurance max amount",
-
 
1099
					invalidInsuranceSalePurchaseAmount);
1004
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount", invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
1100
			throw new ProfitMandiBusinessException("invalidInsuranceSalePurchaseAmount",
-
 
1101
					invalidInsuranceSalePurchaseAmount, "FFORDR_1009");
1005
		}
1102
		}
1006
	}
1103
	}
1007
	
1104
 
-
 
1105
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap,
1008
	private void validateMopPrice(Map<Integer, PriceModel> itemIdMopPriceMap, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException{
1106
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoLineItemMap) throws ProfitMandiBusinessException {
1009
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
1107
		Map<Integer, Float> invalidMopItemIdPriceMap = new HashMap<>();
1010
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
1108
		Map<Integer, Float> invalidDiscountAmountMap = new HashMap<>();
-
 
1109
		// Map<Integer, PriceModel> itemIdMopPriceMap =
1011
		//Map<Integer, PriceModel> itemIdMopPriceMap = pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
1110
		// pricingService.getPurchasePriceMopPriceNotFound(itemIds, fofoId);
1012
		for(Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()){
1111
		for (Map.Entry<Integer, PriceModel> entry : itemIdMopPriceMap.entrySet()) {
1013
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
1112
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoLineItemMap.get(entry.getKey());
-
 
1113
			if (entry.getValue().getPrice() < Float.MAX_VALUE
1014
			if(entry.getValue().getPrice() < Float.MAX_VALUE && customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()){
1114
					&& customFofoOrderItem.getSellingPrice() < entry.getValue().getPrice()) {
1015
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
1115
				invalidMopItemIdPriceMap.put(entry.getKey(), customFofoOrderItem.getSellingPrice());
1016
			}
1116
			}
-
 
1117
			if (entry.getValue().isMop()
1017
			if(entry.getValue().isMop() && customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()){
1118
					&& customFofoOrderItem.getDiscountAmount() > entry.getValue().getMaxDiscountAmount()) {
1018
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
1119
				invalidDiscountAmountMap.put(entry.getKey(), customFofoOrderItem.getDiscountAmount());
1019
			}
1120
			}
1020
		}
1121
		}
1021
		
1122
 
1022
		if(!invalidMopItemIdPriceMap.isEmpty()){
1123
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1023
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}", invalidMopItemIdPriceMap, itemIdMopPriceMap);
1124
			LOGGER.error("Invalid itemIds selling prices{} should be greater than mop prices {}",
-
 
1125
					invalidMopItemIdPriceMap, itemIdMopPriceMap);
1024
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
1126
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidMopItemIdPriceMap, "FFORDR_1010");
1025
		}
1127
		}
1026
		
1128
 
1027
		if(!invalidMopItemIdPriceMap.isEmpty()){
1129
		if (!invalidMopItemIdPriceMap.isEmpty()) {
1028
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}", invalidDiscountAmountMap, itemIdMopPriceMap);
1130
			LOGGER.error("Invalid itemIds discount amounts {} should be less than maxDiscount prices {}",
-
 
1131
					invalidDiscountAmountMap, itemIdMopPriceMap);
1029
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
1132
			throw new ProfitMandiBusinessException("invalidMopItemIdPrice", invalidDiscountAmountMap, "FFORDR_1011");
1030
		}
1133
		}
1031
	}
1134
	}
1032
	
1135
 
1033
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString) throws ProfitMandiBusinessException{
1136
	private LocalDate validateCustomerDateOfBirth(String customerDateOfBirthString)
-
 
1137
			throws ProfitMandiBusinessException {
1034
		LocalDate customerDateOfBirth = null;
1138
		LocalDate customerDateOfBirth = null;
1035
		try{
1139
		try {
1036
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
1140
			customerDateOfBirth = StringUtils.toDate(customerDateOfBirthString);
1037
		}catch(DateTimeException dateTimeException){
1141
		} catch (DateTimeException dateTimeException) {
1038
			LOGGER.error("Unable to parse dateOfBirth message {}", dateTimeException.getMessage());
1142
			LOGGER.error("Unable to parse dateOfBirth message {}", dateTimeException.getMessage());
1039
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
1143
			throw new ProfitMandiBusinessException("dateOfBirth", customerDateOfBirthString, "FFORDR_1012");
1040
		}
1144
		}
1041
		return customerDateOfBirth;
1145
		return customerDateOfBirth;
1042
	}
1146
	}
1043
	
1147
 
1044
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId, Map<Integer, Integer> inventoryItemQuantityUsed){
1148
	private void updateInventoryItemsAndScanRecord(Set<InventoryItem> inventoryItems, int fofoId,
-
 
1149
			Map<Integer, Integer> inventoryItemQuantityUsed) {
1045
		for(InventoryItem inventoryItem : inventoryItems){
1150
		for (InventoryItem inventoryItem : inventoryItems) {
1046
			inventoryItem.setLastScanType(ScanType.SALE);
1151
			inventoryItem.setLastScanType(ScanType.SALE);
1047
			inventoryItemRepository.persist(inventoryItem);
1152
			inventoryItemRepository.persist(inventoryItem);
1048
			ScanRecord scanRecord = new ScanRecord();
1153
			ScanRecord scanRecord = new ScanRecord();
1049
			scanRecord.setInventoryItemId(inventoryItem.getId());
1154
			scanRecord.setInventoryItemId(inventoryItem.getId());
1050
			scanRecord.setFofoId(fofoId);
1155
			scanRecord.setFofoId(fofoId);
1051
			//correct this
1156
			// correct this
1052
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1157
			scanRecord.setQuantity(inventoryItemQuantityUsed.get(inventoryItem.getId()));
1053
			scanRecord.setType(ScanType.SALE);
1158
			scanRecord.setType(ScanType.SALE);
1054
			scanRecordRepository.persist(scanRecord);
1159
			scanRecordRepository.persist(scanRecord);
1055
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
1160
			purchaseReturnItemRepository.deleteById(inventoryItem.getId());
1056
			
1161
 
1057
		}
1162
		}
1058
	}
1163
	}
1059
	
1164
 
1060
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems, Map<Integer, Integer> inventoryItemIdQuantityUsed){
1165
	private void createFofoLineItem(int fofoOrderItemId, Set<InventoryItem> inventoryItems,
-
 
1166
			Map<Integer, Integer> inventoryItemIdQuantityUsed) {
1061
		for(InventoryItem inventoryItem : inventoryItems){
1167
		for (InventoryItem inventoryItem : inventoryItems) {
1062
			FofoLineItem fofoLineItem = new FofoLineItem();
1168
			FofoLineItem fofoLineItem = new FofoLineItem();
1063
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1169
			fofoLineItem.setFofoOrderItemId(fofoOrderItemId);
1064
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1170
			fofoLineItem.setSerialNumber(inventoryItem.getSerialNumber());
1065
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1171
			fofoLineItem.setInventoryItemId(inventoryItem.getId());
1066
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1172
			fofoLineItem.setQuantity(inventoryItemIdQuantityUsed.get(inventoryItem.getId()));
1067
			fofoLineItemRepository.persist(fofoLineItem);
1173
			fofoLineItemRepository.persist(fofoLineItem);
1068
		}
1174
		}
1069
	}
1175
	}
1070
	
1176
 
1071
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId, Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId) throws ProfitMandiBusinessException{
1177
	private FofoOrderItem createAndGetFofoOrderItem(CustomFofoOrderItem customFofoOrderItem, int fofoOrderId,
-
 
1178
			Map<Integer, Item> itemMap, Set<InventoryItem> inventoryItems, Integer stateId)
-
 
1179
			throws ProfitMandiBusinessException {
1072
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1180
		FofoOrderItem fofoOrderItem = new FofoOrderItem();
1073
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1181
		fofoOrderItem.setItemId(customFofoOrderItem.getItemId());
1074
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1182
		fofoOrderItem.setQuantity(customFofoOrderItem.getQuantity());
1075
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1183
		fofoOrderItem.setSellingPrice(customFofoOrderItem.getSellingPrice());
1076
		fofoOrderItem.setOrderId(fofoOrderId);
1184
		fofoOrderItem.setOrderId(fofoOrderId);
1077
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1185
		fofoOrderItem.setDp(customFofoOrderItem.getSellingPrice());
1078
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
1186
		fofoOrderItem.setDiscount(customFofoOrderItem.getDiscountAmount());
1079
		Item item = itemMap.get(customFofoOrderItem.getItemId());
1187
		Item item = itemMap.get(customFofoOrderItem.getItemId());
1080
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1188
		Map<Integer, GstRate> itemIdStateTaxRateMap = null;
1081
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
1189
		Map<Integer, Float> itemIdIgstTaxRateMap = null;
1082
		if(stateId != null){
1190
		if (stateId != null) {
1083
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
1191
			itemIdStateTaxRateMap = Utils.getStateTaxRate(new ArrayList<>(itemMap.keySet()), stateId);
1084
		}else{
1192
		} else {
1085
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1193
			itemIdIgstTaxRateMap = Utils.getIgstTaxRate(new ArrayList<>(itemMap.keySet()));
1086
		}
1194
		}
1087
		float cost = 0;
1195
		float cost = 0;
1088
		for(InventoryItem inventoryItem : inventoryItems){
1196
		for (InventoryItem inventoryItem : inventoryItems) {
1089
			if(stateId == null){
1197
			if (stateId == null) {
1090
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
1198
				fofoOrderItem.setIgstRate(itemIdIgstTaxRateMap.get(inventoryItem.getItemId()));
1091
			}else{
1199
			} else {
1092
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1200
				fofoOrderItem.setCgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getCgstRate());
1093
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1201
				fofoOrderItem.setSgstRate(itemIdStateTaxRateMap.get(inventoryItem.getItemId()).getSgstRate());
1094
			}
1202
			}
1095
			
1203
 
1096
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1204
			fofoOrderItem.setHsnCode(inventoryItem.getHsnCode());
1097
			break;
1205
			break;
1098
		}
1206
		}
1099
		for(InventoryItem inventoryItem : inventoryItems){
1207
		for (InventoryItem inventoryItem : inventoryItems) {
1100
			if(inventoryItem.getSerialNumber() != null) {
1208
			if (inventoryItem.getSerialNumber() != null) {
1101
				cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
1209
				cost += inventoryItem.getUnitPrice() - inventoryItem.getPriceDropAmount();
1102
			} else {
1210
			} else {
1103
				cost += inventoryItem.getUnitPrice();
1211
				cost += inventoryItem.getUnitPrice();
1104
			}
1212
			}
1105
		}
1213
		}
1106
		cost = cost/customFofoOrderItem.getQuantity();
1214
		cost = cost / customFofoOrderItem.getQuantity();
1107
		fofoOrderItem.setCost(cost);
1215
		fofoOrderItem.setCost(cost);
1108
		fofoOrderItem.setBrand(item.getBrand());
1216
		fofoOrderItem.setBrand(item.getBrand());
1109
		fofoOrderItem.setModelName(item.getModelName());
1217
		fofoOrderItem.setModelName(item.getModelName());
1110
		fofoOrderItem.setModelNumber(item.getModelNumber());
1218
		fofoOrderItem.setModelNumber(item.getModelNumber());
1111
		fofoOrderItem.setColor(item.getColor());
1219
		fofoOrderItem.setColor(item.getColor());
1112
		fofoOrderItemRepository.persist(fofoOrderItem);
1220
		fofoOrderItemRepository.persist(fofoOrderItem);
1113
		return fofoOrderItem;
1221
		return fofoOrderItem;
1114
	}
1222
	}
1115
	
1223
 
1116
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId, int itemId, int quantity) throws ProfitMandiBusinessException{
1224
	private void updateCurrentInventorySnapshot(List<CurrentInventorySnapshot> currentInventorySnapshots, int fofoId,
-
 
1225
			int itemId, int quantity) throws ProfitMandiBusinessException {
1117
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
1226
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1118
			if(currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId){
1227
			if (currentInventorySnapshot.getItemId() == itemId && currentInventorySnapshot.getFofoId() == fofoId) {
1119
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId, currentInventorySnapshot.getAvailability() - quantity);
1228
				currentInventorySnapshotRepository.updateAvailabilityByItemIdAndFofoId(itemId, fofoId,
-
 
1229
						currentInventorySnapshot.getAvailability() - quantity);
1120
			}
1230
			}
1121
		}
1231
		}
1122
	}
1232
	}
1123
	
1233
 
1124
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions) throws ProfitMandiBusinessException{
1234
	private void createPaymentOptions(FofoOrder fofoOrder, Set<CustomPaymentOption> customPaymentOptions)
-
 
1235
			throws ProfitMandiBusinessException {
1125
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
1236
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1126
			if(customPaymentOption.getAmount() > 0) {
1237
			if (customPaymentOption.getAmount() > 0) {
1127
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
1238
				PaymentOptionTransaction paymentOptionTransaction = new PaymentOptionTransaction();
1128
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
1239
				paymentOptionTransaction.setReferenceId(fofoOrder.getId());
1129
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1240
				paymentOptionTransaction.setPaymentOptionId(customPaymentOption.getPaymentOptionId());
1130
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1241
				paymentOptionTransaction.setReferenceType(PaymentOptionReferenceType.ORDER);
1131
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
1242
				paymentOptionTransaction.setAmount(customPaymentOption.getAmount());
1132
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
1243
				paymentOptionTransaction.setFofoId(fofoOrder.getFofoId());
1133
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
1244
				paymentOptionTransactionRepository.persist(paymentOptionTransaction);
1134
			}
1245
			}
1135
		}
1246
		}
1136
	}
1247
	}
1137
	
1248
 
-
 
1249
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId,
1138
	private FofoOrder createAndGetFofoOrder(int customerId, String customerGstNumber, int fofoId, InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId){
1250
			InvoiceNumberGenerationSequence invoiceNumberGenerationSequence, float totalAmount, int customerAddressId) {
1139
		FofoOrder fofoOrder = new FofoOrder();
1251
		FofoOrder fofoOrder = new FofoOrder();
1140
		fofoOrder.setCustomerGstNumber(customerGstNumber);
1252
		fofoOrder.setCustomerGstNumber(customerGstNumber);
1141
		fofoOrder.setCustomerId(customerId);
1253
		fofoOrder.setCustomerId(customerId);
1142
		fofoOrder.setFofoId(fofoId);
1254
		fofoOrder.setFofoId(fofoId);
-
 
1255
		fofoOrder.setInvoiceNumber(
1143
		fofoOrder.setInvoiceNumber(invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
1256
				invoiceNumberGenerationSequence.getPrefix() + "/" + invoiceNumberGenerationSequence.getSequence());
1144
		fofoOrder.setTotalAmount(totalAmount);
1257
		fofoOrder.setTotalAmount(totalAmount);
1145
		fofoOrder.setCustomerAddressId(customerAddressId);
1258
		fofoOrder.setCustomerAddressId(customerAddressId);
1146
		fofoOrderRepository.persist(fofoOrder);
1259
		fofoOrderRepository.persist(fofoOrder);
1147
		return fofoOrder;
1260
		return fofoOrder;
1148
	}
1261
	}
1149
	
1262
 
1150
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException{
1263
	private Customer createAndGetCustomer(CustomCustomer customCustomer) throws ProfitMandiBusinessException {
1151
		Customer customer = null;
1264
		Customer customer = null;
1152
		try{
1265
		try {
1153
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
1266
			customer = customerRepository.selectByMobileNumber(customCustomer.getMobileNumber());
1154
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1267
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
1155
			LOGGER.error("Customer not found with mobileNumber [{}]", customCustomer.getMobileNumber());
1268
			LOGGER.error("Customer not found with mobileNumber [{}]", customCustomer.getMobileNumber());
1156
			customer = new Customer();
1269
			customer = new Customer();
1157
		}
1270
		}
1158
		customer.setFirstName(customCustomer.getFirstName());
1271
		customer.setFirstName(customCustomer.getFirstName());
1159
		customer.setLastName(customCustomer.getLastName());
1272
		customer.setLastName(customCustomer.getLastName());
1160
		customer.setEmailId(customCustomer.getEmailId());
1273
		customer.setEmailId(customCustomer.getEmailId());
1161
		customer.setMobileNumber(customCustomer.getMobileNumber());
1274
		customer.setMobileNumber(customCustomer.getMobileNumber());
1162
		customerRepository.persist(customer);
1275
		customerRepository.persist(customer);
1163
		return customer;
1276
		return customer;
1164
	}
1277
	}
1165
	
1278
 
1166
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId, String fofoStoreCode){
1279
	private InvoiceNumberGenerationSequence createAndGetInvoiceNumberGenerationSequence(int fofoId,
-
 
1280
			String fofoStoreCode) {
1167
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1281
		InvoiceNumberGenerationSequence invoiceNumberGenerationSequence = null;
1168
		try{
1282
		try {
1169
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1283
			invoiceNumberGenerationSequence = invoiceNumberGenerationSequenceRepository.selectByFofoId(fofoId);
1170
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1284
			invoiceNumberGenerationSequence.setSequence(invoiceNumberGenerationSequence.getSequence() + 1);
1171
		}catch(ProfitMandiBusinessException profitMandiBusinessException){
1285
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
1172
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1286
			invoiceNumberGenerationSequence = new InvoiceNumberGenerationSequence();
1173
			invoiceNumberGenerationSequence.setFofoId(fofoId);
1287
			invoiceNumberGenerationSequence.setFofoId(fofoId);
1174
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
1288
			invoiceNumberGenerationSequence.setPrefix(fofoStoreCode);
1175
			invoiceNumberGenerationSequence.setSequence(1);
1289
			invoiceNumberGenerationSequence.setSequence(1);
1176
		}
1290
		}
1177
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1291
		invoiceNumberGenerationSequenceRepository.persist(invoiceNumberGenerationSequence);
1178
		return invoiceNumberGenerationSequence;
1292
		return invoiceNumberGenerationSequence;
1179
	}
1293
	}
1180
	
1294
 
-
 
1295
	private void validateItemsSerializedNonSerialized(List<Item> items,
1181
	private void validateItemsSerializedNonSerialized(List<Item> items, Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException{
1296
			Map<Integer, CustomFofoOrderItem> customFofoOrderItemMap) throws ProfitMandiBusinessException {
1182
 		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1297
		List<Integer> invalidItemIdSerialNumbers = new ArrayList<Integer>();
1183
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1298
		List<Integer> itemIdNonSerializedSerialNumbers = new ArrayList<Integer>();
1184
		for (Item i : items){
1299
		for (Item i : items) {
1185
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1300
			CustomFofoOrderItem customFofoOrderItem = customFofoOrderItemMap.get(i.getId());
1186
			if (i.getType().equals(ItemType.SERIALIZED)){
1301
			if (i.getType().equals(ItemType.SERIALIZED)) {
1187
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()){
1302
				if (customFofoOrderItem == null || customFofoOrderItem.getSerialNumberDetails().isEmpty()) {
1188
					invalidItemIdSerialNumbers.add(i.getId());
1303
					invalidItemIdSerialNumbers.add(i.getId());
1189
				}
1304
				}
1190
			}else{
1305
			} else {
-
 
1306
				Set<String> serialNumbers = this
1191
				Set<String> serialNumbers = this.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1307
						.serialNumberDetailsToSerialNumbers(customFofoOrderItem.getSerialNumberDetails());
1192
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()){
1308
				if (customFofoOrderItem == null || !serialNumbers.isEmpty()) {
1193
					itemIdNonSerializedSerialNumbers.add(i.getId());
1309
					itemIdNonSerializedSerialNumbers.add(i.getId());
1194
				}
1310
				}
1195
			}
1311
			}
1196
		}
1312
		}
1197
 
1313
 
1198
		if(!invalidItemIdSerialNumbers.isEmpty()){
1314
		if (!invalidItemIdSerialNumbers.isEmpty()) {
1199
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1315
			LOGGER.error("Invalid itemId's serialNumbers for serialized{}", invalidItemIdSerialNumbers);
1200
			// itemId's are serialized you are saying these are not serialized
1316
			// itemId's are serialized you are saying these are not serialized
1201
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers, "FFORDR_1013");
1317
			throw new ProfitMandiBusinessException("invalidItemIdSerialNumbers", invalidItemIdSerialNumbers,
-
 
1318
					"FFORDR_1013");
1202
		}
1319
		}
1203
 
1320
 
1204
		if(!itemIdNonSerializedSerialNumbers.isEmpty()){
1321
		if (!itemIdNonSerializedSerialNumbers.isEmpty()) {
1205
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1322
			LOGGER.error("Invalid itemId's serialNumbers for non serialized{}", itemIdNonSerializedSerialNumbers);
1206
			// itemId's are non serialized you are saying these are serialized
1323
			// itemId's are non serialized you are saying these are serialized
1207
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers, "FFORDR_1014");
1324
			throw new ProfitMandiBusinessException("itemIdNonSerializedSerialNumbers", itemIdNonSerializedSerialNumbers,
-
 
1325
					"FFORDR_1014");
1208
		}
1326
		}
1209
	}
1327
	}
1210
	
1328
 
1211
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots, Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException{
1329
	private void validateCurrentInventorySnapshotQuantities(List<CurrentInventorySnapshot> currentInventorySnapshots,
-
 
1330
			Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap) throws ProfitMandiBusinessException {
1212
		if(itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()){
1331
		if (itemIdCustomFofoOrderItemMap.keySet().size() != currentInventorySnapshots.size()) {
1213
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1332
			throw new ProfitMandiBusinessException("quantiiesSize", currentInventorySnapshots.size(), "");
1214
		}
1333
		}
1215
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); //this is for error
1334
		List<ItemIdQuantityAvailability> itemIdQuantityAvailabilities = new ArrayList<>(); // this is for error
1216
		LOGGER.info("currentInventorySnapshots "+currentInventorySnapshots);
1335
		LOGGER.info("currentInventorySnapshots " + currentInventorySnapshots);
1217
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
1336
		LOGGER.info("CustomFofoLineItemMap {}", itemIdCustomFofoOrderItemMap);
1218
		for(CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots){
1337
		for (CurrentInventorySnapshot currentInventorySnapshot : currentInventorySnapshots) {
1219
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap.get(currentInventorySnapshot.getItemId());
1338
			CustomFofoOrderItem customFofoOrderItem = itemIdCustomFofoOrderItemMap
-
 
1339
					.get(currentInventorySnapshot.getItemId());
1220
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1340
			LOGGER.info("customFofoOrderItem {}", customFofoOrderItem);
1221
			if(customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()){
1341
			if (customFofoOrderItem.getQuantity() > currentInventorySnapshot.getAvailability()) {
1222
					ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1342
				ItemIdQuantityAvailability itemIdQuantityAvailability = new ItemIdQuantityAvailability();
1223
					itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1343
				itemIdQuantityAvailability.setItemId(customFofoOrderItem.getItemId());
1224
					Quantity quantity = new Quantity();
1344
				Quantity quantity = new Quantity();
1225
					quantity.setAvailable(currentInventorySnapshot.getAvailability());
1345
				quantity.setAvailable(currentInventorySnapshot.getAvailability());
1226
					quantity.setRequested(customFofoOrderItem.getQuantity());
1346
				quantity.setRequested(customFofoOrderItem.getQuantity());
1227
					itemIdQuantityAvailability.setQuantity(quantity);
1347
				itemIdQuantityAvailability.setQuantity(quantity);
1228
					itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1348
				itemIdQuantityAvailabilities.add(itemIdQuantityAvailability);
1229
				}
1349
			}
1230
		}
1350
		}
1231
 
1351
 
1232
		if(!itemIdQuantityAvailabilities.isEmpty()){
1352
		if (!itemIdQuantityAvailabilities.isEmpty()) {
1233
			// itemIdQuantity request is not valid
1353
			// itemIdQuantity request is not valid
1234
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}", itemIdQuantityAvailabilities);
1354
			LOGGER.error("Requested quantities should not be greater than currently available quantities {}",
-
 
1355
					itemIdQuantityAvailabilities);
1235
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities, "FFORDR_1015");
1356
			throw new ProfitMandiBusinessException("itemIdQuantityAvailabilities", itemIdQuantityAvailabilities,
-
 
1357
					"FFORDR_1015");
1236
		}
1358
		}
1237
	}
1359
	}
1238
	
1360
 
1239
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap, String serialNumber){
1361
	private int getItemIdFromSerialNumber(Map<Integer, CustomFofoOrderItem> itemIdCustomFofoOrderItemMap,
-
 
1362
			String serialNumber) {
1240
		int itemId = 0;
1363
		int itemId = 0;
1241
		for(Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()){
1364
		for (Map.Entry<Integer, CustomFofoOrderItem> entry : itemIdCustomFofoOrderItemMap.entrySet()) {
1242
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1365
			Set<SerialNumberDetail> serialNumberDetails = entry.getValue().getSerialNumberDetails();
1243
			for(SerialNumberDetail serialNumberDetail : serialNumberDetails){
1366
			for (SerialNumberDetail serialNumberDetail : serialNumberDetails) {
1244
				if(serialNumberDetail.getSerialNumber().equals(serialNumber)){
1367
				if (serialNumberDetail.getSerialNumber().equals(serialNumber)) {
1245
					itemId = entry.getKey();
1368
					itemId = entry.getKey();
1246
					break;
1369
					break;
1247
				}
1370
				}
1248
			}
1371
			}
1249
		}
1372
		}
1250
		return itemId;
1373
		return itemId;
1251
	}
1374
	}
1252
	
1375
 
1253
	private Map<Integer, Item> toItemMap(List<Item> items){
1376
	private Map<Integer, Item> toItemMap(List<Item> items) {
1254
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1377
		Function<Item, Integer> itemIdFunction = new Function<Item, Integer>() {
1255
			@Override
1378
			@Override
1256
			public Integer apply(Item item) {
1379
			public Integer apply(Item item) {
1257
				return item.getId();
1380
				return item.getId();
1258
			}
1381
			}
Line 1264... Line 1387...
1264
			}
1387
			}
1265
		};
1388
		};
1266
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
1389
		return items.stream().collect(Collectors.toMap(itemIdFunction, itemFunction));
1267
	}
1390
	}
1268
 
1391
 
1269
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress){
1392
	private void setCustomerAddress(CustomerAddress customerAddress, CustomAddress customAddress) {
1270
		customerAddress.setName(customAddress.getName());
1393
		customerAddress.setName(customAddress.getName());
1271
		customerAddress.setLine1(customAddress.getLine1());
1394
		customerAddress.setLine1(customAddress.getLine1());
1272
		customerAddress.setLine2(customAddress.getLine2());
1395
		customerAddress.setLine2(customAddress.getLine2());
1273
		customerAddress.setLandmark(customAddress.getLandmark());
1396
		customerAddress.setLandmark(customAddress.getLandmark());
1274
		customerAddress.setCity(customAddress.getCity());
1397
		customerAddress.setCity(customAddress.getCity());
Line 1276... Line 1399...
1276
		customerAddress.setState(customAddress.getState());
1399
		customerAddress.setState(customAddress.getState());
1277
		customerAddress.setCountry(customAddress.getCountry());
1400
		customerAddress.setCountry(customAddress.getCountry());
1278
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1401
		customerAddress.setPhoneNumber(customAddress.getPhoneNumber());
1279
	}
1402
	}
1280
 
1403
 
1281
	private CustomAddress createCustomAddress(Address address){
1404
	private CustomAddress createCustomAddress(Address address) {
1282
		CustomAddress customAddress = new CustomAddress();
1405
		CustomAddress customAddress = new CustomAddress();
1283
		customAddress.setName(address.getName());
1406
		customAddress.setName(address.getName());
1284
		customAddress.setLine1(address.getLine1());
1407
		customAddress.setLine1(address.getLine1());
1285
		customAddress.setLine2(address.getLine2());
1408
		customAddress.setLine2(address.getLine2());
1286
		customAddress.setLandmark(address.getLandmark());
1409
		customAddress.setLandmark(address.getLandmark());
Line 1290... Line 1413...
1290
		customAddress.setCountry(address.getCountry());
1413
		customAddress.setCountry(address.getCountry());
1291
		customAddress.setPhoneNumber(address.getPhoneNumber());
1414
		customAddress.setPhoneNumber(address.getPhoneNumber());
1292
		return customAddress;
1415
		return customAddress;
1293
	}
1416
	}
1294
 
1417
 
1295
	private CustomAddress createCustomAddress(CustomerAddress customerAddress){
1418
	private CustomAddress createCustomAddress(CustomerAddress customerAddress) {
1296
		CustomAddress customAddress = new CustomAddress();
1419
		CustomAddress customAddress = new CustomAddress();
1297
		customAddress.setName(customerAddress.getName());
1420
		customAddress.setName(customerAddress.getName());
1298
		customAddress.setLine1(customerAddress.getLine1());
1421
		customAddress.setLine1(customerAddress.getLine1());
1299
		customAddress.setLine2(customerAddress.getLine2());
1422
		customAddress.setLine2(customerAddress.getLine2());
1300
		customAddress.setLandmark(customerAddress.getLandmark());
1423
		customAddress.setLandmark(customerAddress.getLandmark());
Line 1304... Line 1427...
1304
		customAddress.setCountry(customerAddress.getCountry());
1427
		customAddress.setCountry(customerAddress.getCountry());
1305
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1428
		customAddress.setPhoneNumber(customerAddress.getPhoneNumber());
1306
		return customAddress;
1429
		return customAddress;
1307
	}
1430
	}
1308
 
1431
 
1309
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount) throws ProfitMandiBusinessException
1432
	private void validatePaymentOptionsAndTotalAmount(Set<CustomPaymentOption> customPaymentOptions, float totalAmount)
1310
	{
-
 
-
 
1433
			throws ProfitMandiBusinessException {
1311
		Set<Integer> paymentOptionIds = new HashSet<>();
1434
		Set<Integer> paymentOptionIds = new HashSet<>();
1312
		
1435
 
1313
		float calculatedAmount = 0;
1436
		float calculatedAmount = 0;
1314
		for(CustomPaymentOption customPaymentOption : customPaymentOptions){
1437
		for (CustomPaymentOption customPaymentOption : customPaymentOptions) {
1315
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1438
			paymentOptionIds.add(customPaymentOption.getPaymentOptionId());
1316
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
1439
			calculatedAmount = calculatedAmount + customPaymentOption.getAmount();
1317
		}
1440
		}
1318
		if(calculatedAmount != totalAmount){
1441
		if (calculatedAmount != totalAmount) {
1319
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]", calculatedAmount, totalAmount);
1442
			LOGGER.warn("Error occured while validating payment options amount[{}] != TotalAmount [{}]",
-
 
1443
					calculatedAmount, totalAmount);
1320
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT, calculatedAmount, "FFORDR_1016");
1444
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_CALCULATED_AMOUNT,
-
 
1445
					calculatedAmount, "FFORDR_1016");
1321
		}
1446
		}
1322
		
1447
 
1323
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
1448
		List<Integer> foundPaymentOptionIds = paymentOptionRepository.selectIdsByIds(paymentOptionIds);
1324
		if(foundPaymentOptionIds.size() != paymentOptionIds.size()) {
1449
		if (foundPaymentOptionIds.size() != paymentOptionIds.size()) {
1325
			paymentOptionIds.removeAll(foundPaymentOptionIds);
1450
			paymentOptionIds.removeAll(foundPaymentOptionIds);
1326
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds, "FFORDR_1017");
1451
			throw new ProfitMandiBusinessException(ProfitMandiConstants.PAYMENT_OPTION_ID, paymentOptionIds,
-
 
1452
					"FFORDR_1017");
1327
		}
1453
		}
1328
	}
1454
	}
1329
	
1455
 
1330
	@Override
1456
	@Override
1331
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1457
	public List<FofoOrderItem> getByOrderId(int orderId) throws ProfitMandiBusinessException {
1332
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1458
		List<FofoOrderItem> fofoOrderItems = fofoOrderItemRepository.selectByOrderId(orderId);
1333
		if(!fofoOrderItems.isEmpty()){
1459
		if (!fofoOrderItems.isEmpty()) {
1334
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1460
			List<FofoOrderItem> newFofoOrderItems = new ArrayList<>();
1335
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1461
			Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = this
-
 
1462
					.toFofoOrderItemIdFofoLineItems(fofoOrderItems);
1336
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1463
			Iterator<FofoOrderItem> fofoOrderItemsIterator = fofoOrderItems.iterator();
1337
			while(fofoOrderItemsIterator.hasNext()){
1464
			while (fofoOrderItemsIterator.hasNext()) {
1338
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1465
				FofoOrderItem fofoOrderItem = fofoOrderItemsIterator.next();
1339
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1466
				fofoOrderItem.setFofoLineItems(fofoOrderItemIdFofoLineItemsMap.get(fofoOrderItem.getId()));
1340
				newFofoOrderItems.add(fofoOrderItem);
1467
				newFofoOrderItems.add(fofoOrderItem);
1341
				fofoOrderItemsIterator.remove();
1468
				fofoOrderItemsIterator.remove();
1342
			}
1469
			}
1343
			fofoOrderItems = newFofoOrderItems;
1470
			fofoOrderItems = newFofoOrderItems;
1344
		}
1471
		}
1345
		return fofoOrderItems;
1472
		return fofoOrderItems;
1346
	}
1473
	}
1347
	
1474
 
1348
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems){
1475
	private Set<Integer> toFofoOrderItemIds(List<FofoOrderItem> fofoOrderItems) {
1349
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1476
		Function<FofoOrderItem, Integer> fofoOrderItemToFofoOrderItemIdFunction = new Function<FofoOrderItem, Integer>() {
1350
			@Override
1477
			@Override
1351
			public Integer apply(FofoOrderItem fofoOrderItem) {
1478
			public Integer apply(FofoOrderItem fofoOrderItem) {
1352
				return fofoOrderItem.getId();
1479
				return fofoOrderItem.getId();
1353
			}
1480
			}
1354
		};
1481
		};
1355
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
1482
		return fofoOrderItems.stream().map(fofoOrderItemToFofoOrderItemIdFunction).collect(Collectors.toSet());
1356
	}
1483
	}
1357
	
1484
 
1358
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems){
1485
	private Map<Integer, Set<FofoLineItem>> toFofoOrderItemIdFofoLineItems(List<FofoOrderItem> fofoOrderItems) {
1359
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1486
		Set<Integer> fofoOrderItemIds = this.toFofoOrderItemIds(fofoOrderItems);
1360
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1487
		List<FofoLineItem> fofoLineItems = fofoLineItemRepository.selectByFofoOrderItemIds(fofoOrderItemIds);
1361
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1488
		Map<Integer, Set<FofoLineItem>> fofoOrderItemIdFofoLineItemsMap = new HashMap<>();
1362
		for(FofoLineItem fofoLineItem : fofoLineItems){
1489
		for (FofoLineItem fofoLineItem : fofoLineItems) {
1363
			if(!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())){
1490
			if (!fofoOrderItemIdFofoLineItemsMap.containsKey(fofoLineItem.getFofoOrderItemId())) {
1364
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1491
				Set<FofoLineItem> fofoLineItems2 = new HashSet<>();
1365
				fofoLineItems2.add(fofoLineItem);
1492
				fofoLineItems2.add(fofoLineItem);
1366
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1493
				fofoOrderItemIdFofoLineItemsMap.put(fofoLineItem.getFofoOrderItemId(), fofoLineItems2);
1367
			}else{
1494
			} else {
1368
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1495
				fofoOrderItemIdFofoLineItemsMap.get(fofoLineItem.getFofoOrderItemId()).add(fofoLineItem);
1369
			}
1496
			}
1370
		}
1497
		}
1371
		return fofoOrderItemIdFofoLineItemsMap;
1498
		return fofoOrderItemIdFofoLineItemsMap;
1372
	}
1499
	}
1373
	
1500
 
1374
	private String getOtpString(){
1501
	private String getOtpString() {
1375
		Random rndm_method = new Random();
1502
		Random rndm_method = new Random();
1376
		String numbers ="0123456789";
1503
		String numbers = "0123456789";
1377
		char[] otp = new char[5];
1504
		char[] otp = new char[5];
1378
 
1505
 
1379
		for (int i = 0; i < 5; i++){
1506
		for (int i = 0; i < 5; i++) {
1380
			otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
1507
			otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
1381
		}
1508
		}
1382
		return String.valueOf(otp);
1509
		return String.valueOf(otp);
1383
	}
1510
	}
1384
	
1511
 
1385
	private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount){
1512
	private void sendOtp(String otp_text, String phone, Map<Integer, Float> itemIdAdvanceAmount) {
1386
		Map<Integer, String> itemIdDescriptionMap = inventoryService.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());
1513
		Map<Integer, String> itemIdDescriptionMap = inventoryService
-
 
1514
				.getItemIdDescriptionMap(itemIdAdvanceAmount.keySet());
1387
		StringBuilder itemIdAdvanceAmountString = new StringBuilder();
1515
		StringBuilder itemIdAdvanceAmountString = new StringBuilder();
1388
		int index = 0;
1516
		int index = 0;
1389
		for(Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {
1517
		for (Map.Entry<Integer, Float> itemIdAdvanceAmountEntry : itemIdAdvanceAmount.entrySet()) {
1390
			itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));
1518
			itemIdAdvanceAmountString.append(itemIdDescriptionMap.get(itemIdAdvanceAmountEntry.getKey()));
1391
			itemIdAdvanceAmountString.append("'s Advance amount [");
1519
			itemIdAdvanceAmountString.append("'s Advance amount [");
1392
			itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());
1520
			itemIdAdvanceAmountString.append(itemIdAdvanceAmountEntry.getValue());
1393
			itemIdAdvanceAmountString.append("]");
1521
			itemIdAdvanceAmountString.append("]");
1394
			if(index + 1 < itemIdAdvanceAmount.size()) {
1522
			if (index + 1 < itemIdAdvanceAmount.size()) {
1395
				itemIdAdvanceAmountString.append(", ");
1523
				itemIdAdvanceAmountString.append(", ");
1396
			}
1524
			}
1397
			index++;
1525
			index++;
1398
		}
1526
		}
1399
		String text = "Dear Customer, {0} is the OTP that you have requested for prebooking orders for items {1} Don't share your OTP with anyone.";
1527
		String text = "Dear Customer, {0} is the OTP that you have requested for prebooking orders for items {1} Don't share your OTP with anyone.";
1400
		LOGGER.info("OTP to Customer Successfully sends"+text);
1528
		LOGGER.info("OTP to Customer Successfully sends" + text);
1401
		String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);
1529
		String msg = java.text.MessageFormat.format(text, otp_text, itemIdAdvanceAmountString);
1402
		try {
1530
		try {
1403
			Utils.sendSms(msg, phone);
1531
			Utils.sendSms(msg, phone);
1404
		} catch (URISyntaxException e) {
1532
		} catch (URISyntaxException e) {
1405
			// TODO Auto-generated catch block
1533
			// TODO Auto-generated catch block
1406
			e.printStackTrace();
1534
			e.printStackTrace();
1407
		} catch (IOException e) {
1535
		} catch (IOException e) {
1408
			// TODO Auto-generated catch block
1536
			// TODO Auto-generated catch block
1409
			e.printStackTrace();
1537
			e.printStackTrace();
1410
		}
1538
		}
1411
		
1539
 
1412
	}
1540
	}
1413
	
1541
 
1414
	@Override
1542
	@Override
1415
	public int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber, Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {
1543
	public int generatePrebookingOrdersOtp(String customerEmailId, String customerMobileNumber,
-
 
1544
			Map<Integer, Float> itemIdAdvanceAmount) throws ProfitMandiBusinessException {
1416
		if(!StringUtils.isValidEmailAddress(customerEmailId)){
1545
		if (!StringUtils.isValidEmailAddress(customerEmailId)) {
1417
			LOGGER.error("invalid customer emailId {} ", customerEmailId);
1546
			LOGGER.error("invalid customer emailId {} ", customerEmailId);
1418
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");
1547
			throw new ProfitMandiBusinessException(ProfitMandiConstants.EMAIL_ID, customerEmailId, "VE_1016");
1419
		}
1548
		}
1420
 
1549
 
1421
		if(!StringUtils.isValidMobile(customerMobileNumber)){
1550
		if (!StringUtils.isValidMobile(customerMobileNumber)) {
1422
			LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);
1551
			LOGGER.error("invalid customer mobileNumber {} ", customerMobileNumber);
1423
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");
1552
			throw new ProfitMandiBusinessException(ProfitMandiConstants.MOBILE_NUMBER, customerMobileNumber, "VE_1071");
1424
		}
1553
		}
1425
		
1554
 
1426
		List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);
1555
		List<Otp> otps = otpRepository.selectAllByEmailWithTime(customerEmailId);
1427
		String otp = null;
1556
		String otp = null;
1428
		if (otps.size() >= 5){
1557
		if (otps.size() >= 5) {
1429
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId, "FFORDR_1019");
1558
			throw new ProfitMandiBusinessException(ProfitMandiConstants.CUSTOMER_EMAIL_ID, customerEmailId,
-
 
1559
					"FFORDR_1019");
1430
		}
1560
		}
1431
		if (!otps.isEmpty()){
1561
		if (!otps.isEmpty()) {
1432
			if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))){
1562
			if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(2))) {
1433
				return otps.get(0).getId();
1563
				return otps.get(0).getId();
1434
			}else if(otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))){
1564
			} else if (otps.get(0).getCreatedOn().isAfter(LocalDateTime.now().minusMinutes(10))) {
1435
				otp = otps.get(0).getOtp();
1565
				otp = otps.get(0).getOtp();
1436
			}
1566
			}
1437
		}
1567
		}
1438
		if (otp == null || otp.isEmpty()){
1568
		if (otp == null || otp.isEmpty()) {
1439
			otp = getOtpString();
1569
			otp = getOtpString();
1440
		}
1570
		}
1441
		
1571
 
1442
		this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);
1572
		this.sendOtp(otp, customerMobileNumber, itemIdAdvanceAmount);
1443
		
1573
 
1444
		Otp otp_bean = new Otp();
1574
		Otp otp_bean = new Otp();
1445
		otp_bean.setEmail(customerEmailId);
1575
		otp_bean.setEmail(customerEmailId);
1446
		otp_bean.setMobile(customerMobileNumber);
1576
		otp_bean.setMobile(customerMobileNumber);
1447
		otp_bean.setOtp(otp);
1577
		otp_bean.setOtp(otp);
1448
		otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);
1578
		otp_bean.setOtpType(OtpType.PREBOOKING_ORDER);
1449
		otp_bean.setCreatedOn(LocalDateTime.now());
1579
		otp_bean.setCreatedOn(LocalDateTime.now());
1450
		otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
1580
		otp_bean.setExpiryTimestamp(LocalDateTime.now().plusMinutes(10));
1451
		otpRepository.persist(otp_bean);
1581
		otpRepository.persist(otp_bean);
1452
		
1582
 
1453
		return otp_bean.getId();
1583
		return otp_bean.getId();
1454
	}
1584
	}
1455
	
1585
 
1456
	@Override
1586
	@Override
1457
	public String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)
1587
	public String validateOtp(String customerEmailId, String customerMobileNumber, int otpId, String otpValue)
1458
			throws ProfitMandiBusinessException {
1588
			throws ProfitMandiBusinessException {
1459
		Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);
1589
		Otp otp = otpRepository.selectByIdEmailIdMobileNumber(otpId, customerEmailId, customerMobileNumber);
1460
		otp.setTryCount(otp.getTryCount() + 1);
1590
		otp.setTryCount(otp.getTryCount() + 1);
1461
		if (!otp.getOtp().equalsIgnoreCase(otpValue)){
1591
		if (!otp.getOtp().equalsIgnoreCase(otpValue)) {
1462
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");
1592
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1020");
1463
		}
1593
		}
1464
		if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())){
1594
		if (otp.isExpired() || otp.isVerified() || otp.getExpiryTimestamp().isBefore(LocalDateTime.now())) {
1465
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");
1595
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1021");
1466
		}
1596
		}
1467
		if (otp.getTryCount() >5){
1597
		if (otp.getTryCount() > 5) {
1468
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");
1598
			throw new ProfitMandiBusinessException("otpValue", otpValue, "FFORDR_1022");
1469
		}
1599
		}
1470
		otp.setExpired(true);
1600
		otp.setExpired(true);
1471
		otp.setVerified(true);
1601
		otp.setVerified(true);
1472
		otpRepository.persist(otp);
1602
		otpRepository.persist(otp);
1473
		
1603
 
1474
		return ResponseCodeHolder.getMessage("FFORDR_OK_1002");
1604
		return ResponseCodeHolder.getMessage("FFORDR_OK_1002");
1475
	}
1605
	}
1476
	
1606
 
1477
	@Override
1607
	@Override
1478
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber) throws ProfitMandiBusinessException {
1608
	public void updateCustomerDetails(CustomCustomer customCustomer, String invoiceNumber)
-
 
1609
			throws ProfitMandiBusinessException {
1479
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1610
		FofoOrder fofoOrder = fofoOrderRepository.selectByInvoiceNumber(invoiceNumber);
1480
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1611
		Customer customer = customerRepository.selectById(fofoOrder.getCustomerId());
1481
		customer.setFirstName(customCustomer.getFirstName());
1612
		customer.setFirstName(customCustomer.getFirstName());
1482
		customer.setLastName(customCustomer.getLastName());
1613
		customer.setLastName(customCustomer.getLastName());
1483
		customerRepository.persist(customer);
1614
		customerRepository.persist(customer);
Line 1485... Line 1616...
1485
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1616
		this.setCustomerAddress(customerAddress, customCustomer.getAddress());
1486
		customerAddressRepository.persist(customerAddress);
1617
		customerAddressRepository.persist(customerAddress);
1487
	}
1618
	}
1488
 
1619
 
1489
	@Override
1620
	@Override
1490
	public void badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest) throws ProfitMandiBusinessException{
1621
	public void badReturn(int fofoId, FoiBadReturnRequest foiBadReturnRequest) throws ProfitMandiBusinessException {
1491
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFoiId());
1622
		FofoOrderItem foi = fofoOrderItemRepository.selectById(foiBadReturnRequest.getFoiId());
-
 
1623
		FofoOrder fofoOrder = fofoOrderRepository.selectByOrderId(foi.getOrderId());
1492
		if(fofoOrderRepository.selectByOrderId(foi.getOrderId()).getFofoId()==fofoId) {
1624
		if (fofoOrderRepository.selectByOrderId(foi.getOrderId()).getFofoId() == fofoId) {
1493
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1625
			throw new ProfitMandiBusinessException("Partner Auth", "", "Invalid Order");
1494
		}
1626
		}
-
 
1627
		List<CustomerReturnItem> customerReturnItems = new ArrayList<>();
1495
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getBadReturnArr()) {
1628
		for (BadReturnRequest badReturnRequest : foiBadReturnRequest.getBadReturnArr()) {
-
 
1629
			CustomerReturnItem customerReturnItem = new CustomerReturnItem();
-
 
1630
			customerReturnItem.setFofoId(fofoId);
-
 
1631
			customerReturnItem.setFofoOrderItemId(foiBadReturnRequest.getFoiId());
1496
			badReturnRequest.getInventoryItemId();
1632
			customerReturnItem.setInventoryItemId(badReturnRequest.getInventoryItemId());
1497
			badReturnRequest.getRemarks();
1633
			customerReturnItem.setQuantity(1);
1498
			
-
 
-
 
1634
			customerReturnItem.setType(ReturnType.BAD);
-
 
1635
			//customerReturnItemRepository.persist(customerReturnItem);
-
 
1636
			inventoryService.saleReturnInventoryItem(customerReturnItem);
-
 
1637
			customerReturnItems.add(customerReturnItem);
1499
		}
1638
		}
-
 
1639
		generateCreditNote(fofoOrder, customerReturnItems);
1500
		
1640
 
1501
	}
1641
	}
1502
	
1642
 
1503
	/*private CreditNotePdfModel generateCreditNote(FofoOrder fofoOrder, List<InventoryItem> inventoryItems,
1643
	private CreditNotePdfModel generateCreditNote(FofoOrder fofoOrder, List<CustomerReturnItem> customerReturnItems) throws ProfitMandiBusinessException {
1504
			CustomRetailer customRetailer, CustomCustomer customCustomer) throws Exception {
-
 
1505
 
1644
 
1506
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
1645
		InvoiceNumberGenerationSequence sequence = invoiceNumberGenerationSequenceRepository
1507
				.selectByFofoId(purchase.getFofoId());
1646
				.selectByFofoId(fofoOrder.getFofoId());
1508
		sequence.setReturnSequence(sequence.getReturnSequence() + 1);
1647
		sequence.setCreditNoteSequence(sequence.getCreditNoteSequence() + 1);
1509
		invoiceNumberGenerationSequenceRepository.persist(sequence);
1648
		invoiceNumberGenerationSequenceRepository.persist(sequence);
-
 
1649
		
1510
		String debitNoteNumber = sequence.getPrefix() + "/" + sequence.getReturnSequence();
1650
		String creditNoteNumber = sequence.getPrefix() + "/" + sequence.getReturnSequence();
1511
 
-
 
1512
		DebitNote debitNote = new DebitNote();
1651
		CustomerCreditNote creditNote = new CustomerCreditNote();
1513
		debitNote.setDebitNoteNumber(debitNoteNumber);
1652
		creditNote.setCreditNoteNumber(creditNoteNumber);
1514
		debitNote.setFofoId(purchase.getFofoId());
1653
		creditNote.setFofoId(fofoOrder.getFofoId());
-
 
1654
		creditNote.setCreditNoteNumber(creditNoteNumber);
1515
		debitNoteRepository.persist(debitNote);
1655
		customerCreditNoteRepository.persist(creditNote);
1516
 
1656
		
1517
		for (InventoryItem inventoryItem : inventoryItems) {
-
 
1518
			PurchaseReturnItem purchaseReturnItem = purchaseReturnItemRepository
1657
		for (CustomerReturnItem customerReturnItem : customerReturnItems) {
1519
					.selectByInventoryItemId(inventoryItem.getId());
-
 
1520
			purchaseReturnItem.setStatus(PurchaseReturnStatus.DEBIT_NOTE_CREATED);
-
 
1521
			purchaseReturnItem.setDebitNoteId(debitNote.getId());
1658
			customerReturnItem.setCreditNoteId(creditNote.getId());
1522
			purchaseReturnItemRepository.persist(purchaseReturnItem);
1659
			customerReturnItemRepository.persist(customerReturnItem);
1523
		}
1660
		}
1524
		this.returnInventoryItems(inventoryItems, debitNote);
1661
		//this.returnInventoryItems(inventoryItems, debitNote);
1525
 
1662
 
1526
		return getDebitNotePdfModel(debitNote, inventoryItems);
1663
		return getCreditNotePdfModel(creditNote, customerReturnItems);
1527
	}*/
1664
	}
-
 
1665
	
-
 
1666
	private CreditNotePdfModel getCreditNotePdfModel(CustomerCreditNote creditNote, List<CustomerReturnItem> customerReturnItems) {
-
 
1667
		PdfModel pdfModel = new PdfModel();
-
 
1668
		pdfModel.setAuther("NSSPL");
-
 
1669
		CreditNotePdfModel creditNotePdfModel = new CreditNotePdfModel();
-
 
1670
		creditNotePdfModel.setCreditNoteDate(FormattingUtils.formatDate(creditNote.getCreateTimestamp()));
-
 
1671
		creditNotePdfModel.setCreditNoteNumber(creditNote.getCreditNoteNumber());
-
 
1672
		creditNotePdfModel.setPdfModel(pdfModel);
-
 
1673
		return creditNotePdfModel;
-
 
1674
	}
1528
 
1675
 
1529
}
1676
}