Subversion Repositories SmartDukaan

Rev

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

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