Subversion Repositories SmartDukaan

Rev

Rev 15807 | Rev 15810 | 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():
15806 manish.sha 62
    existingMaxOrderId = session.query(func.max(MerchantSubOrders.orderId)).one()
15795 manish.sha 63
    db = client.Dtr
64
    collection = db.merchantOrder
15806 manish.sha 65
    orders = collection.find({'orderId':{'$gt':int(existingMaxOrderId[0])}})
15795 manish.sha 66
    catalogdb = client.Catalog
67
    masterDataCollection = catalogdb.MasterData
68
    for order in orders:
69
        if order.has_key('subOrders'):
70
            orderId = order['orderId']
71
            merchantOrderId = order['merchantOrderId']
72
            storeId = order['storeId']
73
            userId = order['userId']
15798 manish.sha 74
            createdOnInt = None
75
            if order.has_key('createdOnInt'):
76
                createdOnInt = order['createdOnInt']
15795 manish.sha 77
            subOrders = order['subOrders']
78
            for subOrder in subOrders:
15801 manish.sha 79
                unitPrice = 0
80
                if subOrder.has_key('unitPrice'):
81
                    unitPrice = subOrder['unitPrice']
15802 manish.sha 82
                productCode = "Undefined"
83
                if subOrder.has_key('productCode'):
84
                    productCode = subOrder['productCode']
85
                merchantSubOrder = MerchantSubOrder(orderId, merchantOrderId, subOrder['merchantSubOrderId'], storeId, userId, productCode, subOrder['productTitle'], subOrder['amountPaid'], subOrder['quantity'], unitPrice, subOrder['status'], createdOnInt)
15795 manish.sha 86
                product = None
87
                if storeId in (1,2,4,5):
15803 manish.sha 88
                    product = list(masterDataCollection.find({'identifier':productCode.strip(), 'source_id':storeId}))
15795 manish.sha 89
                elif storeId == 3:
15803 manish.sha 90
                    product = list(masterDataCollection.find({'secondaryIdentifier':productCode.strip(), 'source_id':storeId}))
15800 manish.sha 91
                if product is not None and len(product)>0:
15795 manish.sha 92
                    merchantSubOrder.brand = product[0]["brand"]
93
                else:
94
                    merchantSubOrder.brand = 'NA'
95
 
96
                existingMerchantSubOrder = MerchantSubOrders.query.filter(MerchantSubOrders.orderId == orderId).filter(MerchantSubOrders.merchantOrderId == merchantOrderId).filter(MerchantSubOrders.merchantSubOrderId == merchantSubOrder.merchantSubOrderId).first()
97
                if existingMerchantSubOrder is None:
98
                    merchantSubOrderDetail = MerchantSubOrders()
99
                    merchantSubOrderDetail.orderId = merchantSubOrder.orderId
100
                    merchantSubOrderDetail.merchantOrderId = merchantSubOrder.merchantOrderId
101
                    merchantSubOrderDetail.merchantSubOrderId = merchantSubOrder.merchantSubOrderId
102
                    merchantSubOrderDetail.storeId = merchantSubOrder.storeId
103
                    merchantSubOrderDetail.userId = merchantSubOrder.userId
104
                    merchantSubOrderDetail.productCode = merchantSubOrder.productCode
105
                    merchantSubOrderDetail.brand = merchantSubOrder.brand
106
                    merchantSubOrderDetail.productName = merchantSubOrder.productName
107
                    merchantSubOrderDetail.amountPaid = merchantSubOrder.amountPaid
108
                    merchantSubOrderDetail.quantity = merchantSubOrder.quantity
109
                    merchantSubOrderDetail.unitPrice = merchantSubOrder.unitPrice
110
                    merchantSubOrderDetail.status = merchantSubOrder.status
111
                    merchantSubOrderDetail.createdTime = merchantSubOrder.createdTime
112
                    session.commit()          
113
 
114
 
15804 manish.sha 115
def initiateUserGroupSegmentation():
15809 manish.sha 116
    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 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 group by x.brand, x.pricerange, x.category_id UNION select y.brand, GROUP_CONCAT(distinct y.userid) userids, 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 group by y.brand, y.category_id"
15804 manish.sha 117
    cursor = db.cursor()
118
 
119
    deleteAllUserGroups = "delete from pushnotificationusergroups"
120
    try:
121
        cursor.execute(deleteAllUserGroups)
122
        db.commit()
123
    except:
124
        db.rollback()
125
 
126
    cursor.execute(userGroupSegmentationQuery)
127
    allUserGroups = cursor.fetchall()
128
    for userGroup in allUserGroups:
129
        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])
15805 manish.sha 130
        print sql
15804 manish.sha 131
        try:
132
            dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
133
            cursor = dtrdb.cursor()
134
            cursor.execute(sql)
135
            dtrdb.commit()
136
            dtrdb.close()
137
        except:
138
            dtrdb.rollback()
139
            dtrdb.close()
140
 
15795 manish.sha 141
def main():
15804 manish.sha 142
    parser = optparse.OptionParser()
143
    parser.add_option("-T", "--segmenttype", dest="segmenttype",
144
                      default="group",
145
                      type="str", help="To avoid not needed order backups",
146
                      metavar="SEGMENTTYPE")
147
    (options, args) = parser.parse_args()
148
    if options.segmenttype == 'full':
149
        getAndStoreMerchantSubOrders()
150
        initiateUserGroupSegmentation()
151
    if options.segmenttype == 'group':
152
        initiateUserGroupSegmentation()
15807 manish.sha 153
    if options.segmenttype == 'order':
154
        getAndStoreMerchantSubOrders()
15795 manish.sha 155
    db.close()
156
    if session.is_active:
157
        print "session is active. closing it."
158
        session.close()
159
    client.close()
160
 
161
if __name__=='__main__':
162
    main()