Subversion Repositories SmartDukaan

Rev

Rev 13869 | Rev 13930 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 13869 Rev 13927
Line 21... Line 21...
21
            'Accept-Language' : 'en-US,en;q=0.8',                     
21
            'Accept-Language' : 'en-US,en;q=0.8',                     
22
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
22
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
23
        }
23
        }
24
CASHBACK_URL = 'http://api.profittill.com/cashbacks/index/%s/%s'
24
CASHBACK_URL = 'http://api.profittill.com/cashbacks/index/%s/%s'
25
USER_LOOKUP_URL = 'http://api.profittill.com/user_account/saholic/%s'
25
USER_LOOKUP_URL = 'http://api.profittill.com/user_account/saholic/%s'
26
WALLET_CREDIT_URL = 'http://www.shop2020.in:8080/mobileapi/wallet!batchUpdate'
26
WALLET_CREDIT_URL = 'http://localhost:8080/mobileapi/wallet!batchUpdate'
27
 
27
 
28
def getStore(source_id):
28
def getStore(source_id):
29
    #module = sourceMap[source_id]
29
    #module = sourceMap[source_id]
30
    store = Store(source_id)
30
    store = Store(source_id)
31
    try:
31
    try:
Line 69... Line 69...
69
    ORDER_SHIPPED = 'Shipped' #Lets see if we can make use of it
69
    ORDER_SHIPPED = 'Shipped' #Lets see if we can make use of it
70
    ORDER_CANCELLED = 'Cancelled'
70
    ORDER_CANCELLED = 'Cancelled'
71
    
71
    
72
    CB_INIT = 'Waiting Confirmation'
72
    CB_INIT = 'Waiting Confirmation'
73
    CB_PENDING = 'Pending'
73
    CB_PENDING = 'Pending'
-
 
74
    CB_CREDIT_IN_PROCESS = 'Credited to wallet'
74
    CB_CREDITED = 'Credited to wallet'
75
    CB_CREDITED = 'Credited to wallet'
75
    CB_NA = 'Not Applicable'
76
    CB_NA = 'Not Applicable'
76
    CB_APPROVED = 'Approved'
77
    CB_APPROVED = 'Approved'
77
    CB_CANCELLED = 'Cancelled'
78
    CB_CANCELLED = 'Cancelled'
78
    
79
    
Line 144... Line 145...
144
        pass
145
        pass
145
    
146
    
146
    def _updateOrdersPayBackStatus(self, searchMap, updateMap):
147
    def _updateOrdersPayBackStatus(self, searchMap, updateMap):
147
        searchMap['subOrders.missingAff'] = False
148
        searchMap['subOrders.missingAff'] = False
148
        updateMap['subOrders.$.missingAff'] = True
149
        updateMap['subOrders.$.missingAff'] = True
149
        self.db.merchantOrder.update(searchMap, { '$set': updateMap })
150
        self.db.merchantOrder.update(searchMap, { '$set': updateMap }, multi=True)
150
        
151
        
151
    def _getActiveOrders(self, searchMap={}, collectionMap={}):
152
    def _getActiveOrders(self, searchMap={}, collectionMap={}):
152
        collection = self.db.merchantOrder
153
        collection = self.db.merchantOrder
153
        searchMap = dict(searchMap.items()+ {"closed": False, "storeId" : self.store_id}.items()) 
154
        searchMap = dict(searchMap.items()+ {"closed": False, "storeId" : self.store_id}.items()) 
154
        collectionMap =  dict(collectionMap.items() + {"orderSuccessUrl":1, "orderId":1,"subOrders":1, "placedOn":1}.items())
155
        collectionMap =  dict(collectionMap.items() + {"orderSuccessUrl":1, "orderId":1,"subOrders":1, "placedOn":1}.items())
Line 161... Line 162...
161
            if merchantSubOrderId == subOrder.get("merchantSubOrderId"):
162
            if merchantSubOrderId == subOrder.get("merchantSubOrderId"):
162
                return subOrder
163
                return subOrder
163
        return None
164
        return None
164
 
165
 
165
def settlePayBack():
166
def settlePayBack():
-
 
167
        client.Dtr.merchantOrder.update({'subOrders.cashBackStatus':Store.CB_APPROVED},{'subOrders.$.cashBackStatus':Store.CB_CREDIT_IN_PROCESS}, multi=True)    
166
        result = client.Dtr.merchantOrder\
168
        result = client.Dtr.merchantOrder\
167
            .aggregate([
169
            .aggregate([
168
                        {'$match':{'subOrders.cashBackStatus':Store.CB_APPROVED}},
170
                        {'$match':{'subOrders.cashBackStatus':Store.CB_CREDIT_IN_PROCESS}},
169
                        {'$unwind':"$subOrders"},
171
                        {'$unwind':"$subOrders"},
170
                        { 
172
                        { 
171
                         '$group':{
173
                         '$group':{
172
                                   '_id':'$userId',
174
                                   '_id':'$userId',
173
                                   'amount': { '$sum':'$subOrders.cashBackAmount'},
175
                                   'amount': { '$sum':'$subOrders.cashBackAmount'},
Line 175... Line 177...
175
                         }
177
                         }
176
                    ])['result']
178
                    ])['result']
177
                    
179
                    
178
        userAmountMap = {}
180
        userAmountMap = {}
179
        for res in result:
181
        for res in result:
180
            userAmountMap[res['_id']] = res['amount'] 
182
            userAmountMap[res['_id']] = res['amount']
-
 
183
        datetimeNow = datetime.now() 
181
        batchId = int(time.mktime(datetime.now().timetuple()))
184
        batchId = int(time.mktime(datetimeNow.timetuple()))
182
        batchUpdateMap = {'batchId':batchId}
185
        if refundToWallet(batchId, userAmountMap):
183
        batchUpdateMap['userAmount'] = result
186
            client.Dtr.merchantOrder.update({'subOrders.cashBackStatus':Store.CB_CREDIT_IN_PROCESS},{'subOrders.$.cashBackStatus':Store.CB_CREDITED, 'subOrders.$.batchId':batchId}, multi=True)
184
        #for 
-
 
185
        #get batch id
187
            for key, value in userAmountMap:
186
        print batchId 
-
 
187
        if __refundToWallet(batchUpdateMap):
188
                client.Dtr.refund.insert({"userId": key, "batch":batchId, "userAmount":value, "timestamp":datetime.strftime(datetimeNow,"%Y-%m-%d %H:%M:%S")})
188
            client.Dtr.merchantOrder.update({'subOrders.cashBackStatus':Store.CB_APPROVED},{'subOrders.$.cashBackStatus':Store.CB_CREDITED}, multi=True)
189
                client.Dtr.user.update({"userId":key}, {'$inc': { "credited": value}}, upsert=True)
189
        else:
190
        else:
190
            tprint("Error Occurred while running batch")
191
            tprint("Error Occurred while running batch.. Rolling Back")
-
 
192
            client.Dtr.merchantOrder.update({'subOrders.cashBackStatus':Store.CB_CREDIT_IN_PROCESS},{'subOrders.$.cashBackStatus':Store.CB_APPROVED}, multi=True)    
191
    
193
    
-
 
194
def refundToWallet(batchId, userAmountMap):
-
 
195
    batchUpdateMap = {}
-
 
196
    try :
-
 
197
        saholicUserAmountMap = {}
-
 
198
        for key, value in userAmountMap.iteritems():
-
 
199
            userLookupRequest = urllib2.Request(USER_LOOKUP_URL %(key), headers=headers)
-
 
200
            try:
-
 
201
                response = urllib2.urlopen(userLookupRequest).read()
-
 
202
                saholicUserId = json.loads(response)['account_id']
-
 
203
                saholicUserAmountMap[saholicUserId] = value
-
 
204
            except:
-
 
205
                tprint("Could not fetch saholic id for user : " + key)
-
 
206
                continue
-
 
207
        batchUpdateMap['userAmount'] = json.dumps(saholicUserAmountMap)
-
 
208
        batchUpdateMap['batchId'] = batchId
-
 
209
        request = urllib2.Request(WALLET_CREDIT_URL, headers=headers)
-
 
210
        data = urllib.urlencode(batchUpdateMap)
-
 
211
        response = urllib2.urlopen(request, data)
-
 
212
        return json.loads(response.read())['response']['credited']
-
 
213
    except:
-
 
214
        traceback.print_exc()
-
 
215
        tprint("Could not batch refund")
-
 
216
        return False
-
 
217
    
-
 
218
    
-
 
219
    #return json.loads(response.read())['credited']
192
    
220
    
193
def main():
221
def main():
194
    #store = getStore(3)
222
    #store = getStore(3)
195
    #print store.getCashbackAmount('864683341', 100)
223
    #print store.getCashbackAmount('864683341', 100)
196
    #data = urllib.urlencode({'orderId':6000, 'amount':200})
224
    #data = urllib.urlencode({'orderId':6000, 'amount':200})
197
    #request = urllib2.Request(WALLET_CREDIT_URL % (483649), headers=headers)
225
    #request = urllib2.Request(WALLET_CREDIT_URL % (483649), headers=headers)
198
    #response = urllib2.urlopen(request, data)
226
    #response = urllib2.urlopen(request, data)
199
    #print response.read()
227
    #print response.read()
200
    settlePayBack()
228
    #settlePayBack()
-
 
229
    batchId =1 
-
 
230
    userAmount = {483649:3.0}
-
 
231
    refundToWallet(batchId, userAmount)
201
        
232
        
202
if __name__ == '__main__':
233
if __name__ == '__main__':
203
    main()
234
    main()
204
 
235
 
205
 
236
 
206
###
237
###
207
#Settlement process is suposed to be a batch and run weekly
238
#Settlement process is suposed to be a batch and run weekly
208
#It is should be running on first hour of mondays. As cron should
239
#It is should be running on first hour of mondays. As cron should
209
# Maintain a batch id.
240
# Maintain a batch id.
210
 
241
 
211
def __refundToWallet(self, batchUpdateMap):
-
 
212
    result = False
-
 
213
    try :
-
 
214
        userAmountMap = batchUpdateMap['userAmount']
-
 
215
        saholicUserAmountMap = {}
-
 
216
        for key, value in userAmountMap:
-
 
217
            userLookupRequest = urllib2.Request(USER_LOOKUP_URL %(key), headers=headers)
-
 
218
            response = urllib2.urlopen(userLookupRequest).read()
-
 
219
            saholicUserId = json.loads(response)['account_id']
-
 
220
            saholicUserAmountMap[saholicUserId] = value
-
 
221
        batchUpdateMap['userAmount'] = saholicUserAmountMap
-
 
222
        request = urllib2.Request(WALLET_CREDIT_URL, headers=headers)
-
 
223
        data = urllib.urlencode(batchUpdateMap)
-
 
224
        response = urllib2.urlopen(request, data)
-
 
225
    except:
-
 
226
        traceback.print_exc()
-
 
227
        return False
-
 
228
    
-
 
229
    return json.loads(response.read())['credited']
-
 
230
 
242
 
231
def getBrowserObject():
243
def getBrowserObject():
232
    import cookielib
244
    import cookielib
233
    br = mechanize.Browser(factory=mechanize.RobustFactory())
245
    br = mechanize.Browser(factory=mechanize.RobustFactory())
234
    cj = cookielib.LWPCookieJar()
246
    cj = cookielib.LWPCookieJar()
Line 258... Line 270...
258
        html = gz.read()
270
        html = gz.read()
259
        gz.close()
271
        gz.close()
260
        return html
272
        return html
261
 
273
 
262
def tprint(*msg):
274
def tprint(*msg):
263
    print datetime.now(), "-", msg
-
 
264
275
    print datetime.now(), "-", msg
-
 
276
    
-
 
277
265
278