Subversion Repositories SmartDukaan

Rev

Rev 28346 | Rev 28908 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
22980 ashik.ali 1
package com.spice.profitmandi.service.user;
2
 
26528 amit.gupta 3
import java.nio.charset.StandardCharsets;
23300 amit.gupta 4
import java.time.LocalDateTime;
23060 ashik.ali 5
import java.util.ArrayList;
22980 ashik.ali 6
import java.util.HashMap;
23781 ashik.ali 7
import java.util.HashSet;
22980 ashik.ali 8
import java.util.List;
9
import java.util.Map;
10
import java.util.Set;
11
import java.util.function.Function;
12
import java.util.stream.Collectors;
26962 amit.gupta 13
import java.util.stream.Stream;
22980 ashik.ali 14
 
23781 ashik.ali 15
import org.apache.logging.log4j.LogManager;
23568 govind 16
import org.apache.logging.log4j.Logger;
22980 ashik.ali 17
import org.springframework.beans.factory.annotation.Autowired;
23043 ashik.ali 18
import org.springframework.beans.factory.annotation.Qualifier;
24349 amit.gupta 19
import org.springframework.cache.annotation.Cacheable;
22980 ashik.ali 20
import org.springframework.stereotype.Component;
21
 
26528 amit.gupta 22
import com.google.common.hash.Hashing;
22980 ashik.ali 23
import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
23025 ashik.ali 24
import com.spice.profitmandi.common.model.CustomAddress;
23509 amit.gupta 25
import com.spice.profitmandi.common.model.CustomRetailer;
23025 ashik.ali 26
import com.spice.profitmandi.common.model.CustomShop;
23781 ashik.ali 27
import com.spice.profitmandi.common.model.MapWrapper;
23329 ashik.ali 28
import com.spice.profitmandi.common.model.ProfitMandiConstants;
23025 ashik.ali 29
import com.spice.profitmandi.common.model.UpdateRetailerRequest;
23329 ashik.ali 30
import com.spice.profitmandi.common.util.StringUtils;
31
import com.spice.profitmandi.common.util.Utils;
32
import com.spice.profitmandi.dao.entity.dtr.DistrictMaster;
22980 ashik.ali 33
import com.spice.profitmandi.dao.entity.dtr.Retailer;
28024 tejbeer 34
import com.spice.profitmandi.dao.entity.dtr.RetailerBlockBrands;
23043 ashik.ali 35
import com.spice.profitmandi.dao.entity.dtr.RetailerRegisteredAddress;
23781 ashik.ali 36
import com.spice.profitmandi.dao.entity.dtr.Role;
22980 ashik.ali 37
import com.spice.profitmandi.dao.entity.dtr.Shop;
38
import com.spice.profitmandi.dao.entity.dtr.ShopAddress;
39
import com.spice.profitmandi.dao.entity.dtr.User;
23269 ashik.ali 40
import com.spice.profitmandi.dao.entity.dtr.UserAccount;
22980 ashik.ali 41
import com.spice.profitmandi.dao.entity.dtr.UserRole;
23365 ashik.ali 42
import com.spice.profitmandi.dao.entity.fofo.FofoPartnerPaymentOption;
23329 ashik.ali 43
import com.spice.profitmandi.dao.entity.fofo.FofoStore;
23365 ashik.ali 44
import com.spice.profitmandi.dao.entity.fofo.PaymentOption;
24349 amit.gupta 45
import com.spice.profitmandi.dao.entity.inventory.State;
22980 ashik.ali 46
import com.spice.profitmandi.dao.entity.user.Address;
23043 ashik.ali 47
import com.spice.profitmandi.dao.entity.user.Cart;
23329 ashik.ali 48
import com.spice.profitmandi.dao.entity.user.Counter;
26522 amit.gupta 49
import com.spice.profitmandi.dao.entity.user.LoginRequestResponseModel;
23329 ashik.ali 50
import com.spice.profitmandi.dao.entity.user.PrivateDealUser;
51
import com.spice.profitmandi.dao.entity.user.PrivateDealUserAddressMapping;
23063 ashik.ali 52
import com.spice.profitmandi.dao.enumuration.dtr.AccountType;
23106 ashik.ali 53
import com.spice.profitmandi.dao.enumuration.dtr.RetailerType;
23136 ashik.ali 54
import com.spice.profitmandi.dao.enumuration.dtr.RoleType;
23365 ashik.ali 55
import com.spice.profitmandi.dao.enumuration.fofo.PaymentOptionType;
23329 ashik.ali 56
import com.spice.profitmandi.dao.repository.dtr.DistrictMasterRepository;
22980 ashik.ali 57
import com.spice.profitmandi.dao.repository.dtr.DocumentRepository;
23329 ashik.ali 58
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
28024 tejbeer 59
import com.spice.profitmandi.dao.repository.dtr.Mongo;
60
import com.spice.profitmandi.dao.repository.dtr.RetailerBlockBrandsRepository;
22980 ashik.ali 61
import com.spice.profitmandi.dao.repository.dtr.RetailerRegisteredAddressRepository;
62
import com.spice.profitmandi.dao.repository.dtr.RetailerRepository;
23781 ashik.ali 63
import com.spice.profitmandi.dao.repository.dtr.RoleRepository;
22980 ashik.ali 64
import com.spice.profitmandi.dao.repository.dtr.ShopAddressRepository;
65
import com.spice.profitmandi.dao.repository.dtr.ShopRepository;
66
import com.spice.profitmandi.dao.repository.dtr.UserAccountRepository;
67
import com.spice.profitmandi.dao.repository.dtr.UserRepository;
68
import com.spice.profitmandi.dao.repository.dtr.UserRoleRepository;
23365 ashik.ali 69
import com.spice.profitmandi.dao.repository.fofo.FofoPartnerPaymentOptionRepository;
70
import com.spice.profitmandi.dao.repository.fofo.PaymentOptionRepository;
24349 amit.gupta 71
import com.spice.profitmandi.dao.repository.inventory.StateRepository;
22980 ashik.ali 72
import com.spice.profitmandi.dao.repository.user.AddressRepository;
23043 ashik.ali 73
import com.spice.profitmandi.dao.repository.user.CartRepository;
23329 ashik.ali 74
import com.spice.profitmandi.dao.repository.user.CounterRepository;
75
import com.spice.profitmandi.dao.repository.user.PrivateDealUserAddressMappingRepository;
76
import com.spice.profitmandi.dao.repository.user.PrivateDealUserRepository;
27877 amit.gupta 77
import com.spice.profitmandi.service.offers.PartnerCriteria;
22980 ashik.ali 78
 
23329 ashik.ali 79
import in.shop2020.model.v1.inventory.StateInfo;
23043 ashik.ali 80
import in.shop2020.model.v1.user.CartStatus;
81
 
22980 ashik.ali 82
@Component
83
public class RetailerServiceImpl implements RetailerService {
23955 govind 84
 
23568 govind 85
	private static final Logger LOGGER = LogManager.getLogger(RetailerServiceImpl.class);
23955 govind 86
 
22980 ashik.ali 87
	@Autowired
88
	private RetailerRepository retailerRepository;
23955 govind 89
 
22980 ashik.ali 90
	@Autowired
28024 tejbeer 91
	private RetailerBlockBrandsRepository retailerBlockBrandsRepository;
92
 
93
	@Autowired
22980 ashik.ali 94
	private UserAccountRepository userAccountRepository;
23955 govind 95
 
22980 ashik.ali 96
	@Autowired
28024 tejbeer 97
	private Mongo mongoClient;
98
 
99
	@Autowired
22980 ashik.ali 100
	private UserRepository userRepository;
23955 govind 101
 
22980 ashik.ali 102
	@Autowired
23043 ashik.ali 103
	private CartRepository cartRepository;
23955 govind 104
 
23043 ashik.ali 105
	@Autowired
22980 ashik.ali 106
	private RetailerRegisteredAddressRepository retailerRegisteredAddressRepository;
23955 govind 107
 
22980 ashik.ali 108
	@Autowired
109
	private AddressRepository addressRepository;
23955 govind 110
 
22980 ashik.ali 111
	@Autowired
112
	private ShopRepository shopRepository;
23955 govind 113
 
22980 ashik.ali 114
	@Autowired
115
	private ShopAddressRepository shopAddressRepository;
23955 govind 116
 
22980 ashik.ali 117
	@Autowired
118
	private UserRoleRepository userRoleRepository;
23955 govind 119
 
22980 ashik.ali 120
	@Autowired
121
	private DocumentRepository documentRepository;
23955 govind 122
 
23043 ashik.ali 123
	@Autowired
23329 ashik.ali 124
	private PrivateDealUserRepository privateDealUserRepository;
23955 govind 125
 
23329 ashik.ali 126
	@Autowired
127
	private PrivateDealUserAddressMappingRepository privateDealUserAddressMappingRepository;
23955 govind 128
 
23329 ashik.ali 129
	@Autowired
130
	private CounterRepository counterRepository;
25295 amit.gupta 131
 
24349 amit.gupta 132
	@Autowired
133
	private StateRepository stateRepository;
23955 govind 134
 
23329 ashik.ali 135
	@Autowired
23043 ashik.ali 136
	@Qualifier("userUserRepository")
137
	private com.spice.profitmandi.dao.repository.user.UserRepository userUserRepository;
23955 govind 138
 
23329 ashik.ali 139
	@Autowired
140
	private DistrictMasterRepository districtMasterRepository;
23955 govind 141
 
23329 ashik.ali 142
	@Autowired
143
	private FofoStoreRepository fofoStoreRepository;
23955 govind 144
 
23329 ashik.ali 145
	@Autowired
23365 ashik.ali 146
	private PaymentOptionRepository paymentOptionRepository;
23955 govind 147
 
23365 ashik.ali 148
	@Autowired
149
	private FofoPartnerPaymentOptionRepository fofoPartnerPaymentOptionRepository;
23955 govind 150
 
23842 ashik.ali 151
	@Autowired
152
	private RoleRepository roleRepository;
23955 govind 153
 
22980 ashik.ali 154
	@Override
155
	public Map<String, Object> getByEmailIdOrMobileNumber(String emailIdOrMobileNumber)
156
			throws ProfitMandiBusinessException {
23202 ashik.ali 157
		User user = null;
28024 tejbeer 158
		int fofoId = Utils.SYSTEM_PARTNER_ID;
159
 
23955 govind 160
		try {
23202 ashik.ali 161
			user = userRepository.selectByEmailIdOrMobileNumber(emailIdOrMobileNumber);
23955 govind 162
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
163
 
23202 ashik.ali 164
		}
23955 govind 165
		if (user == null) {
166
			try {
23329 ashik.ali 167
				user = userRepository.selectBySecondryEmailId(emailIdOrMobileNumber);
23955 govind 168
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
169
 
23329 ashik.ali 170
			}
23202 ashik.ali 171
		}
22980 ashik.ali 172
		Map<String, Object> map = new HashMap<>();
25295 amit.gupta 173
		map.put("stateNames", stateRepository.selectAll().stream().map(x -> x.getName()).collect(Collectors.toList()));
23955 govind 174
 
175
		if (user != null) {
176
 
23329 ashik.ali 177
			List<UserRole> userRoles = userRoleRepository.selectByUserId(user.getId());
23955 govind 178
 
23781 ashik.ali 179
			Role role = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 180
 
23329 ashik.ali 181
			map.put("userRoles", userRoles);
182
			map.put("user", user);
23955 govind 183
			// map.put("retailer", retailer);
23781 ashik.ali 184
			map.put("fofoRole", this.containsRoleType(userRoles, role.getId()));
23955 govind 185
 
23329 ashik.ali 186
			map.put("userRoleNames", this.toString(userRoles));
23955 govind 187
			try {
23329 ashik.ali 188
				int retailerId = userAccountRepository.selectRetailerIdByUserId(user.getId());
189
				Retailer retailer = retailerRepository.selectById(retailerId);
23955 govind 190
 
23329 ashik.ali 191
				map.put("retailer", retailer);
23955 govind 192
 
28024 tejbeer 193
				List<String> retailerBlockBrands = null;
194
				Set<String> brands = null;
195
				if (retailer.getId() != fofoId) {
196
					brands = mongoClient.getMongoBrands(retailer.getId(), null, 3).stream()
197
							.map(x -> (String) x.get("name")).collect(Collectors.toSet());
28189 tejbeer 198
					retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream()
199
							.map(x -> x.getBlockBrands()).collect(Collectors.toList());
200
 
28024 tejbeer 201
					LOGGER.info("loginDetailsFofoId" + retailer.getId());
202
				} else {
203
					LOGGER.info("fofoId" + fofoId);
204
					brands = mongoClient.getMongoBrands(fofoId, null, 3).stream().map(x -> (String) x.get("name"))
205
							.collect(Collectors.toSet());
206
				}
207
				map.put("brands", brands);
208
				map.put("retailerBlockBrands", retailerBlockBrands);
23955 govind 209
				if (this.containsRoleType(userRoles, role.getId())) {
210
					try {
23329 ashik.ali 211
						FofoStore fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
212
						map.put("fofoStore", fofoStore);
23955 govind 213
						// map.put("counterSize", fofoStore.getCounterSize().toString());
214
						// LOGGER.info("fofoStore" + fofoStore);
215
					} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 216
						LOGGER.error("FofoStore code not found");
217
					}
218
				}
23955 govind 219
 
220
				try {
23329 ashik.ali 221
					PrivateDealUser privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23955 govind 222
					if (privateDealUser.getCounterId() != null) {
23329 ashik.ali 223
						Counter counter = counterRepository.selectById(privateDealUser.getCounterId());
224
						map.put("gstNumber", counter.getGstin());
23955 govind 225
						// LOGGER.info("gstNumber" + counter.getGstin());
23329 ashik.ali 226
					}
23955 govind 227
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 228
					LOGGER.error("PrivateDealUser not found");
229
				}
23955 govind 230
				try {
231
					int retailerAddressId = retailerRegisteredAddressRepository
232
							.selectAddressIdByRetailerId(retailer.getId());
23329 ashik.ali 233
					Address retailerAddress = addressRepository.selectById(retailerAddressId);
234
					map.put("retailerAddress", retailerAddress);
24349 amit.gupta 235
					State state = stateRepository.selectByName(retailerAddress.getState());
23955 govind 236
					// LOGGER.info("retailerAddress.." + retailerAddress);
237
					List<DistrictMaster> districtMasters = districtMasterRepository
24349 amit.gupta 238
							.selectByStateShortName(state.getShortName());
23329 ashik.ali 239
					map.put("districtMasters", districtMasters);
23955 govind 240
					// LOGGER.info("districtMasters" + districtMasters);
23329 ashik.ali 241
					List<Shop> shops = shopRepository.selectByRetailerId(retailer.getId());
23955 govind 242
					map.put("shops", shops);
23329 ashik.ali 243
					this.addAddress(shops);
23955 govind 244
					// LOGGER.info("shops" + shops);
245
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 246
					LOGGER.error("Retailer Registered Address not found");
247
				}
23955 govind 248
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 249
				LOGGER.error("Retailer not found in user_account");
23043 ashik.ali 250
			}
251
		}
23955 govind 252
 
22980 ashik.ali 253
		return map;
254
	}
23955 govind 255
 
256
	private boolean containsRoleType(List<UserRole> userRoles, int roleId) {
257
		for (UserRole userRole : userRoles) {
258
			if (userRole.getRoleId() == roleId) {
23329 ashik.ali 259
				return true;
260
			}
261
		}
262
		return false;
263
	}
23955 govind 264
 
265
	private List<UserRole> addRole(List<UserRole> userRoles, int userId, int roleId) {
266
		if (userRoles == null) {
23329 ashik.ali 267
			userRoles = new ArrayList<>();
268
		}
23955 govind 269
		if (!this.containsRoleType(userRoles, roleId)) {
23329 ashik.ali 270
			UserRole userRole = new UserRole();
271
			userRole.setUserId(userId);
23781 ashik.ali 272
			userRole.setRoleId(roleId);
23329 ashik.ali 273
			try {
274
				userRoleRepository.persist(userRole);
275
			} catch (ProfitMandiBusinessException e) {
276
				LOGGER.error("UserRole is already exist");
277
			}
278
			userRoles.add(userRole);
279
		}
280
		return userRoles;
23955 govind 281
 
23329 ashik.ali 282
	}
23955 govind 283
 
25295 amit.gupta 284
	private List<UserRole> removeRole(List<UserRole> userRoles, int userId, int roleId) {
285
		if (userRoles == null) {
286
			userRoles = new ArrayList<>();
287
			return userRoles;
288
		}
289
		try {
290
			userRoles.remove(userRoleRepository.deleteByRoleUserId(userId, roleId));
291
		} catch (Exception e) {
292
 
293
		}
294
		return userRoles;
295
 
296
	}
297
 
22980 ashik.ali 298
	@SuppressWarnings("unchecked")
299
	@Override
23025 ashik.ali 300
	public Map<String, Object> updateRetailerDetails(UpdateRetailerRequest updateRetailerRequest)
301
			throws ProfitMandiBusinessException {
302
		Map<String, Object> map = this.getByEmailIdOrMobileNumber(updateRetailerRequest.getEmailIdOrMobileNumber());
23955 govind 303
		User user = (User) map.get("user");
28024 tejbeer 304
 
23329 ashik.ali 305
		user = this.createUser(user, updateRetailerRequest);
28024 tejbeer 306
 
23329 ashik.ali 307
		map.put("user", user);
23955 govind 308
		List<UserRole> userRoles = (List<UserRole>) map.get("userRoles");
23781 ashik.ali 309
		Role roleUser = roleRepository.selectByName(RoleType.USER.toString());
310
		userRoles = this.addRole(userRoles, user.getId(), roleUser.getId());
23955 govind 311
		Retailer retailer = (Retailer) map.get("retailer");
23329 ashik.ali 312
		retailer = this.updateRetailer(user, retailer, updateRetailerRequest);
28024 tejbeer 313
 
23329 ashik.ali 314
		map.put("retailer", retailer);
23955 govind 315
 
28189 tejbeer 316
		List<String> retailerBlockBrands = retailerBlockBrandsRepository.selectAllByRetailer(retailer.getId()).stream()
317
				.map(x -> x.getBlockBrands()).collect(Collectors.toList());
28024 tejbeer 318
 
28189 tejbeer 319
		LOGGER.info("retailerBlockBrands" + retailerBlockBrands);
320
 
28024 tejbeer 321
		if (!retailerBlockBrands.isEmpty()) {
322
			retailerBlockBrandsRepository.deleteBrands(retailer.getId());
323
		}
324
 
325
		for (String blockBrand : updateRetailerRequest.getBlocksBrands()) {
326
			RetailerBlockBrands retailerBlockBrand = new RetailerBlockBrands();
327
 
328
			retailerBlockBrand.setFofoId(retailer.getId());
329
			retailerBlockBrand.setBlockBrands(blockBrand);
330
			retailerBlockBrandsRepository.persist(retailerBlockBrand);
331
 
332
		}
333
		map.put("retailerBlockBrands", retailerBlockBrands);
334
 
23781 ashik.ali 335
		Role roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
23955 govind 336
 
23781 ashik.ali 337
		userRoles = this.addRole(userRoles, user.getId(), roleRetailer.getId());
23955 govind 338
 
23781 ashik.ali 339
		Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 340
 
341
		if (updateRetailerRequest.isFofo()) {
23781 ashik.ali 342
			userRoles = this.addRole(userRoles, user.getId(), roleFofo.getId());
25295 amit.gupta 343
		} else {
344
			userRoles = this.removeRole(userRoles, user.getId(), roleFofo.getId());
23061 ashik.ali 345
		}
25295 amit.gupta 346
		map.put("fofoRole", this.containsRoleType(userRoles, roleFofo.getId()));
23955 govind 347
 
348
		if (this.containsRoleType(userRoles, roleFofo.getId())) {
23365 ashik.ali 349
			this.createDefaultPaymentOption(retailer.getId());
23329 ashik.ali 350
		}
23955 govind 351
 
23329 ashik.ali 352
		map.put("userRoles", userRoles);
353
		map.put("userRoleNames", this.toString(userRoles));
23955 govind 354
 
355
		Address retailerAddress = (Address) map.get("retailerAddress");
356
		retailerAddress = this.updateRetailerAddress(retailerAddress, updateRetailerRequest.getAddress(),
357
				retailer.getId());
23329 ashik.ali 358
		map.put("retailerAddress", retailerAddress);
23955 govind 359
 
360
		if (updateRetailerRequest.isFofo()) {
361
			FofoStore fofoStore = this.createFofoStoreCodeByRetailerId(retailer.getId(),
362
					updateRetailerRequest.getDistrictName(), retailerAddress.getState(), updateRetailerRequest);
23378 ashik.ali 363
			map.put("fofoStore", fofoStore);
25297 amit.gupta 364
			fofoStore.setActive(updateRetailerRequest.isActive());
23061 ashik.ali 365
		}
23955 govind 366
 
367
		this.createPrivateDealUser(user, updateRetailerRequest.isFofo(), updateRetailerRequest.getGstNumber(), retailer,
368
				retailerAddress.getId());
23329 ashik.ali 369
		map.put("gstNumber", updateRetailerRequest.getGstNumber());
370
		this.updateSaholicUser(retailer.getId(), retailerAddress.getId());
23955 govind 371
 
372
		List<Shop> shops = (List<Shop>) map.get("shops");
373
		if (shops == null) {
23060 ashik.ali 374
			shops = new ArrayList<>();
23061 ashik.ali 375
			map.put("shops", shops);
23060 ashik.ali 376
		}
23079 ashik.ali 377
		this.updateRetailerShops(shops, updateRetailerRequest.getShops(), retailer.getId(), retailerAddress);
23955 govind 378
 
23025 ashik.ali 379
		return map;
23955 govind 380
 
23025 ashik.ali 381
	}
23955 govind 382
 
383
	private void createDefaultPaymentOption(int fofoId) {
23365 ashik.ali 384
		List<Integer> paymentOptionIds = fofoPartnerPaymentOptionRepository.selectPaymentOptionIdsByFofoId(fofoId);
23955 govind 385
		if (paymentOptionIds.isEmpty()) {
23365 ashik.ali 386
			PaymentOption paymentOption = null;
23955 govind 387
			try {
23365 ashik.ali 388
				paymentOption = paymentOptionRepository.selectByName(PaymentOptionType.CASH.toString());
23955 govind 389
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23365 ashik.ali 390
				paymentOption = new PaymentOption();
391
				paymentOption.setName(PaymentOptionType.CASH.toString());
392
				paymentOptionRepository.persist(paymentOption);
393
			}
394
			FofoPartnerPaymentOption fofoPartnerPaymentOption = new FofoPartnerPaymentOption();
395
			fofoPartnerPaymentOption.setFofoId(fofoId);
396
			fofoPartnerPaymentOption.setPaymentOptionId(paymentOption.getId());
397
			fofoPartnerPaymentOptionRepository.persist(fofoPartnerPaymentOption);
398
		}
23955 govind 399
 
23365 ashik.ali 400
	}
23955 govind 401
 
402
	private User createUser(User user, UpdateRetailerRequest updateRetailerRequest) {
403
		if (user == null) {
23329 ashik.ali 404
			user = new User();
405
			user.setCity("");
406
			user.setPinCode(0);
407
			user.setState("");
408
			user.setPassword("");
409
			user.setMobile_verified(false);
410
			user.setReferral_url("");
411
			user.setGroup_id(1);
412
			user.setStatus(1);
413
			user.setActivated(true);
414
			user.setCreateTimestamp(LocalDateTime.now());
415
		}
24705 amit.gupta 416
		user.setActivated(updateRetailerRequest.isActive());
23329 ashik.ali 417
		user.setFirstName(updateRetailerRequest.getUserFirstName());
418
		user.setLastName(updateRetailerRequest.getUserLastName());
419
		user.setMobileNumber(updateRetailerRequest.getUserMobileNumber());
420
		user.setEmailId(updateRetailerRequest.getUserEmailId());
421
		user.setUsername(updateRetailerRequest.getUserEmailId());
23509 amit.gupta 422
		user.setUpdateTimestamp(LocalDateTime.now());
423
		userRepository.persist(user);
23329 ashik.ali 424
		return user;
23955 govind 425
 
23329 ashik.ali 426
	}
23955 govind 427
 
428
	private int createSaholicUser(User user, String retailerName) {
23043 ashik.ali 429
		com.spice.profitmandi.dao.entity.user.User saholicUser = null;
430
		try {
23063 ashik.ali 431
			saholicUser = userUserRepository.selectByEmailId(user.getEmailId());
23955 govind 432
		} catch (ProfitMandiBusinessException e) {
23043 ashik.ali 433
			LOGGER.info("User doesnt exist in old system");
434
		}
23955 govind 435
		if (saholicUser == null) {
23043 ashik.ali 436
			Cart cart = new Cart();
437
			cart.setCartStatus(CartStatus.ACTIVE);
438
			cartRepository.persist(cart);
439
			saholicUser = new com.spice.profitmandi.dao.entity.user.User();
23063 ashik.ali 440
			saholicUser.setEmailId(user.getEmailId());
23043 ashik.ali 441
			saholicUser.setName(retailerName);
442
			saholicUser.setActiveCartId(cart.getId());
23300 amit.gupta 443
			saholicUser.setCreateTimestamp(LocalDateTime.now());
23043 ashik.ali 444
			userUserRepository.persist(saholicUser);
23955 govind 445
 
23269 ashik.ali 446
			UserAccount ua = new UserAccount();
447
			ua.setAccountKey(saholicUser.getId());
448
			ua.setUserId(user.getId());
449
			ua.setType(AccountType.saholic);
23063 ashik.ali 450
			userAccountRepository.persist(ua);
451
 
23269 ashik.ali 452
			UserAccount ua2 = new UserAccount();
453
			ua2.setAccountKey(saholicUser.getActiveCartId());
454
			ua2.setUserId(user.getId());
455
			ua2.setType(AccountType.cartId);
23063 ashik.ali 456
			userAccountRepository.persist(ua2);
23955 govind 457
			LOGGER.info("created....");
23043 ashik.ali 458
		}
459
		return saholicUser.getId();
460
	}
23955 govind 461
 
26522 amit.gupta 462
	private com.spice.profitmandi.dao.entity.user.User createSaholicUser(
463
			LoginRequestResponseModel loginRequestResponseModel) {
464
		com.spice.profitmandi.dao.entity.user.User saholicUser = null;
465
		try {
466
			saholicUser = userUserRepository.selectByEmailId(loginRequestResponseModel.getEmail());
28198 tejbeer 467
			saholicUser.setCreateTimestamp(LocalDateTime.now());
26522 amit.gupta 468
		} catch (ProfitMandiBusinessException e) {
469
			LOGGER.info("User doesnt exist in old system");
470
		}
471
		if (saholicUser == null) {
472
			Cart cart = new Cart();
473
			cart.setCartStatus(CartStatus.ACTIVE);
474
			cartRepository.persist(cart);
475
			saholicUser = new com.spice.profitmandi.dao.entity.user.User();
26528 amit.gupta 476
			saholicUser.setPassword(getHash256(loginRequestResponseModel.getPassword()));
26522 amit.gupta 477
			saholicUser.setEmailId(loginRequestResponseModel.getEmail());
478
			saholicUser.setName(loginRequestResponseModel.getCustomerName());
479
			saholicUser.setActiveCartId(cart.getId());
480
			saholicUser.setCreateTimestamp(LocalDateTime.now());
481
			loginRequestResponseModel.setPassword(null);
482
			userUserRepository.persist(saholicUser);
483
		}
484
		return saholicUser;
485
	}
486
 
23955 govind 487
	private Retailer updateRetailer(User user, Retailer retailer, UpdateRetailerRequest updateRetailerRequest)
488
			throws ProfitMandiBusinessException {
489
		if (retailer == null) {
490
			LOGGER.info("createSaholicUser.....");
23063 ashik.ali 491
			int saholicUserId = this.createSaholicUser(user, updateRetailerRequest.getName());
23043 ashik.ali 492
			retailer = new Retailer();
493
			retailer.setId(saholicUserId);
494
		}
23329 ashik.ali 495
		retailer.setActive(updateRetailerRequest.isActive());
24704 amit.gupta 496
		user.setActivated(updateRetailerRequest.isActive());//
23955 govind 497
		// this.createRole(user.getId(), RoleType.RETAILER);
23025 ashik.ali 498
		retailer.setName(updateRetailerRequest.getName());
499
		retailer.setNumber(updateRetailerRequest.getNumber());
23955 govind 500
		if (updateRetailerRequest.getNumber() == null || updateRetailerRequest.getNumber().isEmpty()) {
23107 ashik.ali 501
			retailer.setType(RetailerType.UNREGISTERED_SHOP);
23955 govind 502
		} else {
23107 ashik.ali 503
			retailer.setType(RetailerType.GSTIN);
504
		}
23955 govind 505
		if (updateRetailerRequest.getDocumentId() > 0) {
506
			if (retailer.getDocumentId() != null && retailer.getDocumentId() != updateRetailerRequest.getDocumentId()) {
24374 amit.gupta 507
				try {
508
					documentRepository.deleteById(retailer.getDocumentId());
25295 amit.gupta 509
				} catch (Exception e) {
24374 amit.gupta 510
					e.printStackTrace();
511
				}
23489 ashik.ali 512
			}
23497 ashik.ali 513
			retailer.setDocumentId(updateRetailerRequest.getDocumentId());
514
			documentRepository.markDocumentAsPersisted(updateRetailerRequest.getDocumentId());
23025 ashik.ali 515
		}
516
		retailerRepository.persist(retailer);
23059 ashik.ali 517
		return retailer;
23025 ashik.ali 518
	}
23955 govind 519
 
520
	private void updateSaholicUser(int retailerId, int retailerAddressId) {
23329 ashik.ali 521
		try {
522
			com.spice.profitmandi.dao.entity.user.User user = userUserRepository.selectById(retailerId);
523
			user.setAddressId(retailerAddressId);
524
		} catch (ProfitMandiBusinessException e) {
23955 govind 525
 
23329 ashik.ali 526
		}
527
	}
23955 govind 528
 
529
	private void createPrivateDealUser(User user, boolean fofo, String gstNumber, Retailer retailer,
530
			int retailerAddressId) {
23329 ashik.ali 531
		PrivateDealUser privateDealUser = null;
23955 govind 532
		try {
23329 ashik.ali 533
			privateDealUser = privateDealUserRepository.selectById(retailer.getId());
23955 govind 534
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 535
			LOGGER.error("PrivateDealUser not found");
536
		}
23955 govind 537
 
538
		// = privateDealUserRepository.selectById(saholicUser.getId());
539
		if (privateDealUser == null) {
540
			Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(),
541
					retailer.getName(), retailerAddressId);
23473 ashik.ali 542
			try {
543
				this.createPrivateDealUser(retailer.getId(), counterId, fofo);
23955 govind 544
			} catch (Exception e) {
23473 ashik.ali 545
				LOGGER.error("ERROR : ", e);
546
			}
23955 govind 547
		} else {
548
			if (privateDealUser.getCounterId() == null) {
549
				Integer counterId = this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(),
550
						retailer.getName(), retailerAddressId);
23329 ashik.ali 551
				privateDealUser.setCounterId(counterId);
552
				privateDealUser.setFofo(fofo);
553
				privateDealUserRepository.persist(privateDealUser);
23955 govind 554
			} else {
23329 ashik.ali 555
				Counter counter = null;
23955 govind 556
				try {
23329 ashik.ali 557
					counter = counterRepository.selectById(privateDealUser.getCounterId());
23955 govind 558
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 559
					LOGGER.error("Counter not found with id [{}]", privateDealUser.getCounterId());
560
				}
23955 govind 561
				if (counter == null) {
562
					this.createCounter(user.getEmailId(), gstNumber, user.getMobileNumber(), retailer.getName(),
563
							retailerAddressId);
564
				} else {
23329 ashik.ali 565
					counter.setGstin(gstNumber);
566
					counterRepository.persist(counter);
567
				}
568
				privateDealUser.setFofo(fofo);
569
				privateDealUserRepository.persist(privateDealUser);
570
			}
571
		}
23955 govind 572
 
23329 ashik.ali 573
		PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
574
		privateDealUserAddressMapping.setUserId(retailer.getId());
575
		privateDealUserAddressMapping.setAddressId(retailerAddressId);
576
		privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
577
	}
23955 govind 578
 
579
	// Specifically set isFofo to true that has to be used by old system
580
	private void createPrivateDealUser(int retailerId, int counterId, boolean fofo) {
23329 ashik.ali 581
		PrivateDealUser privateDealUser = new PrivateDealUser();
582
		privateDealUser.setActive(true);
583
		privateDealUser.setBulkShipmentAmountLimit(fofo ? 1000000 : 50000);
584
		privateDealUser.setId(retailerId);
585
		privateDealUser.setCounterId(counterId);
586
		privateDealUser.setFofo(fofo);
587
		privateDealUserRepository.persist(privateDealUser);
588
	}
23955 govind 589
 
590
	private Integer createCounter(String emailId, String gstNumber, String mobileNumber, String name, int addressId) {
591
		if (gstNumber != null && !gstNumber.isEmpty()) {
23329 ashik.ali 592
			Counter counter = new Counter();
593
			counter.setEmailId(emailId);
594
			counter.setGstin(gstNumber);
595
			counter.setMobileNumber(mobileNumber);
596
			counter.setName(name);
597
			counter.setAddressId(addressId);
598
			counterRepository.persist(counter);
599
			return counter.getId();
23955 govind 600
		} else {
23329 ashik.ali 601
			return null;
602
		}
603
	}
23955 govind 604
 
605
	private Address updateRetailerAddress(Address address, CustomAddress customAddress, int retailerId)
606
			throws ProfitMandiBusinessException {
607
		if (address == null) {
23043 ashik.ali 608
			address = new Address();
609
			address.setRetaierId(retailerId);
610
			this.updateAddress(address, customAddress);
23955 govind 611
			// addressRepository.persist(addressRetailer);
612
 
23043 ashik.ali 613
			final RetailerRegisteredAddress retailerRegisteredAddress = new RetailerRegisteredAddress();
614
			retailerRegisteredAddress.setRetailerId(retailerId);
615
			retailerRegisteredAddress.setAddressId(address.getId());
616
			retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
23955 govind 617
		} else {
618
			this.updateAddress(address, customAddress);
619
			RetailerRegisteredAddress retailerRegisteredAddress = retailerRegisteredAddressRepository
620
					.selectByRetailerId(retailerId);
621
			retailerRegisteredAddress.setAddressId(address.getId());
622
			retailerRegisteredAddressRepository.persist(retailerRegisteredAddress);
23043 ashik.ali 623
		}
23059 ashik.ali 624
		return address;
23043 ashik.ali 625
	}
23955 govind 626
 
27411 amit.gupta 627
	private void updateAddress(Address address, CustomAddress customAddress) throws ProfitMandiBusinessException {
23025 ashik.ali 628
		address.setName(customAddress.getName());
23829 amit.gupta 629
		address.setPhoneNumber(customAddress.getPhoneNumber());
23025 ashik.ali 630
		address.setLine1(customAddress.getLine1());
631
		address.setLine2(customAddress.getLine2());
632
		address.setCity(customAddress.getCity());
633
		address.setPinCode(customAddress.getPinCode());
27411 amit.gupta 634
		State state = stateRepository.selectByName(customAddress.getState());
27877 amit.gupta 635
		if (state == null) {
636
			throw new ProfitMandiBusinessException("State name", "Invalid State - Pls Contact Technology",
637
					"Invalid State - Pls Contact Technology");
27411 amit.gupta 638
		}
639
		address.setState(state.getName());
23025 ashik.ali 640
		addressRepository.persist(address);
23955 govind 641
		LOGGER.info("Address Updated" + address);
23025 ashik.ali 642
	}
23955 govind 643
 
644
	private void updateRetailerShops(List<Shop> shops, Set<CustomShop> customShops, int retailerId,
645
			Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
646
		if (shops.isEmpty()) {
647
			for (CustomShop customShop : customShops) {
23043 ashik.ali 648
				Shop shop = new Shop();
23079 ashik.ali 649
				this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
23043 ashik.ali 650
				shops.add(shop);
651
			}
23955 govind 652
		} else {
653
			for (Shop shop : shops) {
654
				for (CustomShop customShop : customShops) {
655
					if (shop.getId() == customShop.getShopId()) {
23079 ashik.ali 656
						this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
23025 ashik.ali 657
					}
658
				}
659
			}
23955 govind 660
			for (CustomShop customShop : customShops) {
661
				if (customShop.getShopId() == 0) {
23043 ashik.ali 662
					Shop shop = new Shop();
23079 ashik.ali 663
					this.createOrUpdateShop(shop, customShop, retailerId, sameAsRetailerAddressValue);
23043 ashik.ali 664
					shops.add(shop);
665
				}
666
			}
23025 ashik.ali 667
		}
668
	}
23955 govind 669
 
670
	private void createOrUpdateShop(Shop shop, CustomShop customShop, int retailerId,
671
			Address sameAsRetailerAddressValue) throws ProfitMandiBusinessException {
23043 ashik.ali 672
		shop.setRetailerId(retailerId);
673
		shop.setName(customShop.getName());
23955 govind 674
		if (customShop.getDocumentId() > 0) {
675
			if (shop.getDocumentId() != null && shop.getDocumentId() != customShop.getDocumentId()) {
24374 amit.gupta 676
				try {
677
					documentRepository.deleteById(shop.getDocumentId());
25295 amit.gupta 678
				} catch (Exception e) {
24374 amit.gupta 679
					e.printStackTrace();
680
				}
23489 ashik.ali 681
			}
23497 ashik.ali 682
			shop.setDocumentId(customShop.getDocumentId());
683
			documentRepository.markDocumentAsPersisted(customShop.getDocumentId());
23043 ashik.ali 684
		}
23955 govind 685
		if (shop.getAddressId() == null) {
23079 ashik.ali 686
			Address address = null;
23955 govind 687
			if (customShop.isSameAsRetailerAddress()) {
23079 ashik.ali 688
				address = sameAsRetailerAddressValue;
23955 govind 689
			} else {
690
				// shop.setDocumentId(customShop.getDocumentId());
23079 ashik.ali 691
				address = new Address();
692
				this.updateAddress(address, customShop.getAddress());
693
			}
23043 ashik.ali 694
			shop.setAddressId(address.getId());
695
			shop.setAddress(address);
696
			shopRepository.persist(shop);
23131 ashik.ali 697
			ShopAddress shopAddress = null;
23955 govind 698
			try {
23131 ashik.ali 699
				shopAddress = shopAddressRepository.selectByShopId(shop.getId());
700
				shopAddress.setAddressId(address.getId());
23955 govind 701
			} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23131 ashik.ali 702
				shopAddress = new ShopAddress();
703
				shopAddress.setAddressId(address.getId());
704
				shopAddress.setShopId(shop.getId());
705
			}
23043 ashik.ali 706
			shopAddressRepository.persist(shopAddress);
23955 govind 707
		} else {
24375 amit.gupta 708
			Address address = null;
709
			try {
710
				address = addressRepository.selectById(shop.getAddressId());
711
				CustomAddress customAddress = customShop.getAddress();
712
				if (!(address.getName().equals(customAddress.getName())
713
						&& address.getLine1().equals(customAddress.getLine1())
714
						&& address.getLine2().equals(customAddress.getLine2())
715
						&& address.getCity().equals(customAddress.getCity())
716
						&& address.getPinCode().equals(customAddress.getPinCode())
717
						&& address.getState().equals(customAddress.getState()))) {
718
					address = new Address();
719
					ShopAddress shopAddress = shopAddressRepository.selectByShopId(shop.getId());
720
					this.updateAddress(address, customAddress);
721
					shopAddress.setAddressId(address.getId());
722
					shopAddressRepository.persist(shopAddress);
723
					shop.setAddress(address);
724
					shopRepository.persist(shop);
725
				}
25295 amit.gupta 726
			} catch (Exception e) {
24375 amit.gupta 727
				if (customShop.isSameAsRetailerAddress()) {
728
					address = sameAsRetailerAddressValue;
729
				} else {
730
					// shop.setDocumentId(customShop.getDocumentId());
731
					address = new Address();
732
					this.updateAddress(address, customShop.getAddress());
733
				}
734
				shop.setAddressId(address.getId());
735
				shop.setAddress(address);
736
				shopRepository.persist(shop);
737
				ShopAddress shopAddress = null;
738
				try {
739
					shopAddress = shopAddressRepository.selectByShopId(shop.getId());
740
					shopAddress.setAddressId(address.getId());
741
				} catch (ProfitMandiBusinessException profitMandiBusinessException) {
742
					shopAddress = new ShopAddress();
743
					shopAddress.setAddressId(address.getId());
744
					shopAddress.setShopId(shop.getId());
745
				}
25295 amit.gupta 746
				shopAddressRepository.persist(shopAddress);
747
			}
23955 govind 748
 
23043 ashik.ali 749
		}
23955 govind 750
 
23043 ashik.ali 751
	}
23955 govind 752
 
753
	private void addAddress(List<Shop> shops) {
22980 ashik.ali 754
		Set<Integer> shopIds = this.toShopIds(shops);
23955 govind 755
		if (shopIds.isEmpty()) {
22980 ashik.ali 756
			return;
757
		}
758
		List<ShopAddress> shopAddresses = shopAddressRepository.selectByShopIds(shopIds);
759
		Map<Integer, Address> addressIdAddressMap = this.toAddressIdAddressMap(shopAddresses);
23955 govind 760
 
761
		for (Shop shop : shops) {
22980 ashik.ali 762
			shop.setAddress(addressIdAddressMap.get(shop.getAddressId()));
763
		}
764
	}
765
 
23955 govind 766
	private Map<Integer, Address> toAddressIdAddressMap(List<ShopAddress> shopAddresses) {
22980 ashik.ali 767
		Map<Integer, Address> addressIdAddressMap = new HashMap<>();
768
		List<Integer> addressIds = this.toAddressIds(shopAddresses);
769
		List<Address> addresses = addressRepository.selectByIds(addressIds);
23955 govind 770
		for (Address address : addresses) {
22980 ashik.ali 771
			addressIdAddressMap.put(address.getId(), address);
772
		}
773
		return addressIdAddressMap;
774
	}
23955 govind 775
 
776
	private List<Integer> toAddressIds(List<ShopAddress> shopAddresses) {
777
		Function<ShopAddress, Integer> shopAddressToAddressIdFunction = new Function<ShopAddress, Integer>() {
22980 ashik.ali 778
			@Override
779
			public Integer apply(ShopAddress shopAddress) {
780
				return shopAddress.getAddressId();
781
			}
782
		};
783
		return shopAddresses.stream().map(shopAddressToAddressIdFunction).collect(Collectors.toList());
784
	}
23955 govind 785
 
786
	private Set<Integer> toShopIds(List<Shop> shops) {
787
		Function<Shop, Integer> shopToAddressIdFunction = new Function<Shop, Integer>() {
22980 ashik.ali 788
			@Override
789
			public Integer apply(Shop shop) {
790
				return shop.getId();
791
			}
792
		};
793
		return shops.stream().map(shopToAddressIdFunction).collect(Collectors.toSet());
794
	}
23955 govind 795
 
796
	private String toString(List<UserRole> userRoles) {
23781 ashik.ali 797
		Set<Integer> roleIds = new HashSet<>();
23955 govind 798
		for (UserRole userRole : userRoles) {
23781 ashik.ali 799
			roleIds.add(userRole.getRoleId());
800
		}
801
		List<Role> roles = roleRepository.selectByIds(roleIds);
23955 govind 802
		Function<Role, String> roleToNameFunction = new Function<Role, String>() {
23781 ashik.ali 803
			public String apply(Role role) {
804
				return String.valueOf(role.getName());
22980 ashik.ali 805
			};
806
		};
23781 ashik.ali 807
		Set<String> userRoleStrings = roles.stream().map(roleToNameFunction).collect(Collectors.toSet());
22980 ashik.ali 808
		return String.join(", ", userRoleStrings);
809
	}
23955 govind 810
 
811
	private FofoStore createFofoStoreCodeByRetailerId(int retailerId, String districtName, String stateName,
812
			UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
23378 ashik.ali 813
		FofoStore fofoStore = null;
23955 govind 814
		try {
23378 ashik.ali 815
			fofoStore = fofoStoreRepository.selectByRetailerId(retailerId);
23955 govind 816
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
817
 
23378 ashik.ali 818
		}
23955 govind 819
 
820
		if (fofoStore != null) {
821
			fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
822
			fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
26209 tejbeer 823
			fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
28825 tejbeer 824
			fofoStore.setFofoType(updateRetailerRequest.getFofoType());
23955 govind 825
			fofoStoreRepository.persist(fofoStore);
826
 
827
		} else {
23378 ashik.ali 828
			int retailerAddressId = retailerRegisteredAddressRepository.selectAddressIdByRetailerId(retailerId);
829
			Address retailerAddress = addressRepository.selectById(retailerAddressId);
23955 govind 830
 
23378 ashik.ali 831
			StateInfo stateInfo = null;
832
			try {
833
				stateInfo = Utils.getStateInfo(retailerAddress.getState());
834
			} catch (Exception e) {
835
				// TODO Auto-generated catch block
836
				e.printStackTrace();
23955 govind 837
				// throw new ProfitMandiBusinessException();
23378 ashik.ali 838
			}
23955 govind 839
			DistrictMaster districtMaster = districtMasterRepository.selectByNameAndStateShortName(districtName,
840
					stateInfo.getShortName());
841
 
23378 ashik.ali 842
			fofoStore = new FofoStore();
843
			fofoStore.setId(retailerId);
24023 amit.gupta 844
			fofoStore.setCounterSize(updateRetailerRequest.getCountersize());
845
			fofoStore.setMinimumInvestment(updateRetailerRequest.getMinInvestment());
26209 tejbeer 846
			fofoStore.setWarehouseId(updateRetailerRequest.getWarehouseId());
23786 amit.gupta 847
			String latestStoreCode = fofoStoreRepository.selectLatestStore().getCode();
848
			int latestCodeCounter = Integer.parseInt(latestStoreCode.replaceAll("[A-Z]", ""));
23955 govind 849
			String fofoStoreCode = StringUtils.generateFofoStoreSequence(
850
					districtMaster.getStateShortName() + districtMaster.getShortName(), latestCodeCounter + 1);
23378 ashik.ali 851
			fofoStore.setCode(fofoStoreCode);
28189 tejbeer 852
			fofoStore.setBagsLastCredited(LocalDateTime.now());
28825 tejbeer 853
			fofoStore.setFofoType(updateRetailerRequest.getFofoType());
23378 ashik.ali 854
			fofoStoreRepository.persist(fofoStore);
855
		}
23955 govind 856
 
23378 ashik.ali 857
		return fofoStore;
858
	}
23955 govind 859
 
23329 ashik.ali 860
	@Override
23955 govind 861
	public FofoStore createFofoStoreCodeByUserId(int userId, String districtName, String stateName,
862
			UpdateRetailerRequest updateRetailerRequest) throws ProfitMandiBusinessException {
23329 ashik.ali 863
		User user = userRepository.selectById(userId);
864
		// = userAccountRepository.selectRetailerIdByUserId(user.getId());
865
		UserAccount userAccounts = userAccountRepository.selectSaholicByUserId(user.getId());
866
		Retailer retailer = retailerRepository.selectById(userAccounts.getAccountKey());
23781 ashik.ali 867
		Role roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
23955 govind 868
		try {
23781 ashik.ali 869
			userRoleRepository.selectByUserIdAndRoleId(user.getId(), roleFofo.getId());
23955 govind 870
		} catch (ProfitMandiBusinessException profitMandiBusinessException) {
23329 ashik.ali 871
			throw new ProfitMandiBusinessException(ProfitMandiConstants.USER_ID, user.getId(), "USR_1013");
872
		}
23955 govind 873
		return this.createFofoStoreCodeByRetailerId(retailer.getId(), districtName, stateName, updateRetailerRequest);
874
 
23329 ashik.ali 875
	}
23955 govind 876
 
23329 ashik.ali 877
	@Override
878
	public List<DistrictMaster> getAllDistrictMaster(String stateName) {
879
		StateInfo stateInfo = null;
880
		try {
881
			stateInfo = Utils.getStateInfo(stateName);
882
		} catch (Exception e) {
883
			e.printStackTrace();
23955 govind 884
			// throw new ProfitMandiBusinessException();
23329 ashik.ali 885
		}
886
		return districtMasterRepository.selectByStateShortName(stateInfo.getShortName());
887
	}
22980 ashik.ali 888
 
23509 amit.gupta 889
	@Override
890
	public Map<Integer, CustomRetailer> getFofoRetailers(List<Integer> fofoIds) {
891
		List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
25295 amit.gupta 892
		Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
893
				.filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
23903 amit.gupta 894
		List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
23509 amit.gupta 895
		Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
25295 amit.gupta 896
		for (Address address : addresses) {
23903 amit.gupta 897
			com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
23509 amit.gupta 898
			CustomRetailer customRetailer = new CustomRetailer();
23903 amit.gupta 899
			customRetailer.setEmail(user.getEmailId());
23509 amit.gupta 900
			customRetailer.setBusinessName(address.getName());
901
			customRetailer.setMobileNumber(address.getPhoneNumber());
23532 amit.gupta 902
			try {
26151 amit.gupta 903
				FofoStore fs = fofoStoreRepository.selectByRetailerId(address.getRetaierId());
904
				customRetailer.setCode(fs.getCode());
905
				customRetailer.setWarehouseId(fs.getWarehouseId());
26977 amit.gupta 906
				customRetailer.setPartnerId(fs.getId());
26125 amit.gupta 907
			} catch (Exception e) {
908
				continue;
909
			}
910
			try {
23796 amit.gupta 911
				customRetailer.setCartId(user.getActiveCartId());
23532 amit.gupta 912
				PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
913
				Counter counter = counterRepository.selectById(pdu.getCounterId());
914
				customRetailer.setGstNumber(counter.getGstin());
23955 govind 915
			} catch (Exception e) {
23532 amit.gupta 916
				customRetailer.setGstNumber(null);
917
			}
918
			CustomAddress address1 = new CustomAddress();
919
			address1.setCity(address.getCity());
920
			address1.setState(address.getState());
921
			address1.setLine1(address.getLine1());
922
			address1.setLine2(address.getLine2());
923
			address1.setPinCode(address.getPinCode());
924
			address1.setName(address.getName());
925
			customRetailer.setAddress(address1);
26522 amit.gupta 926
			customRetailer.setDisplayName(
927
					customRetailer.getBusinessName() + "-" + customRetailer.getCode() + "- " + address1.getCity());
26977 amit.gupta 928
			customRetailersMap.put(customRetailer.getPartnerId(), customRetailer);
23509 amit.gupta 929
		}
930
		return customRetailersMap;
931
	}
25295 amit.gupta 932
 
23781 ashik.ali 933
	@Override
25295 amit.gupta 934
	public CustomRetailer getFofoRetailer(int fofoId) throws ProfitMandiBusinessException {
23957 tejbeer 935
		com.spice.profitmandi.dao.entity.user.User saholicUser = userUserRepository.selectById(fofoId);
26089 amit.gupta 936
		FofoStore store = fofoStoreRepository.selectByRetailerId(fofoId);
23957 tejbeer 937
		Address address = null;
938
		try {
939
			address = addressRepository.selectById(saholicUser.getAddressId());
940
		} catch (ProfitMandiBusinessException e1) {
941
			// TODO Auto-generated catch block
942
			e1.printStackTrace();
943
		}
944
		Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
25295 amit.gupta 945
		CustomRetailer customRetailer = new CustomRetailer();
946
		customRetailer.setEmail(saholicUser.getEmailId());
947
		customRetailer.setBusinessName(address.getName());
948
		customRetailer.setMobileNumber(address.getPhoneNumber());
949
		try {
950
			customRetailer.setCartId(saholicUser.getActiveCartId());
951
			PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
952
			Counter counter = counterRepository.selectById(pdu.getCounterId());
953
			customRetailer.setGstNumber(counter.getGstin());
954
		} catch (Exception e) {
955
			customRetailer.setGstNumber(null);
956
		}
957
		CustomAddress address1 = new CustomAddress();
958
		address1.setCity(address.getCity());
959
		address1.setState(address.getState());
960
		address1.setLine1(address.getLine1());
961
		address1.setLine2(address.getLine2());
962
		address1.setPinCode(address.getPinCode());
26653 amit.gupta 963
		address1.setPhoneNumber(address.getPhoneNumber());
25295 amit.gupta 964
		address1.setName(address.getName());
26125 amit.gupta 965
		customRetailer.setDisplayName(address.getName() + " - " + address.getCity());
25295 amit.gupta 966
		customRetailer.setAddress(address1);
967
		customRetailer.setPartnerId(address.getRetaierId());
26089 amit.gupta 968
		customRetailer.setCode(store.getCode());
26112 amit.gupta 969
		customRetailer.setWarehouseId(store.getWarehouseId());
25295 amit.gupta 970
		customRetailersMap.put(address.getRetaierId(), customRetailer);
23957 tejbeer 971
		return customRetailer;
25295 amit.gupta 972
 
23957 tejbeer 973
	}
26125 amit.gupta 974
 
25383 tejbeer 975
	@Override
27877 amit.gupta 976
	public Map<Integer, CustomRetailer> getFofoRetailerUserId(List<Integer> fofoIds) {
25383 tejbeer 977
		List<com.spice.profitmandi.dao.entity.user.User> saholicUsers = userUserRepository.selectByIds(fofoIds);
978
		Map<Integer, com.spice.profitmandi.dao.entity.user.User> userAddressMap = saholicUsers.stream()
979
				.filter(x -> x.getAddressId() != null).collect(Collectors.toMap(x -> x.getAddressId(), x -> x));
980
		List<Address> addresses = addressRepository.selectByIds(new ArrayList<>(userAddressMap.keySet()));
981
		Map<Integer, CustomRetailer> customRetailersMap = new HashMap<>();
982
		for (Address address : addresses) {
983
			com.spice.profitmandi.dao.entity.user.User user = userAddressMap.get(address.getId());
984
			CustomRetailer customRetailer = new CustomRetailer();
985
			customRetailer.setEmail(user.getEmailId());
986
			customRetailer.setBusinessName(address.getName());
987
			customRetailer.setMobileNumber(address.getPhoneNumber());
27877 amit.gupta 988
			int userId = 0;
25383 tejbeer 989
			try {
27877 amit.gupta 990
				userId = userAccountRepository.selectUserIdByRetailerId(user.getId());
28024 tejbeer 991
			} catch (ProfitMandiBusinessException e) {
27877 amit.gupta 992
				continue;
993
			}
994
			try {
25383 tejbeer 995
				customRetailer.setCartId(user.getActiveCartId());
996
				PrivateDealUser pdu = privateDealUserRepository.selectById(address.getRetaierId());
997
				Counter counter = counterRepository.selectById(pdu.getCounterId());
998
				customRetailer.setGstNumber(counter.getGstin());
999
			} catch (Exception e) {
1000
				customRetailer.setGstNumber(null);
1001
			}
1002
			CustomAddress address1 = new CustomAddress();
1003
			address1.setCity(address.getCity());
1004
			address1.setState(address.getState());
1005
			address1.setLine1(address.getLine1());
1006
			address1.setLine2(address.getLine2());
1007
			address1.setPinCode(address.getPinCode());
1008
			address1.setName(address.getName());
1009
			customRetailer.setAddress(address1);
1010
			customRetailer.setPartnerId(address.getRetaierId());
1011
			customRetailer.setDisplayName(customRetailer.getBusinessName() + "-" + address1.getCity());
1012
			customRetailersMap.put(userId, customRetailer);
1013
		}
1014
		return customRetailersMap;
1015
	}
25295 amit.gupta 1016
 
23957 tejbeer 1017
	@Override
23781 ashik.ali 1018
	public Map<Integer, String> getAllFofoRetailerIdEmailIdMap() {
1019
		Role roleFofo = null;
1020
		try {
1021
			roleFofo = roleRepository.selectByName(RoleType.FOFO.toString());
1022
		} catch (ProfitMandiBusinessException e) {
1023
			// TODO Auto-generated catch block
1024
			e.printStackTrace();
1025
		}
1026
		Role roleRetailer = null;
1027
		try {
1028
			roleRetailer = roleRepository.selectByName(RoleType.RETAILER.toString());
1029
		} catch (ProfitMandiBusinessException e) {
1030
			// TODO Auto-generated catch block
1031
			e.printStackTrace();
1032
		}
1033
		Set<Integer> roleIds = new HashSet<>();
1034
		roleIds.add(roleFofo.getId());
1035
		roleIds.add(roleRetailer.getId());
1036
		List<Integer> userIds = userRoleRepository.selectUserIdsByRoleIds(roleIds);
1037
		List<User> users = userRepository.selectAllByIds(new HashSet<>(userIds));
1038
		Map<Integer, Integer> userIdRetailerIdMap = this.getUserIdRetailerIdMap(userIds);
1039
		Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
23955 govind 1040
		for (User user : users) {
23781 ashik.ali 1041
			retailerIdEmailIdMap.put(userIdRetailerIdMap.get(user.getId()), user.getEmailId());
1042
		}
1043
		return retailerIdEmailIdMap;
1044
	}
23955 govind 1045
 
1046
	private Map<Integer, Integer> getUserIdRetailerIdMap(List<Integer> userIds) {
23781 ashik.ali 1047
		List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByUserIds(new HashSet<>(userIds));
1048
		Map<Integer, Integer> userIdRetailerIdMap = new HashMap<>();
23955 govind 1049
		for (UserAccount userAccount : userAccounts) {
23781 ashik.ali 1050
			userIdRetailerIdMap.put(userAccount.getUserId(), userAccount.getAccountKey());
1051
		}
1052
		return userIdRetailerIdMap;
1053
	}
25295 amit.gupta 1054
 
1055
	private Map<Integer, String> getUserIdEmailIdMap(Set<Integer> userIds) {
23880 ashik.ali 1056
		List<User> users = userRepository.selectAllByIds(userIds);
1057
		Map<Integer, String> userIdEmailIdMap = new HashMap<>();
23955 govind 1058
		for (User user : users) {
23880 ashik.ali 1059
			userIdEmailIdMap.put(user.getId(), user.getEmailId());
1060
		}
1061
		return userIdEmailIdMap;
1062
	}
23509 amit.gupta 1063
 
23880 ashik.ali 1064
	@Override
1065
	public Map<Integer, String> getAllFofoRetailerIdEmailIdMap(Set<Integer> retailerIds) {
1066
		List<UserAccount> userAccounts = userAccountRepository.selectAllSaholicByRetailerIds(retailerIds);
1067
		Set<Integer> userIds = new HashSet<>();
23955 govind 1068
		for (UserAccount userAccount : userAccounts) {
23880 ashik.ali 1069
			userIds.add(userAccount.getUserId());
1070
		}
1071
		Map<Integer, String> retailerIdEmailIdMap = new HashMap<>();
1072
		Map<Integer, String> userIdEmailIdMap = this.getUserIdEmailIdMap(userIds);
23955 govind 1073
		for (UserAccount userAccount : userAccounts) {
23880 ashik.ali 1074
			retailerIdEmailIdMap.put(userAccount.getAccountKey(), userIdEmailIdMap.get(userAccount.getUserId()));
1075
		}
1076
		return retailerIdEmailIdMap;
1077
	}
25295 amit.gupta 1078
 
24168 amit.gupta 1079
	@Override
24349 amit.gupta 1080
	public Map<Integer, String> getAllFofoRetailerIdNameMap(List<Integer> storeIds) {
24168 amit.gupta 1081
		Map<Integer, CustomRetailer> retailersMap = this.getFofoRetailers(storeIds);
1082
		Map<Integer, String> retailerIdNameMap = new HashMap<>();
25295 amit.gupta 1083
		for (Map.Entry<Integer, CustomRetailer> entry : retailersMap.entrySet()) {
1084
			retailerIdNameMap.put(entry.getKey(),
1085
					entry.getValue().getBusinessName() + "-" + entry.getValue().getAddress().getCity());
24168 amit.gupta 1086
		}
1087
		return retailerIdNameMap;
1088
	}
1089
 
1090
	@Override
28330 amit.gupta 1091
	@Cacheable(value = "FofoRetailerIdNameMap", cacheManager = "oneDayCacheManager")
24168 amit.gupta 1092
	public Map<Integer, String> getAllFofoRetailerIdNameMap() {
24349 amit.gupta 1093
		List<FofoStore> stores = fofoStoreRepository.selectAll();
25295 amit.gupta 1094
		List<Integer> storeIds = stores.stream().map(x -> x.getId()).collect(Collectors.toList());
24349 amit.gupta 1095
		return this.getAllFofoRetailerIdNameMap(storeIds);
1096
	}
1097
 
1098
	@Override
1099
	public List<MapWrapper<Integer, String>> getAllFofoRetailerIdNameList() {
1100
		List<MapWrapper<Integer, String>> mapWrappers = new ArrayList<>();
24168 amit.gupta 1101
		// TODO Auto-generated method stub
24349 amit.gupta 1102
		Map<Integer, String> fofoIdNameMap = this.getAllFofoRetailerIdNameMap();
25295 amit.gupta 1103
		fofoIdNameMap.forEach((fofoId, name) -> {
24349 amit.gupta 1104
			MapWrapper<Integer, String> idWrapper = new MapWrapper<>();
1105
			idWrapper.setKey(fofoId);
1106
			idWrapper.setValue(name);
1107
			mapWrappers.add(idWrapper);
1108
		});
1109
		return mapWrappers;
1110
	}
1111
 
1112
	@Override
27124 amit.gupta 1113
	@Cacheable(value = "retailerNames", cacheManager = "oneDayCacheManager")
26962 amit.gupta 1114
	public Map<Integer, CustomRetailer> getFofoRetailers(boolean activeOnly) {
24349 amit.gupta 1115
		// TODO Auto-generated method stub
26962 amit.gupta 1116
		Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();
27861 tejbeer 1117
		if (activeOnly) {
1118
			storeStream = storeStream.filter(x -> x.isActive());
26962 amit.gupta 1119
		}
1120
		List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
24349 amit.gupta 1121
		return this.getFofoRetailers(storeIds);
24168 amit.gupta 1122
	}
25295 amit.gupta 1123
 
26522 amit.gupta 1124
	@Override
27861 tejbeer 1125
	@Cacheable(value = "retailerNames", cacheManager = "oneDayCacheManager")
1126
	public Map<Integer, CustomRetailer> getAllFofoRetailers() {
1127
		// TODO Auto-generated method stub
1128
		Stream<FofoStore> storeStream = fofoStoreRepository.selectAll().stream();
1129
 
1130
		List<Integer> storeIds = storeStream.map(x -> x.getId()).collect(Collectors.toList());
1131
		return this.getFofoRetailers(storeIds);
1132
	}
1133
 
1134
	@Override
26522 amit.gupta 1135
	public LoginRequestResponseModel registerWebUser(LoginRequestResponseModel loginRequestModel)
1136
			throws ProfitMandiBusinessException {
1137
 
1138
		com.spice.profitmandi.dao.entity.user.User saholicUser = this.createSaholicUser(loginRequestModel);
1139
		loginRequestModel.setUserId(saholicUser.getId());
1140
 
1141
		this.createRetailerAddress(loginRequestModel);
1142
 
1143
		this.createPrivateDealUser(loginRequestModel);
1144
		this.updateSaholicUser(saholicUser.getId(), loginRequestModel.getBusinessAddress().getId());
1145
 
1146
		return loginRequestModel;
1147
 
1148
	}
1149
 
1150
	private void createPrivateDealUser(LoginRequestResponseModel loginRequestModel) {
1151
 
1152
		Integer counterId = this.createCounter(loginRequestModel.getEmail(), loginRequestModel.getGstNumber(),
1153
				loginRequestModel.getBusinessAddress().getPhoneNumber(),
1154
				loginRequestModel.getBusinessAddress().getName(), loginRequestModel.getBusinessAddress().getId());
1155
		try {
1156
			this.createPrivateDealUser(loginRequestModel.getUserId(), counterId, false);
1157
		} catch (Exception e) {
1158
			LOGGER.error("ERROR : ", e);
1159
		}
1160
 
1161
		PrivateDealUserAddressMapping privateDealUserAddressMapping = new PrivateDealUserAddressMapping();
1162
		privateDealUserAddressMapping.setUserId(loginRequestModel.getUserId());
1163
		privateDealUserAddressMapping.setAddressId(loginRequestModel.getBusinessAddress().getId());
1164
		privateDealUserAddressMappingRepository.persist(privateDealUserAddressMapping);
1165
 
1166
	}
1167
 
1168
	private void createRetailerAddress(LoginRequestResponseModel loginRequestResponseModel)
1169
			throws ProfitMandiBusinessException {
1170
		Address businessAddress = loginRequestResponseModel.getBusinessAddress();
1171
		businessAddress.setRetaierId(loginRequestResponseModel.getUserId());
1172
		addressRepository.persist(businessAddress);
1173
	}
26536 amit.gupta 1174
 
26528 amit.gupta 1175
	private String getHash256(String originalString) {
26533 amit.gupta 1176
		String hashString = Hashing.sha256().hashString(originalString, StandardCharsets.UTF_8).toString();
1177
		LOGGER.info("Hash String {}", hashString);
1178
		return hashString;
26528 amit.gupta 1179
	}
26533 amit.gupta 1180
 
1181
	@Override
26536 amit.gupta 1182
	@Cacheable(value = "fofoIdUrl", cacheManager = "oneDayCacheManager")
26533 amit.gupta 1183
	public Map<Integer, String> getAllFofoRetailerIdUrlMap() {
26536 amit.gupta 1184
		Map<Integer, String> fofoRetailerUrlMap = new HashMap<>();
1185
		List<FofoStore> stores = fofoStoreRepository.selectAll().stream().filter(x -> x.isActive())
1186
				.collect(Collectors.toList());
1187
		Map<Integer, com.spice.profitmandi.dao.entity.user.User> userMap = userUserRepository
1188
				.selectByIds(stores.stream().map(x -> x.getId()).collect(Collectors.toList())).stream()
1189
				.collect(Collectors.toMap(x -> x.getId(), x -> x));
1190
		for (FofoStore store : stores) {
26537 amit.gupta 1191
			LOGGER.info("Store is {}", store);
26544 amit.gupta 1192
			String districtShortName = store.getCode().replaceAll("\\d+", "").substring(2);
26593 amit.gupta 1193
			String stateShortName = store.getCode().replaceAll("\\d+", "").substring(0, 2);
26539 amit.gupta 1194
			DistrictMaster districtMaster = null;
26544 amit.gupta 1195
			LOGGER.info("Store shortname is {}", districtShortName);
26593 amit.gupta 1196
			districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName(districtShortName,
1197
					stateShortName);
26543 amit.gupta 1198
			if (districtMaster == null) {
26544 amit.gupta 1199
				districtMaster = districtMasterRepository.selectByShortnameNameAndStateShortName("FB", "HR");
26539 amit.gupta 1200
			}
26542 amit.gupta 1201
			LOGGER.info("Store id - {}", store.getId());
28825 tejbeer 1202
			// com.spice.profitmandi.dao.entity.user.User user = userMap.get(store.getId());
26536 amit.gupta 1203
			String urlString = districtMaster.getStateShortName() + "/"
27877 amit.gupta 1204
					+ Utils.getHyphenatedString(districtMaster.getName()) + "/" + store.getCode();
28346 amit.gupta 1205
			fofoRetailerUrlMap.put(store.getId(), urlString.toLowerCase());
26541 amit.gupta 1206
			LOGGER.info("Store is {} end", store);
26536 amit.gupta 1207
 
1208
		}
1209
		return fofoRetailerUrlMap;
26533 amit.gupta 1210
	}
1211
 
1212
	@Override
26590 amit.gupta 1213
	@Cacheable(value = "storeCodeRetailerMap", cacheManager = "oneDayCacheManager")
1214
	public Map<String, Integer> getStoreCodeRetailerMap() {
26533 amit.gupta 1215
		Map<Integer, String> map = this.getAllFofoRetailerIdUrlMap();
26596 amit.gupta 1216
		Map<String, Integer> returnMap = map.entrySet().stream().collect(Collectors.toMap(x -> {
26593 amit.gupta 1217
			String[] splitString = x.getValue().split("/");
27877 amit.gupta 1218
			return splitString[splitString.length - 1];
26593 amit.gupta 1219
		}, x -> x.getKey()));
26596 amit.gupta 1220
		LOGGER.info("returnMap {}", returnMap);
1221
		return returnMap;
26533 amit.gupta 1222
	}
27877 amit.gupta 1223
 
1224
	@Override
1225
	public String getPartnerCriteriaString(PartnerCriteria partnerCriteria) {
1226
 
1227
		StringBuilder sb = new StringBuilder();
1228
		if (partnerCriteria.getFofoIds().size() > 0) {
1229
			List<Integer> fofoIds = partnerCriteria.getFofoIds();
1230
			Map<Integer, CustomRetailer> customRetailers = this.getFofoRetailerUserId(fofoIds);
28024 tejbeer 1231
			List<String> businessNames = customRetailers.values().stream().map(x -> x.getBusinessName())
1232
					.collect(Collectors.toList());
27877 amit.gupta 1233
			sb.append(String.join(", ", businessNames));
1234
 
1235
		} else {
1236
			sb.append("All");
28024 tejbeer 1237
			if (partnerCriteria.getPartnerTypes().size() > 0) {
1238
				sb.append(" ").append(String.join(", ", partnerCriteria.getPartnerTypes().stream()
1239
						.map(x -> x.getValue()).collect(Collectors.toList())));
27877 amit.gupta 1240
			}
1241
			sb.append(" partners ");
28024 tejbeer 1242
			if (partnerCriteria.getRegionIds().size() > 0) {
27877 amit.gupta 1243
				sb.append("from ");
28024 tejbeer 1244
				sb.append(String.join(", ", partnerCriteria.getRegionIds().stream()
1245
						.map(x -> ProfitMandiConstants.WAREHOUSE_MAP.get(x)).collect(Collectors.toList())));
27877 amit.gupta 1246
			}
1247
		}
1248
		return sb.toString();
1249
	}
22980 ashik.ali 1250
}