Subversion Repositories SmartDukaan

Rev

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