Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
15795 manish.sha 1
#brandAndPriceSql = "select b.brand, GROUP_CONCAT(distinct b.user_id), p.min_price, p.max_price, p.category_id, concat(p.min_price, '-', p.max_price) pricerange, 'BPP' as SubCategory, 'CB' as Main_Category from brand_preferences b join price_preferences p on b.user_id= p.user_id where b.status='show' and trim(coalesce(b.brand, '')) <>'' group by b.brand, pricerange, p.category_id"
2
#clickAndPriceSql = "select b.brand, GROUP_CONCAT(distinct b.user_id), p.min_price, p.max_price, p.category_id, concat(p.min_price, '-', p.max_price) pricerange, 'CPP' as SubCategory, 'CB' as Main_Category from clicks b join price_preferences p on b.user_id= p.user_id where trim(coalesce(b.brand, '')) <>'' group by b.brand, pricerange, p.category_id"
3
import os
4
import re
5
import smtplib
6
import csv
7
import MySQLdb
8
from dtr.storage import DataService
9
from dtr.storage.DataService import MerchantSubOrders
10
from elixir import *
11
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
12
from sqlalchemy.sql import func
13
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
14
    between
15
import datetime
16
from pymongo.mongo_client import MongoClient
15804 manish.sha 17
import optparse
15795 manish.sha 18
 
19
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
20
 
21
DataService.initialize(db_hostname="localhost")
22
client = MongoClient('mongodb://localhost:27017/') 
23
 
24
def to_py_date(java_timestamp):
25
    date = datetime.datetime.fromtimestamp(java_timestamp)
26
    return date
27
 
28
class MerchantSubOrder():
29
    orderId = None
30
    merchantOrderId = None
31
    merchantSubOrderId = None
32
    storeId = None
33
    userId = None
34
    productCode = None
35
    brand = None
36
    productName = None
37
    amountPaid = None
38
    quantity = None
39
    unitPrice = None
40
    status = None
41
    createdTime = None
42
 
43
    def __init__(self,orderId, merchantOrderId, merchantSubOrderId, storeId, userId, productCode, productName, amountPaid, quantity,unitPrice, status, createdTime):
44
        self.orderId = orderId
45
        self.merchantOrderId = merchantOrderId
46
        self.merchantSubOrderId = merchantSubOrderId
47
        self.storeId = storeId
48
        self.userId = userId 
49
        self.productCode = productCode
50
        self.productName= productName
51
        self.amountPaid = amountPaid
52
        self.quantity = quantity
53
        self.unitPrice = unitPrice
54
        self.status = status
15798 manish.sha 55
        if createdTime is not None:
56
            self.createdTime = to_py_date(createdTime)
57
        else:
58
            self.createdTime = None
15795 manish.sha 59
        self.userId = userId
60
 
61
def getAndStoreMerchantSubOrders():
62
    db = client.Dtr
63
    collection = db.merchantOrder
64
    orders = collection.find()
65
    catalogdb = client.Catalog
66
    masterDataCollection = catalogdb.MasterData
67
    for order in orders:
68
        if order.has_key('subOrders'):
69
            orderId = order['orderId']
70
            merchantOrderId = order['merchantOrderId']
71
            storeId = order['storeId']
72
            userId = order['userId']
15798 manish.sha 73
            createdOnInt = None
74
            if order.has_key('createdOnInt'):
75
                createdOnInt = order['createdOnInt']
15795 manish.sha 76
            subOrders = order['subOrders']
77
            for subOrder in subOrders:
15801 manish.sha 78
                unitPrice = 0
79
                if subOrder.has_key('unitPrice'):
80
                    unitPrice = subOrder['unitPrice']
15802 manish.sha 81
                productCode = "Undefined"
82
                if subOrder.has_key('productCode'):
83
                    productCode = subOrder['productCode']
84
                merchantSubOrder = MerchantSubOrder(orderId, merchantOrderId, subOrder['merchantSubOrderId'], storeId, userId, productCode, subOrder['productTitle'], subOrder['amountPaid'], subOrder['quantity'], unitPrice, subOrder['status'], createdOnInt)
15795 manish.sha 85
                product = None
86
                if storeId in (1,2,4,5):
15803 manish.sha 87
                    product = list(masterDataCollection.find({'identifier':productCode.strip(), 'source_id':storeId}))
15795 manish.sha 88
                elif storeId == 3:
15803 manish.sha 89
                    product = list(masterDataCollection.find({'secondaryIdentifier':productCode.strip(), 'source_id':storeId}))
15800 manish.sha 90
                if product is not None and len(product)>0:
15795 manish.sha 91
                    merchantSubOrder.brand = product[0]["brand"]
92
                else:
93
                    merchantSubOrder.brand = 'NA'
94
 
95
                existingMerchantSubOrder = MerchantSubOrders.query.filter(MerchantSubOrders.orderId == orderId).filter(MerchantSubOrders.merchantOrderId == merchantOrderId).filter(MerchantSubOrders.merchantSubOrderId == merchantSubOrder.merchantSubOrderId).first()
96
                if existingMerchantSubOrder is None:
97
                    merchantSubOrderDetail = MerchantSubOrders()
98
                    merchantSubOrderDetail.orderId = merchantSubOrder.orderId
99
                    merchantSubOrderDetail.merchantOrderId = merchantSubOrder.merchantOrderId
100
                    merchantSubOrderDetail.merchantSubOrderId = merchantSubOrder.merchantSubOrderId
101
                    merchantSubOrderDetail.storeId = merchantSubOrder.storeId
102
                    merchantSubOrderDetail.userId = merchantSubOrder.userId
103
                    merchantSubOrderDetail.productCode = merchantSubOrder.productCode
104
                    merchantSubOrderDetail.brand = merchantSubOrder.brand
105
                    merchantSubOrderDetail.productName = merchantSubOrder.productName
106
                    merchantSubOrderDetail.amountPaid = merchantSubOrder.amountPaid
107
                    merchantSubOrderDetail.quantity = merchantSubOrder.quantity
108
                    merchantSubOrderDetail.unitPrice = merchantSubOrder.unitPrice
109
                    merchantSubOrderDetail.status = merchantSubOrder.status
110
                    merchantSubOrderDetail.createdTime = merchantSubOrder.createdTime
111
                    session.commit()          
112
 
113
 
15804 manish.sha 114
def initiateUserGroupSegmentation():
115
    userGroupSegmentationQuery ="select x.brand, GROUP_CONCAT(distinct x.userid) userids, x.min_price, x.max_price, x.pricerange, x.category_id from (select b.brand, b.user_id userid, p.min_price, p.max_price, p.category_id, concat(p.min_price, '-', p.max_price) pricerange from brand_preferences b join price_preferences p on b.user_id= p.user_id where b.status='show' and trim(coalesce(b.brand, '')) <>'' group by b.brand, pricerange, p.category_id, b.user_id UNION select b.brand, b.user_id userid, p.min_price, p.max_price, p.category_id, concat(p.min_price, '-', p.max_price) pricerange from clicks b join price_preferences p on b.user_id= p.user_id where trim(coalesce(b.brand, '')) <>'' group by b.brand, pricerange, p.category_id, b.user_id UNION select b.brand, s.user_id userid, p.min_price, p.max_price, p.category_id, concat(p.min_price, '-', p.max_price) pricerange from search_terms s join (select distinct brand from brand_preferences where trim(coalesce(brand, '')) <>'') b on lower(s.search_term) like concat('%', lower(b.brand), '%') join price_preferences p on s.user_id= p.user_id group by b.brand, pricerange, p.category_id, s.user_id UNION select b.brand, b.userId userid, p.min_price, p.max_price, p.category_id, concat(p.min_price, '-', p.max_price) pricerange from merchantsuborders b join price_preferences p on b.userId= p.user_id where trim(coalesce(b.brand, '')) <>'' and b.brand!='NA' group by b.brand, pricerange, p.category_id, b.userId) as x group by x.brand, x.pricerange, x.category_id"
116
    cursor = db.cursor()
117
 
118
    deleteAllUserGroups = "delete from pushnotificationusergroups"
119
    try:
120
        cursor.execute(deleteAllUserGroups)
121
        db.commit()
122
    except:
123
        db.rollback()
124
 
125
    cursor.execute(userGroupSegmentationQuery)
126
    allUserGroups = cursor.fetchall()
127
    for userGroup in allUserGroups:
128
        sql = "insert into pushnotificationusergroups (brand, userids, min_price, max_price, pricerange, category_id) values('%s', '%s', %f, %f, '%s', %d)"%(userGroup[0], userGroup[1], userGroup[2], userGroup[3], userGroup[4], userGroup[5])
129
        try:
130
            dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
131
            cursor = dtrdb.cursor()
132
            cursor.execute(sql)
133
            dtrdb.commit()
134
            dtrdb.close()
135
        except:
136
            dtrdb.rollback()
137
            dtrdb.close()
138
 
15795 manish.sha 139
def main():
15804 manish.sha 140
    parser = optparse.OptionParser()
141
    parser.add_option("-T", "--segmenttype", dest="segmenttype",
142
                      default="group",
143
                      type="str", help="To avoid not needed order backups",
144
                      metavar="SEGMENTTYPE")
145
    (options, args) = parser.parse_args()
146
    if options.segmenttype == 'full':
147
        getAndStoreMerchantSubOrders()
148
        initiateUserGroupSegmentation()
149
    if options.segmenttype == 'group':
150
        initiateUserGroupSegmentation()
15795 manish.sha 151
    db.close()
152
    if session.is_active:
153
        print "session is active. closing it."
154
        session.close()
155
    client.close()
156
 
157
if __name__=='__main__':
158
    main()