Subversion Repositories SmartDukaan

Rev

Rev 15812 | Rev 16201 | 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
6
from dtr.storage import DataService
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
15804 manish.sha 15
import optparse
15795 manish.sha 16
 
17
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
18
 
19
DataService.initialize(db_hostname="localhost")
20
client = MongoClient('mongodb://localhost:27017/') 
21
 
22
def to_py_date(java_timestamp):
23
    date = datetime.datetime.fromtimestamp(java_timestamp)
24
    return date
25
 
26
class MerchantSubOrder():
27
    orderId = None
28
    merchantOrderId = None
29
    merchantSubOrderId = None
30
    storeId = None
31
    userId = None
32
    productCode = None
33
    brand = None
34
    productName = None
35
    amountPaid = None
36
    quantity = None
37
    unitPrice = None
38
    status = None
39
    createdTime = None
40
 
41
    def __init__(self,orderId, merchantOrderId, merchantSubOrderId, storeId, userId, productCode, productName, amountPaid, quantity,unitPrice, status, createdTime):
42
        self.orderId = orderId
43
        self.merchantOrderId = merchantOrderId
44
        self.merchantSubOrderId = merchantSubOrderId
45
        self.storeId = storeId
46
        self.userId = userId 
47
        self.productCode = productCode
48
        self.productName= productName
49
        self.amountPaid = amountPaid
50
        self.quantity = quantity
51
        self.unitPrice = unitPrice
52
        self.status = status
15798 manish.sha 53
        if createdTime is not None:
54
            self.createdTime = to_py_date(createdTime)
55
        else:
56
            self.createdTime = None
15795 manish.sha 57
        self.userId = userId
58
 
59
def getAndStoreMerchantSubOrders():
15806 manish.sha 60
    existingMaxOrderId = session.query(func.max(MerchantSubOrders.orderId)).one()
15795 manish.sha 61
    db = client.Dtr
62
    collection = db.merchantOrder
15806 manish.sha 63
    orders = collection.find({'orderId':{'$gt':int(existingMaxOrderId[0])}})
15795 manish.sha 64
    catalogdb = client.Catalog
65
    masterDataCollection = catalogdb.MasterData
66
    for order in orders:
67
        if order.has_key('subOrders'):
68
            orderId = order['orderId']
69
            merchantOrderId = order['merchantOrderId']
70
            storeId = order['storeId']
71
            userId = order['userId']
15798 manish.sha 72
            createdOnInt = None
73
            if order.has_key('createdOnInt'):
74
                createdOnInt = order['createdOnInt']
15795 manish.sha 75
            subOrders = order['subOrders']
76
            for subOrder in subOrders:
15801 manish.sha 77
                unitPrice = 0
78
                if subOrder.has_key('unitPrice'):
79
                    unitPrice = subOrder['unitPrice']
15802 manish.sha 80
                productCode = "Undefined"
81
                if subOrder.has_key('productCode'):
82
                    productCode = subOrder['productCode']
83
                merchantSubOrder = MerchantSubOrder(orderId, merchantOrderId, subOrder['merchantSubOrderId'], storeId, userId, productCode, subOrder['productTitle'], subOrder['amountPaid'], subOrder['quantity'], unitPrice, subOrder['status'], createdOnInt)
15795 manish.sha 84
                product = None
85
                if storeId in (1,2,4,5):
15803 manish.sha 86
                    product = list(masterDataCollection.find({'identifier':productCode.strip(), 'source_id':storeId}))
15795 manish.sha 87
                elif storeId == 3:
15803 manish.sha 88
                    product = list(masterDataCollection.find({'secondaryIdentifier':productCode.strip(), 'source_id':storeId}))
15800 manish.sha 89
                if product is not None and len(product)>0:
15795 manish.sha 90
                    merchantSubOrder.brand = product[0]["brand"]
91
                else:
92
                    merchantSubOrder.brand = 'NA'
93
 
94
                existingMerchantSubOrder = MerchantSubOrders.query.filter(MerchantSubOrders.orderId == orderId).filter(MerchantSubOrders.merchantOrderId == merchantOrderId).filter(MerchantSubOrders.merchantSubOrderId == merchantSubOrder.merchantSubOrderId).first()
95
                if existingMerchantSubOrder is None:
96
                    merchantSubOrderDetail = MerchantSubOrders()
97
                    merchantSubOrderDetail.orderId = merchantSubOrder.orderId
98
                    merchantSubOrderDetail.merchantOrderId = merchantSubOrder.merchantOrderId
99
                    merchantSubOrderDetail.merchantSubOrderId = merchantSubOrder.merchantSubOrderId
100
                    merchantSubOrderDetail.storeId = merchantSubOrder.storeId
101
                    merchantSubOrderDetail.userId = merchantSubOrder.userId
102
                    merchantSubOrderDetail.productCode = merchantSubOrder.productCode
103
                    merchantSubOrderDetail.brand = merchantSubOrder.brand
104
                    merchantSubOrderDetail.productName = merchantSubOrder.productName
105
                    merchantSubOrderDetail.amountPaid = merchantSubOrder.amountPaid
106
                    merchantSubOrderDetail.quantity = merchantSubOrder.quantity
107
                    merchantSubOrderDetail.unitPrice = merchantSubOrder.unitPrice
108
                    merchantSubOrderDetail.status = merchantSubOrder.status
109
                    merchantSubOrderDetail.createdTime = merchantSubOrder.createdTime
110
                    session.commit()          
111
 
112
 
15804 manish.sha 113
def initiateUserGroupSegmentation():
16083 manish.sha 114
    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) 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) 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 115
    cursor = db.cursor()
116
 
117
    deleteAllUserGroups = "delete from pushnotificationusergroups"
118
    try:
119
        cursor.execute(deleteAllUserGroups)
120
        db.commit()
121
    except:
122
        db.rollback()
123
 
124
    cursor.execute(userGroupSegmentationQuery)
125
    allUserGroups = cursor.fetchall()
126
    for userGroup in allUserGroups:
15810 manish.sha 127
        min_price = userGroup[2]
128
        if min_price is None:
129
            min_price = 0.0
130
        max_price = userGroup[3]
131
        if max_price is None:
132
            max_price = 0.0
133
        category_id = userGroup[5]
134
        if category_id is None:
135
            category_id= 0
136
 
15811 manish.sha 137
        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 138
        print sql
15804 manish.sha 139
        try:
140
            dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
141
            cursor = dtrdb.cursor()
142
            cursor.execute(sql)
143
            dtrdb.commit()
144
            dtrdb.close()
145
        except:
146
            dtrdb.rollback()
147
            dtrdb.close()
148
 
15795 manish.sha 149
def main():
15804 manish.sha 150
    parser = optparse.OptionParser()
151
    parser.add_option("-T", "--segmenttype", dest="segmenttype",
152
                      default="group",
153
                      type="str", help="To avoid not needed order backups",
154
                      metavar="SEGMENTTYPE")
155
    (options, args) = parser.parse_args()
156
    if options.segmenttype == 'full':
157
        getAndStoreMerchantSubOrders()
158
        initiateUserGroupSegmentation()
159
    if options.segmenttype == 'group':
160
        initiateUserGroupSegmentation()
15807 manish.sha 161
    if options.segmenttype == 'order':
162
        getAndStoreMerchantSubOrders()
15795 manish.sha 163
    db.close()
164
    if session.is_active:
165
        print "session is active. closing it."
166
        session.close()
167
    client.close()
168
 
169
if __name__=='__main__':
170
    main()