Subversion Repositories SmartDukaan

Rev

Rev 28025 | Rev 31720 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.repository.dtr;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
import com.spice.profitmandi.common.util.Utils;
import com.spice.profitmandi.dao.entity.dtr.NotificationCampaigns;
import com.spice.profitmandi.dao.model.ContentPojo;
import com.spice.profitmandi.dao.model.FofoForm;
import com.spice.profitmandi.dao.model.RetailerFofoInterest;

public class Mongo {

        private static final Logger LOGGER = LogManager.getLogger(Mongo.class);

        private static final String CONTENT = "CONTENT";
        private static final String SITE_CONTENT = "siteContent";
        private static final String CATALOG_DB = "Catalog";
        private static final String MASTER_DATA = "MasterData";
        private static final String FOFO_DB = "Fofo";
        private static final String FOFO_BRANDS = "brands";
        private static final String PROFITMANDI_BANNERS = "banners";
        private static final String RETAILER_FOFO_INTEREST = "RetailerFofoInterest";
        private static final String FOFO_FORM_COLLECTION = "RegistrationForm";
        private static final String NOTIFICATION_CAMPAIGNS = "notificationcampaigns";
        private static final String USER_DB = "User";
        private static final int MONGO_PORT = 27017;

        private static final Gson gson = new Gson();
        private static final List<String> BLOCKED_BRANDS = Arrays.asList();
        public static final Map<Integer, List<String>> PARTNER_BLoCKED_BRANDS = new HashMap<>();
        public static final Map<Integer, List<String>> PARTNER_ALLOWED_BRANDS = new HashMap<>();

        static {
                PARTNER_BLoCKED_BRANDS.put(175135597, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175135183, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175137445, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175137557, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138281, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138441, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138447, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138570, Arrays.asList("Vivo"));
                // TITU
                PARTNER_BLoCKED_BRANDS.put(175138610, Arrays.asList("Vivo"));
                // HRPHK204 = MOBILE ZONE
                // PARTNER_BLoCKED_BRANDS.put(175138917, Arrays.asList("Vivo"));
                // HRKK205, SATIJA
                PARTNER_BLoCKED_BRANDS.put(175138918, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138611, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138639, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138716, Arrays.asList("Vivo"));
                // Laxmi Communication - Shahbad
                // PARTNER_BLoCKED_BRANDS.put(175138911, Arrays.asList("Vivo"));
                // Chaudhary Electronics
                // PARTNER_BLoCKED_BRANDS.put(175138906, Arrays.asList("Vivo"));
                // DY Venturs
                // PARTNER_BLoCKED_BRANDS.put(175138874, Arrays.asList("Vivo"));
                // Pardeep Telecom
                // PARTNER_BLoCKED_BRANDS.put(175138843, Arrays.asList("Vivo"));
                // PARTNER_BLoCKED_BRANDS.put(175138733,Arrays.asList("Vivo"));
                // Venus Agencies
                // PARTNER_BLoCKED_BRANDS.put(175138801, Arrays.asList("Vivo"));
                // PARTNER_BLoCKED_BRANDS.put(175138717, Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138803, Arrays.asList("Vivo"));
                // PARTNER_BLoCKED_BRANDS.put(175138821, Arrays.asList("Vivo"));
                // PARTNER_BLoCKED_BRANDS.put(175138820,Arrays.asList("Vivo"));
                PARTNER_BLoCKED_BRANDS.put(175138718, Arrays.asList("Vivo"));
                // Gaurav Electronics
                PARTNER_BLoCKED_BRANDS.put(175138637, Arrays.asList("Vivo"));
                // PARTNER_BLoCKED_BRANDS.put(175138814,Arrays.asList("Vivo"));
                // PARTNER_BLoCKED_BRANDS.put(175138833, Arrays.asList("Vivo"));
                // Durga Enterprises
                // PARTNER_BLoCKED_BRANDS.put(175138832, Arrays.asList("Vivo"));
                PARTNER_ALLOWED_BRANDS.put(172157716, Arrays.asList("Realme"));
                // DY Ventures
                PARTNER_ALLOWED_BRANDS.put(175138874, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175135227, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175135707, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175135923, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138372, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138520, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138522, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138541, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138674, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138716, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138801, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138812, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138813, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138814, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138816, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138820, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138836, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138838, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138840, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138842, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138843, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138847, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138858, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138859, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138860, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138862, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138863, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138865, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138868, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138829, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138864, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138878, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138876, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138883, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138862, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138847, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138870, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138873, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138879, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138884, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138872, Arrays.asList("Realme"));
                PARTNER_ALLOWED_BRANDS.put(175138866, Arrays.asList("Realme"));

        }
        @Autowired
        private RetailerBlockBrandsRepository retailerBlockBrandsRepository;

        private MongoClient mongoClient;
        private MongoClient contentMongoClient;

        public Mongo(String mongoHost, String contentMongoHost) {
                try {
                        LOGGER.info("mongoHost => {}, contentMongoHost {} ", mongoHost, contentMongoHost);
                        mongoClient = new MongoClient(mongoHost, MONGO_PORT);
                        contentMongoClient = new MongoClient(contentMongoHost, MONGO_PORT);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        public ContentPojo getEntityById(long id) throws Exception {
                DB db = contentMongoClient.getDB(CONTENT);
                DBCollection collection = db.getCollection(SITE_CONTENT);
                BasicDBObject obj = new BasicDBObject();
                obj.append("_id", id);
                DBObject result = collection.findOne(obj);
                if (result == null) {
                        throw new Exception();
                }
                LOGGER.info(result.toMap());
                ContentPojo cp = gson.fromJson(new BasicDBObject(result.toMap()).toJson(), ContentPojo.class);
                if (cp.getDefaultImageUrl() != null) {
                        cp.setDefaultImageUrl(cp.getDefaultImageUrl().replaceAll("saholic", "smartdukaan"));
                }

                LOGGER.info("cp" + cp);

                return cp;
        }

        public List<DBObject> getMongoBrands(int fofoId, String email, int categoryId) {
                List<DBObject> brandsDisplay = this.getBrandsToDisplay(categoryId);
                if (fofoId == Utils.SYSTEM_PARTNER_ID) {
                        return brandsDisplay;
                }
                List<String> blockedBrands = retailerBlockBrandsRepository.selectAllByRetailer(fofoId).stream()
                                .map(x -> x.getBlockBrands()).collect(Collectors.toList());
                LOGGER.info("blockedBrands" + blockedBrands);
                brandsDisplay = brandsDisplay.stream().filter(x -> !blockedBrands.contains(x.get("name")))
                                .collect(Collectors.toList());

                LOGGER.info("brandsDisplay" + brandsDisplay);
                return brandsDisplay;
        }

        public ContentPojo getEntityByName(String name) throws Exception {
                LOGGER.info("Name --- {}", name);
                DB db = contentMongoClient.getDB(CONTENT);
                DBCollection collection = db.getCollection(SITE_CONTENT);
                BasicDBObject obj = new BasicDBObject();
                obj.append("title", name);
                DBObject result = collection.findOne();
                if (result == null) {
                        throw new Exception();
                }
                return gson.fromJson(new BasicDBObject(result.toMap()).toJson(), ContentPojo.class);
        }

        public void persistEntity(ContentPojo contentPojo) {
                DB db = contentMongoClient.getDB(CONTENT);
                DBCollection collection = db.getCollection(SITE_CONTENT);
                insertOrUpdateById(collection, contentPojo.getId(), contentPojo);

        }

        private static <T> void insertOrUpdateById(DBCollection collection, long id, T obj) {
                DBObject dbo = BasicDBObject.parse(gson.toJson(obj));
                dbo.put("_id", id);
                collection.update(new BasicDBObject("_id", id), dbo, true, false);
        }

        public JSONObject getItemsByBundleId(long bundleId) throws Exception {
                DB db = mongoClient.getDB(CATALOG_DB);
                DBCollection collection = db.getCollection(MASTER_DATA);
                BasicDBObject obj = new BasicDBObject();
                BasicDBObject in_query = new BasicDBObject();
                obj.append("skuBundleId", bundleId);
                in_query.append("$in", new int[] { 1, 2, 3, 4, 5, 6, 7 });
                obj.append("source_id", in_query);
                DBObject result = collection.findOne(obj);
                if (result == null) {
                        throw new Exception();
                }
                return new JSONObject(JSON.serialize(result));
        }

        public JSONObject getItemByID(long id) throws Exception {
                DB db = mongoClient.getDB(CATALOG_DB);
                DBCollection collection = db.getCollection(MASTER_DATA);
                BasicDBObject obj = new BasicDBObject();
                obj.append("_id", id);
                DBObject result = collection.findOne(obj);
                if (result == null) {
                        throw new Exception();
                }
                return new JSONObject(JSON.serialize(result));
        }

        public void persistFofoRegInfo(FofoForm ff) {
                DB db = mongoClient.getDB(FOFO_DB);
                DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
                if (ff.get_id() == 0) {
                        BasicDBObject orderBy = new BasicDBObject();
                        orderBy.put("_id", -1);
                        DBCursor cursor = collection.find().sort(orderBy).limit(1);
                        long id = 1l;
                        while (cursor.hasNext()) {
                                FofoForm existingFofo = gson.fromJson(cursor.next().toString(), FofoForm.class);
                                id = existingFofo.get_id() + 1;
                        }
                        ff.set_id(id);
                }
                DBObject dbObject = (DBObject) JSON.parse(gson.toJson(ff));
                collection.save(dbObject);
        }

        public List<FofoForm> getFofoForms(int offset, int limit) {
                List<FofoForm> ffList = new ArrayList<FofoForm>();
                DB db = mongoClient.getDB(FOFO_DB);
                DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
                BasicDBObject orderBy = new BasicDBObject();
                orderBy.put("_id", -1);
                DBCursor dbc = collection.find().sort(orderBy).limit(limit).skip(offset);
                while (dbc.hasNext()) {
                        ffList.add(convertJSONToPojo(dbc.next().toString()));
                }
                return ffList;
        }

        public String getFofoFormJsonStringByFofoId(int fofoId) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                filter.append("_id", fofoId);
                DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
                DBObject fofoDbOject = collection.findOne(filter);
                if (fofoDbOject != null) {
                        return fofoDbOject.toString();
                } else {
                        return null;
                }
        }

        public String getFofoFormJsonStringByEmail(String email) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                filter.append("registeredEmail1", email);
                DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
                DBObject fofoDbOject = collection.findOne(filter);
                if (fofoDbOject != null) {
                        return fofoDbOject.toString();
                } else {
                        return null;
                }
        }

        public String getFofoFormsJsonString() {
                DB db = mongoClient.getDB(FOFO_DB);
                DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
                DBCursor cursor = collection.find();
                StringBuilder fofoFormsJsonString = new StringBuilder();
                fofoFormsJsonString.append("[");
                while (cursor.hasNext()) {
                        fofoFormsJsonString.append(cursor.next().toString());
                        if (cursor.hasNext()) {
                                fofoFormsJsonString.append(",");
                        }
                }
                fofoFormsJsonString.append("]");
                return fofoFormsJsonString.toString();
        }

        public FofoForm getFofoForm(int fofoId) {
                String fofoFormJsonString = getFofoFormJsonStringByFofoId(fofoId);
                System.out.println(fofoFormJsonString);
                return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
                // return convertJSONToPojo(fofoDbOject.toString());
        }

        public FofoForm getFofoForm(String email) {
                String fofoFormJsonString = getFofoFormJsonStringByEmail(email);
                System.out.println(fofoFormJsonString);
                return new Gson().fromJson(fofoFormJsonString, FofoForm.class);
                // return convertJSONToPojo(fofoDbOject.toString());
        }

        private static FofoForm convertJSONToPojo(String json) {

                Type type = new TypeToken<FofoForm>() {
                }.getType();

                return new Gson().fromJson(json, type);

        }

        public void updateColumnsById(Map<String, Integer> map, int fofoId) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                filter.append("_id", fofoId);
                DBCollection collection = db.getCollection(FOFO_FORM_COLLECTION);
                BasicDBObject updateFields = new BasicDBObject();
                for (Map.Entry<String, Integer> entry : map.entrySet()) {
                        updateFields.append(entry.getKey(), entry.getValue());
                }
                BasicDBObject newDocument = new BasicDBObject();
                newDocument.append("$set", updateFields);
                collection.update(filter, newDocument);
        }

        public List<DBObject> getBrandsToDisplay(int categoryId) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                filter.append("active", true);
                if (categoryId != 0) {
                        filter.append("categoryId", categoryId);
                }
                return db.getCollection(FOFO_BRANDS).find(filter).toArray();
        }

        public List<DBObject> getAllBrandsToDisplay(int categoryId) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                if (categoryId != 0) {
                        filter.append("categoryId", categoryId);
                }
                return db.getCollection(FOFO_BRANDS).find(filter).toArray();
        }

        public List<DBObject> getBannersByType(String bannerType) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                filter.append("type", bannerType);
                BasicDBObject orderBy = new BasicDBObject();
                orderBy.put("rank", 1);
                return db.getCollection(PROFITMANDI_BANNERS).find(filter).sort(orderBy).toArray();
        }

        @SuppressWarnings("unchecked")
        public List<Document> getSubcategoriesToDisplay() {
                MongoDatabase db = mongoClient.getDatabase("Catalog");
                System.out.println("Connection to MongoDB database successfully");
                MongoCollection<Document> collection = db.getCollection("Deals");

                Document object = new Document().append("$match", new Document().append("category_id", 6).append("showDeal", 1)
                                .append("dealRankPoints", new Document("$gt", 0)));
                Document ob = new Document("$group",
                                new Document().append("_id",
                                                new Document().append("subCategoryId", "$subCategoryId").append("subCategory", "$subCategory"))
                                                .append("count", new Document("$sum", 1)));
                List<Document> pipeline = Arrays.asList(object, ob);
                AggregateIterable<Document> cursor = collection.aggregate(pipeline);

                List<Document> resultDocuments = new ArrayList<>();
                for (Document dbo : cursor) {
                        System.out.println(dbo.toString());
                        LOGGER.info("categories" + dbo.toString());
                        resultDocuments.add(dbo);
                }
                return resultDocuments;
        }

        public boolean saveRetailerInterestOnFofo(RetailerFofoInterest retailerInterest) {
                DB db = mongoClient.getDB(FOFO_DB);
                Gson gs = new Gson();
                DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
                DBObject dbObject = (DBObject) JSON.parse(gs.toJson(retailerInterest));
                fofoInterestCollection.save(dbObject);
                return true;
        }

        public boolean hasRetailerShownInterest(int userId) {
                DB db = mongoClient.getDB(FOFO_DB);
                BasicDBObject filter = new BasicDBObject();
                filter.append("userId", userId);
                DBCollection fofoInterestCollection = db.getCollection(RETAILER_FOFO_INTEREST);
                return fofoInterestCollection.findOne(filter) != null;
        }

        public void persistNotificationCmpInfo(NotificationCampaigns ff) {
                DB db = mongoClient.getDB(USER_DB);
                DBCollection collection = db.getCollection(NOTIFICATION_CAMPAIGNS);
                if (ff.get_id() == 0) {
                        BasicDBObject orderBy = new BasicDBObject();
                        orderBy.put("_id", -1);
                        DBCursor cursor = collection.find().sort(orderBy).limit(1);
                        long id = 1l;
                        while (cursor.hasNext()) {
                                Gson gson = new Gson();
                                NotificationCampaigns existingFofo = gson.fromJson(cursor.next().toString(),
                                                NotificationCampaigns.class);
                                id = existingFofo.get_id() + 1;
                        }
                        ff.set_id(id);
                }
                Gson gs = new Gson();
                DBObject dbObject = (DBObject) JSON.parse(gs.toJson(ff));
                collection.save(dbObject);
        }

}