Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
104 ashish 1
'''
2
Created on 29-Mar-2010
3
 
2536 chandransh 4
@author: Chandranshu
104 ashish 5
'''
2536 chandransh 6
 
4369 rajveer 7
from datetime import date, timedelta
2536 chandransh 8
from elixir import *
5944 mandeep.dh 9
from random import randrange
3499 mandeep.dh 10
from reportlab.lib.units import inch
2536 chandransh 11
from reportlab.pdfgen.canvas import Canvas
12
from reportlab.rl_config import defaultPageSize
5944 mandeep.dh 13
from shop2020.clients.AlertClient import AlertClient
3499 mandeep.dh 14
from shop2020.clients.CatalogClient import CatalogClient
15
from shop2020.clients.HelperClient import HelperClient
5944 mandeep.dh 16
from shop2020.clients.InventoryClient import InventoryClient
3499 mandeep.dh 17
from shop2020.clients.LogisticsClient import LogisticsClient
2747 chandransh 18
from shop2020.clients.PaymentClient import PaymentClient
3499 mandeep.dh 19
from shop2020.clients.UserClient import UserClient
20
from shop2020.clients.WarehouseClient import WarehouseClient
21
from shop2020.model.v1 import order
6048 rajveer 22
from shop2020.model.v1.order.impl import DataService, RechargeService
3499 mandeep.dh 23
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem, \
4435 mandeep.dh 24
    Order, BatchNoGenerator, InvoiceIDGenerator, TransactionRequiringExtraProcessing, \
5348 anupam.sin 25
    OrderInventory, Alert, PaymentSettlement, EBSSettlementSummary, \
5527 anupam.sin 26
    CodVerificationAgent, Attribute, RechargeVoucherTracker
6000 mandeep.dh 27
from shop2020.model.v1.order.impl.model.MobileRechargeOrder import \
28
    MobileRechargeOrder
2687 chandransh 29
from shop2020.model.v1.order.impl.model.ReturnOrder import ReturnOrder
5944 mandeep.dh 30
from shop2020.thriftpy.alert.ttypes import MonitoredEntity, EntityType
5527 anupam.sin 31
from shop2020.thriftpy.logistics.ttypes import DeliveryType, PickUpType
6000 mandeep.dh 32
from shop2020.thriftpy.model.v1.catalog.ttypes import ItemType
5944 mandeep.dh 33
from shop2020.thriftpy.model.v1.inventory.ttypes import BillingType, \
34
    InventoryServiceException, WarehouseType, InventoryType
4435 mandeep.dh 35
from shop2020.thriftpy.model.v1.order.ttypes import TransactionServiceException, \
36
    TransactionStatus, OrderStatus, DelayReason, ExtraTransactionProcessingType, \
6031 rajveer 37
    HotspotAction, TimeoutSummary, OrderStatusGroups, OrderType,\
6289 anupam.sin 38
    RechargeOrderStatus, RechargeType, RechargeStatistics, DeviceNumberInfo
5944 mandeep.dh 39
from shop2020.thriftpy.model.v1.user.ttypes import VoucherType
4421 mandeep.dh 40
from shop2020.thriftpy.payments.ttypes import PaymentException
5110 mandeep.dh 41
from shop2020.thriftpy.warehouse.ttypes import ScanType, \
42
    WarehouseServiceException
6000 mandeep.dh 43
from shop2020.utils.EmailAttachmentSender import mail, get_attachment_part
855 rajveer 44
from shop2020.utils.Utils import to_py_date, to_java_date
4008 mandeep.dh 45
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
3499 mandeep.dh 46
from sqlalchemy.sql import func
6000 mandeep.dh 47
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct
3499 mandeep.dh 48
from string import Template
49
from textwrap import dedent
50
import datetime
5944 mandeep.dh 51
import httplib
3499 mandeep.dh 52
import logging
53
import os
4421 mandeep.dh 54
import sys
4435 mandeep.dh 55
import time
4421 mandeep.dh 56
import traceback
5806 rajveer 57
import urllib
5966 rajveer 58
from shop2020.config.client.ConfigClient import ConfigClient
6177 anupam.sin 59
from shop2020.model.v1.order.impl.model.RechargePlan import RechargePlan
6031 rajveer 60
from shop2020.model.v1.order.impl.model.RechargeOrder import RechargeOrder
61
from shop2020.model.v1.order.impl.model.UserWallet import UserWallet
62
from shop2020.model.v1.order.impl.model.UserWalletHistory import UserWalletHistory
6048 rajveer 63
from shop2020.model.v1.order.impl.model.ServiceProvider import ServiceProvider
64
from shop2020.model.v1.order.impl.model.DTHRechargeOrder import DTHRechargeOrder
6289 anupam.sin 65
from shop2020.model.v1.order.impl.model.TelecomCircle import TelecomCircle
66
from shop2020.model.v1.order.impl.model.RechargeDenomination import RechargeDenomination
6281 rajveer 67
from shop2020.clients.PromotionClient import PromotionClient
5944 mandeep.dh 68
 
3499 mandeep.dh 69
logging.basicConfig(level=logging.DEBUG)
104 ashish 70
 
5966 rajveer 71
sourceId = int(ConfigClient().get_property("sourceid"))
72
mail_user = 'cnc.center@shop2020.in'
73
mail_password = '5h0p2o2o'
74
help_user = 'help@shop2020.in'
75
help_password = '5h0p2o2o'
6029 rajveer 76
source_url = 'www.saholic.com'
77
source_name = 'Saholic'
3499 mandeep.dh 78
 
4763 rajveer 79
PREPAID_SHIPPING_CUTOFF_TIME = 15
4019 chandransh 80
COD_SHIPPING_CUTOFF_TIME = 12
3499 mandeep.dh 81
 
2819 chandransh 82
PAGE_HEIGHT=defaultPageSize[1]
83
PAGE_WIDTH=defaultPageSize[0]
84
 
4763 rajveer 85
billedOrdersColorMap = {}
86
 
3499 mandeep.dh 87
ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT = {
4873 mandeep.dh 88
        OrderStatus.RTO_RESHIPPED    :  3,
89
        OrderStatus.RTO_IN_TRANSIT   : -5,
90
        OrderStatus.DELIVERY_SUCCESS :  1,
91
        OrderStatus.DOA_CERT_INVALID : -5
3499 mandeep.dh 92
}
93
 
5783 rajveer 94
delhi_pincodes = ['110001','110002','110003','110004','110005','110006','110007','110008','110009','110010','110011','110012','110013','110014','110015',\
95
                '110016','110017','110018','110019','110020','110021','110022','110023','110024','110025','110026','110027','110028','110029','110030',\
96
                '110031','110032','110033','110034','110035','110037','110038','110041','110042','110044','110045','110046','110047','110048','110049',\
97
                '110051','110052','110053','110054','110055','110056','110057','110058','110059','110060','110061','110062','110063','110064','110065',\
98
                '110066','110067','110068','110070','110071','110074','110075','110076','110078','110081','110082','110083','110084','110085','110086',\
99
                '110087','110088','110089','110091','110092','110093','110094','110095','110096','110101','110103','110104','110105','110106','110107',\
100
                '110108','110109','110110','110112','110113','110114','110115','110116','110117','110118','110119','110120','110122','110124','110125',\
101
                '110301','110302','110501','110502','110503','110504','110505','110510','110511','110512','110601','110602','110603','110604','110605',\
102
                '110606','110607','110608','110609']
103
 
104 ashish 104
def get_new_transaction():
105
    transaction = Transaction()
106
    transaction.createdOn = datetime.datetime.now()
738 chandransh 107
    transaction.status = TransactionStatus.INIT
104 ashish 108
    transaction.status_message = "New transaction"
483 rajveer 109
    return transaction
110
 
111
def create_order(t_order):
112
    order = Order()
113
    if t_order.warehouse_id:
114
        order.warehouse_id = t_order.warehouse_id
509 rajveer 115
    if t_order.logistics_provider_id:    
483 rajveer 116
        order.logistics_provider_id = t_order.logistics_provider_id
117
        order.airwaybill_no = t_order.airwaybill_no
118
        order.tracking_id = t_order.tracking_id
4009 chandransh 119
    if t_order.expected_shipping_time:
4019 chandransh 120
        order.expected_shipping_time = to_py_date(t_order.expected_shipping_time).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 121
        order.promised_shipping_time = order.expected_shipping_time
4009 chandransh 122
    if t_order.expected_delivery_time:
483 rajveer 123
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
4102 chandransh 124
        order.promised_delivery_time = order.expected_delivery_time
483 rajveer 125
    if t_order.customer_id:    
126
        order.customer_id = t_order.customer_id
127
        order.customer_name = t_order.customer_name
860 rajveer 128
        order.customer_city = t_order.customer_city
129
        order.customer_state = t_order.customer_state
483 rajveer 130
        order.customer_mobilenumber = t_order.customer_mobilenumber
131
        order.customer_pincode = t_order.customer_pincode
738 chandransh 132
        order.customer_address1 = t_order.customer_address1
133
        order.customer_address2 = t_order.customer_address2
483 rajveer 134
        order.customer_email = t_order.customer_email
135
    #new status and status description to be added    
716 rajveer 136
    order.status = t_order.status  
483 rajveer 137
    order.statusDescription = t_order.statusDescription
138
    order.total_amount = t_order.total_amount
139
    order.total_weight = t_order.total_weight
140
    if t_order.created_timestamp:
141
        order.created_timestamp = to_py_date(t_order.created_timestamp)
142
    else:
685 chandransh 143
        order.created_timestamp = datetime.datetime.now()
5555 rajveer 144
    order.pickupStoreId = t_order.pickupStoreId
483 rajveer 145
    return order
146
 
147
def create_transaction(t_transaction):
148
    t_orders = t_transaction.orders
149
    if not t_orders:
150
        raise TransactionServiceException(101, "Orders missing from the transaction")
151
    transaction = get_new_transaction()
152
    transaction.customer_id = t_transaction.customer_id 
153
    transaction.shopping_cart_id = t_transaction.shoppingCartid
2219 varun.gupt 154
    transaction.coupon_code = t_transaction.coupon_code
2815 vikas 155
    transaction.session_source = t_transaction.sessionSource
156
    transaction.session_start_time = to_py_date(t_transaction.sessionStartTime)
3858 vikas 157
    transaction.first_source = t_transaction.firstSource
158
    transaction.first_source_start_time = to_py_date(t_transaction.firstSourceTime)
483 rajveer 159
 
160
    for t_order in t_orders:
161
        order = create_order(t_order)
162
        order.transaction = transaction 
163
        for line_item in t_order.lineitems:
164
            litem = LineItem()
716 rajveer 165
            litem.item_id = line_item.item_id
963 chandransh 166
            litem.productGroup = line_item.productGroup
483 rajveer 167
            litem.brand = line_item.brand
168
            if line_item.model_number:
169
                litem.model_number = line_item.model_number
170
            if line_item.model_name:    
171
                litem.model_name = line_item.model_name
908 chandransh 172
            if line_item.color:
173
                litem.color = line_item.color
483 rajveer 174
            if line_item.extra_info:
175
                litem.extra_info = line_item.extra_info
176
            litem.quantity = line_item.quantity
177
            litem.unit_price = line_item.unit_price
178
            litem.unit_weight = line_item.unit_weight
179
            litem.total_price = line_item.total_price
180
            litem.total_weight = line_item.total_weight
4283 anupam.sin 181
            '''litem.transfer_price = line_item.transfer_price'''
4172 rajveer 182
            litem.dealText = line_item.dealText
4295 varun.gupt 183
            litem.warranty_expiry_timestamp = to_py_date(line_item.warrantry_expiry_timestamp)
1976 varun.gupt 184
 
483 rajveer 185
            """
186
            if line_item.addedOn:
187
                litem.added_on = to_py_date(line_item.addedOn)
188
            else:
189
                litem.added_on = datetime.datetime.now()
190
            """
191
            litem.order = order
192
    session.commit()
193
    return transaction.id
194
 
195
def get_transaction(transaction_id):
196
    transaction = Transaction.get_by(id=transaction_id)
197
    if not transaction:
198
        raise TransactionServiceException(108, "no such transaction")
199
 
200
    return transaction
201
 
202
def get_transactions_for_customer(customer_id, from_date, to_date, status):
203
    if not customer_id:
204
        raise TransactionServiceException(101, "bad customer id")
205
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 206
    if status is not None:
483 rajveer 207
        query = query.filter(Transaction.status == status)
208
    if from_date:
209
        query = query.filter(Transaction.createdOn >from_date)
210
    if to_date:
211
        query = query.filter(Transaction.createdOn < to_date)
212
    return query.all()
213
 
214
def get_transactions_for_shopping_cart_id(shopping_cart_id):
215
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
216
    return transactions
217
 
218
def get_transaction_status(transaction_id):
219
    if not transaction_id:
220
        raise TransactionServiceException(101, "bad transaction id")
221
 
222
    transaction = get_transaction(transaction_id)
223
 
224
    return transaction.status
225
 
5527 anupam.sin 226
def change_transaction_status(transaction_id, new_status, description, pickUp, orderType):
483 rajveer 227
    transaction = get_transaction(transaction_id)
228
    transaction.status = new_status
229
    transaction.status_message = description
5783 rajveer 230
    ## Assign runner in case of delhi pincodes
5784 rajveer 231
    if transaction.orders[0].pickupStoreId:
232
        logistics_client = LogisticsClient().get_client() 
233
        store = logistics_client.getPickupStore(transaction.orders[0].pickupStoreId)
234
        if delhi_pincodes.__contains__(store.pin):
5793 rajveer 235
            pickUp = PickUpType.RUNNER  
5783 rajveer 236
 
690 chandransh 237
    if new_status == TransactionStatus.FAILED:
238
        for order in transaction.orders:
239
            order.status = OrderStatus.PAYMENT_FAILED
2339 chandransh 240
            order.statusDescription = "Payment Failed"
4247 rajveer 241
    elif new_status == TransactionStatus.AUTHORIZED or new_status == TransactionStatus.FLAGGED:
690 chandransh 242
        for order in transaction.orders:
4247 rajveer 243
            if new_status == TransactionStatus.AUTHORIZED:
244
                order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
245
                order.statusDescription = "Submitted to warehouse"
246
            elif new_status == TransactionStatus.FLAGGED:
247
                order.status = OrderStatus.PAYMENT_FLAGGED
248
                order.statusDescription = "Payment flagged by gateway"
3092 chandransh 249
            order.cod = False
5527 anupam.sin 250
            order.orderType = orderType
743 rajveer 251
            #After we got payment success, we will set logistics info also 
252
            logistics_client = LogisticsClient().get_client()
253
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 254
            item_id = order.lineitems[0].item_id
5767 rajveer 255
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID, pickUp)
743 rajveer 256
 
1730 ankur.sing 257
            current_time = datetime.datetime.now()
258
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 259
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
5110 mandeep.dh 260
 
743 rajveer 261
            order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 262
            order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
743 rajveer 263
            order.logistics_provider_id = logistics_info.providerId
264
            order.airwaybill_no = logistics_info.airway_billno
265
            order.tracking_id = order.airwaybill_no
4019 chandransh 266
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 267
            order.promised_shipping_time = order.expected_shipping_time
5165 rajveer 268
            order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3986 chandransh 269
            order.promised_delivery_time = order.expected_delivery_time 
871 chandransh 270
 
5944 mandeep.dh 271
            inventory_client = InventoryClient().get_client()
5966 rajveer 272
            inventory_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, sourceId, order.id, to_java_date(order.created_timestamp), to_java_date(order.promised_shipping_time), order.lineitems[0].quantity)
1351 varun.gupt 273
 
4316 anupam.sin 274
            try:
5944 mandeep.dh 275
                item_pricing = inventory_client.getItemPricing(item_id, -1)
4316 anupam.sin 276
                order.lineitems[0].transfer_price = item_pricing.transferPrice
277
            except:
278
                print "Not able to get transfer price. Skipping"
5944 mandeep.dh 279
 
280
            catalog_client = CatalogClient().get_client() 
5508 rajveer 281
            voucherAmount = catalog_client.getVoucherAmount(item_id, VoucherType.SPICEDECK_MOBILE)
282
            if voucherAmount:
5514 rajveer 283
                __create_recharge_voucher_tracker(order, voucherAmount, VoucherType.SPICEDECK_MOBILE)
5508 rajveer 284
 
3064 chandransh 285
    elif new_status == TransactionStatus.COD_IN_PROCESS:
286
        for order in transaction.orders:
4662 rajveer 287
            order.status = OrderStatus.COD_VERIFICATION_PENDING
3064 chandransh 288
            order.statusDescription = "Verification Pending"
289
            order.cod = True
5527 anupam.sin 290
            order.orderType = orderType
3064 chandransh 291
            #After we got payment success, we will set logistics info also 
292
            logistics_client = LogisticsClient().get_client()
293
            #FIXME line item is only one now. If multiple will come, need to fix.
294
            item_id = order.lineitems[0].item_id
5555 rajveer 295
            if order.pickupStoreId:
5885 mandeep.dh 296
                # Need to send prepaid awb number for store pick up orders
297
                logistics_info = logistics_client.getLogisticsEstimation(item_id, order.customer_pincode, DeliveryType.COD)
298
                prepaid_logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.PREPAID, pickUp)
299
                logistics_info.airway_billno = prepaid_logistics_info.airway_billno
300
                logistics_info.providerId = prepaid_logistics_info.providerId
5555 rajveer 301
            else:
5767 rajveer 302
                logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id, DeliveryType.COD, pickUp)
5885 mandeep.dh 303
 
3064 chandransh 304
            current_time = datetime.datetime.now()
305
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
4009 chandransh 306
            logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
3064 chandransh 307
 
308
            order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 309
            order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
3064 chandransh 310
            order.logistics_provider_id = logistics_info.providerId
311
            order.airwaybill_no = logistics_info.airway_billno
312
            order.tracking_id = order.airwaybill_no
4019 chandransh 313
            order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4102 chandransh 314
            order.promised_shipping_time = order.expected_shipping_time
5165 rajveer 315
            order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3986 chandransh 316
            order.promised_delivery_time = order.expected_delivery_time
3064 chandransh 317
 
5944 mandeep.dh 318
            inventory_client = InventoryClient().get_client()
5966 rajveer 319
            inventory_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, sourceId, order.id, to_java_date(order.created_timestamp), to_java_date(order.promised_shipping_time), order.lineitems[0].quantity)
3064 chandransh 320
 
4316 anupam.sin 321
            try:
5944 mandeep.dh 322
                item_pricing = inventory_client.getItemPricing(item_id, -1)
4316 anupam.sin 323
                order.lineitems[0].transfer_price = item_pricing.transferPrice        
324
            except:
325
                print "Not able to get transfer price. Skipping"
5508 rajveer 326
 
5944 mandeep.dh 327
            catalog_client = CatalogClient().get_client()
5508 rajveer 328
            voucherAmount = catalog_client.getVoucherAmount(item_id, VoucherType.SPICEDECK_MOBILE)
329
            if voucherAmount:
5514 rajveer 330
                __create_recharge_voucher_tracker(order, voucherAmount, VoucherType.SPICEDECK_MOBILE)
483 rajveer 331
    session.commit()
3499 mandeep.dh 332
 
3530 mandeep.dh 333
    try:
334
        if new_status == TransactionStatus.COD_IN_PROCESS:
4008 mandeep.dh 335
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
336
            transaction_requiring_extra_processing.category = 'COD_VERIFICATION'
337
            transaction_requiring_extra_processing.transaction_id = transaction_id
338
            session.commit()
4247 rajveer 339
        elif new_status == TransactionStatus.FLAGGED:
340
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
341
            transaction_requiring_extra_processing.category = 'PAYMENT_FLAGGED'
342
            transaction_requiring_extra_processing.transaction_id = transaction_id
343
            session.commit()
3530 mandeep.dh 344
    except Exception as e:
4065 mandeep.dh 345
        print "Error inserting transaction Id: " + str(transaction_id) + " due to " + str(e)
3499 mandeep.dh 346
 
483 rajveer 347
    return True
348
 
5514 rajveer 349
def __create_recharge_voucher_tracker(order, amount, voucherType):
5508 rajveer 350
    rvt = RechargeVoucherTracker()
351
    rvt.order = order
352
    rvt.amount = amount
353
    rvt.voucherIssued = False
5514 rajveer 354
    rvt.voucherType = voucherType
5508 rajveer 355
 
3994 chandransh 356
def __get_holidays(start_time=0L, to_time=-1L):
357
    '''
358
    Get the list of all public holidays since start time including the
359
    day of start time if it's a holiday
360
    '''
361
    midnightTime = start_time.replace(hour=0, minute=0, second=0, microsecond=0)
1730 ankur.sing 362
    fromDate = to_java_date(midnightTime)
363
    logistics_client = LogisticsClient().get_client()
3994 chandransh 364
    #TODO: This list should be cached after the first call.
365
    #Calling logistics server is also unnecessary.
366
    holidays = logistics_client.getHolidays(fromDate, to_time)
367
    holidays = [to_py_date(holiday).date() for holiday in holidays]
368
    return holidays
369
 
370
def adjust_delivery_time(start_time, delivery_days):
371
    '''
372
    Returns the actual no. of days which will pass while 'delivery_days'
373
    no. of business days will pass since 'order_time'. 
374
    '''
375
    start_date = start_time.date()
376
    end_date = start_date + datetime.timedelta(days = delivery_days)
377
    holidays = __get_holidays(start_time)
1730 ankur.sing 378
 
3994 chandransh 379
    while start_date <= end_date:
380
        if start_date.weekday() == 6 or start_date in holidays:
1730 ankur.sing 381
            delivery_days = delivery_days + 1
3994 chandransh 382
            end_date = end_date + datetime.timedelta(days = 1)
4088 chandransh 383
        start_date = start_date + datetime.timedelta(days = 1)
3994 chandransh 384
 
1730 ankur.sing 385
    return delivery_days
386
 
1398 varun.gupt 387
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 388
    transaction = get_transaction(transaction_id)
5793 rajveer 389
    customer_name = "" 
1262 varun.gupt 390
    html_header = """
391
<html>
392
<body>
393
<div>
394
    <p>
5793 rajveer 395
        Hello $customer_name,<br /><br />
1742 rajveer 396
        Thanks for placing order with us. Following are the details of your order:
1262 varun.gupt 397
    </p>
398
    <div>
399
        Order Date: $order_date
1569 varun.gupt 400
    </div>
1262 varun.gupt 401
    <div>
402
        <table>
5879 rajveer 403
        <tr><td colspan="6"><hr /></td></tr>
404
        <tr><td colspan="6" align="left"><b>Order Details</b></td></tr>
405
        <tr><td colspan="6"><hr /></td></tr>
1262 varun.gupt 406
        <tr>
2050 varun.gupt 407
            <th width="100">Order No.</th>
408
            <th>Product</th>
5879 rajveer 409
            <th width="100">Estimated Delivery Date</th>
2050 varun.gupt 410
            <th width="100">Quantity</th>
411
            <th width="100">Unit Price</th>
412
            <th width="100">Amount</th>
1262 varun.gupt 413
        </tr>
414
    """
1398 varun.gupt 415
    user_email = ""
1262 varun.gupt 416
    total_amount = 0.0
417
    html_table = ""
1569 varun.gupt 418
    order_date = datetime.datetime.now()
5676 rajveer 419
 
420
    orders = transaction.orders
421
    html_pickup_text = ""
422
    random_text = ""
5697 rajveer 423
    if orders[0].pickupStoreId:
5793 rajveer 424
        random_text = str(randrange(100000, 999999)) 
5676 rajveer 425
 
426
    for order in orders:
5793 rajveer 427
        customer_name = order.customer_name
1262 varun.gupt 428
        order_date = order.created_timestamp
1398 varun.gupt 429
        user_email = order.customer_email
1569 varun.gupt 430
        html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
5676 rajveer 431
 
5879 rajveer 432
        sdt = datetime.datetime.strptime(str(orders[0].expected_delivery_time), "%Y-%m-%d %H:%M:%S")
433
        store_delivery_date = sdt.strftime("%d %B %Y")
434
 
5676 rajveer 435
        if order.pickupStoreId:
436
            attribute = Attribute()
437
            attribute.orderId = order.id
438
            attribute.name = "SECRET_CODE"
439
            attribute.value = random_text
440
            session.commit()
1262 varun.gupt 441
 
442
        for lineitem in order.lineitems:
2050 varun.gupt 443
            lineitem_total_price = round(lineitem.total_price, 2)
444
 
1276 chandransh 445
            html_tr += "<td>" + str(lineitem) + "</td>"
5879 rajveer 446
            html_tr += "<td align='center'>" + store_delivery_date + "</td>"
2050 varun.gupt 447
            html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
448
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
449
            html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
450
            total_amount += lineitem_total_price
1262 varun.gupt 451
            html_table += html_tr
2050 varun.gupt 452
 
1262 varun.gupt 453
    html_footer = """
5879 rajveer 454
        <tr><td colspan=6>&nbsp;</td></tr>
455
        <tr><td colspan=6><hr /></td></tr>
1262 varun.gupt 456
        <tr>
5879 rajveer 457
            <td colspan=5>Total Amount</td>
2050 varun.gupt 458
            <td> Rs. $total_amount</td>
1262 varun.gupt 459
        </tr>
460
        </table>
1569 varun.gupt 461
    </div>
5676 rajveer 462
    """
5793 rajveer 463
 
464
    store_address = ""
465
    if orders[0].pickupStoreId:
466
        store = LogisticsClient().get_client().getPickupStore(orders[0].pickupStoreId)
467
        store_address = __get_store_address_html(store)
468
 
469
        html_pickup_text = html_pickup_text + """
470
        <h3>Steps to Pickup In Store</h3>
5879 rajveer 471
        1) You will receive a confirmation email from us when your product(s) reaches the store. Once you receive the same, please visit the following store selected by you.<br>
5793 rajveer 472
        <br><i>$store_address</i><br>
473
        """
474
 
475
        if orders[0].cod:
476
            html_pickup_text = html_pickup_text + """
5879 rajveer 477
            2) Pay Rs. $total_amount, present a valid Photo Identity Proof* and use your Secret Code <b><i>$secret_code</i></b> to claim your Product(s).<br><br>
5793 rajveer 478
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
479
            <br>
6029 rajveer 480
            In case you have any questions please visit <a href="$source_url/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="$source_url/contact-us">$source_url/contact-us</a>
5793 rajveer 481
            </br><hr />
482
            """
483
        else:
484
            html_pickup_text = html_pickup_text + """
5879 rajveer 485
            2) Present a valid Photo Identity Proof* and use your Secret Code <b><i>$secret_code</i></b> to claim your Product(s).<br><br>
5793 rajveer 486
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
487
            <br>
6029 rajveer 488
            In case you have any questions please visit <a href="$source_url/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="$source_url/contact-us">$source_url/contact-us</a>
5793 rajveer 489
            </br><hr />
490
            """
491
 
5676 rajveer 492
    html_footer = html_footer + html_pickup_text + """
1262 varun.gupt 493
    <p>
494
        Best Wishes,<br />
6029 rajveer 495
        $source_name Team
1262 varun.gupt 496
    </p>
497
</div>
498
</body>
499
</html>
500
    """
1398 varun.gupt 501
 
1569 varun.gupt 502
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 503
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
5793 rajveer 504
 
505
    sdt = datetime.datetime.strptime(str(orders[0].expected_delivery_time), "%Y-%m-%d %H:%M:%S")
506
    store_delivery_date = sdt.strftime("%A, %d %B %Y")
507
 
6029 rajveer 508
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, source_url = source_url))
509
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount, secret_code = random_text, store_address = store_address, store_delivery_date = store_delivery_date, source_url = source_url, source_name = source_name))
1565 varun.gupt 510
 
1351 varun.gupt 511
    try:
512
        helper_client = HelperClient().get_client()
6280 rajveer 513
        helper_client.saveUserEmailForSending([user_email], "", source_name + " - Order Details", email_header + html_table + email_footer, str(transaction_id), "TransactionInfo", [], [])
5866 rajveer 514
 
1351 varun.gupt 515
        return True
516
    except Exception as e:
517
        print e
518
        return False
1262 varun.gupt 519
 
5802 rajveer 520
def enqueue_received_at_store_email(order):
521
    html_header = """
522
    <html>
523
    <body>
524
    <div>
525
        <p>
526
            Hello $customer_name,<br /><br />
527
            Your Product has reached the Store selected by you and is available for pickup. Please pick up your product on or before $order_expiry_date. Following are the details of your order and steps to pickup the same:
528
        </p>
529
        <div>
530
            Order Date: $order_date
531
        </div>
532
        <div>
533
            <table>
534
            <tr><td colspan="5"><hr /></td></tr>
535
            <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
536
            <tr><td colspan="5"><hr /></td></tr>
537
            <tr>
538
                <th width="100">Order No.</th>
539
                <th>Product</th>
540
                <th width="100">Quantity</th>
541
                <th width="100">Unit Price</th>
542
                <th width="100">Amount</th>
543
            </tr>
544
    """
545
    total_amount = 0.0
546
    html_table = ""
547
 
548
    html_pickup_text = ""
549
    random_text = __get_secret_code(order.id)
550
 
551
    customer_name = order.customer_name
552
    order_date = order.created_timestamp
553
    user_email = order.customer_email
554
    html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
555
 
556
    for lineitem in order.lineitems:
557
        lineitem_total_price = round(lineitem.total_price, 2)
558
 
559
        html_tr += "<td>" + str(lineitem) + "</td>"
560
        html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
561
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
562
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
563
        total_amount += lineitem_total_price
564
        html_table += html_tr
565
 
566
    html_footer = """
567
        <tr><td colspan=5>&nbsp;</td></tr>
568
        <tr><td colspan=5><hr /></td></tr>
569
        <tr>
570
            <td colspan=4>Total Amount</td>
571
            <td> Rs. $total_amount</td>
572
        </tr>
573
        </table>
574
    </div>
575
    """
576
 
577
    store_address = ""
578
    if order.pickupStoreId:
579
        store = LogisticsClient().get_client().getPickupStore(order.pickupStoreId)
580
        store_address = __get_store_address_html(store)
581
 
582
        html_pickup_text = html_pickup_text + """
583
        <h3>Steps to Pickup In Store</h3>
584
        1) Please visit the following store selected by you on or before $order_expiry_date<br>
585
        <br><i>$store_address</i><br>
586
        """
587
 
588
        if order.cod:
589
            html_pickup_text = html_pickup_text + """
590
            2) Pay Rs. $total_amount, present a valid Photo Identity Proof* and quote your Secret Code <b><i>$secret_code</i></b> to claim your Product.<br><br>
591
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
592
            <br>
6029 rajveer 593
            In case you have any questions please visit <a href="$source_url/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="$source_url/contact-us">$source_url/contact-us</a>
5802 rajveer 594
            </br><hr />
595
            """
596
        else:
597
            html_pickup_text = html_pickup_text + """
598
            2) Present a valid Photo Identity Proof* and use your Secret Code <b><i>$secret_code</i></b> to claim your Product(s).<br><br>
599
            *Valid Photo Identity Proof are Driving License, Passport, PAN Card, Voter ID, Company Issued ID Card, College issued Student ID Card Or any other Government approved Photo Id.<br>
600
            <br>
6029 rajveer 601
            In case you have any questions please visit <a href="$source_url/static/buy-online-and-pickup-in-store">Details on Pickup in Store</a>. If you still have more questions feel free to contact us 24/7 via <a href="$source_url/contact-us">$source_url/contact-us</a>
5802 rajveer 602
            </br><hr />
603
            """
604
 
605
        html_footer = html_footer + html_pickup_text + """
606
        <p>
607
            Best Wishes,<br />
6029 rajveer 608
            $source_name Team
5802 rajveer 609
        </p>
610
        </div>
611
        </body>
612
        </html>
613
        """
614
 
615
    subject = "Your order for " + str(order.lineitems[0]) + " is ready for Pickup in Store"
616
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
617
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
618
 
619
    oetd = datetime.datetime.now() + datetime.timedelta(days=4)
620
    formated_order_expiry_date = oetd.strftime("%A, %d %B %Y")
621
 
622
 
6029 rajveer 623
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, order_expiry_date = formated_order_expiry_date, source_url = source_url, source_name = source_name))
624
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount, secret_code = random_text, store_address = store_address, order_expiry_date = formated_order_expiry_date, source_url = source_url, source_name = source_name))
5802 rajveer 625
 
626
    try:
5812 rajveer 627
        helper_client = HelperClient(host_key = "helper_service_server_host_prod").get_client()
6280 rajveer 628
        helper_client.saveUserEmailForSending([user_email], "", subject, email_header + html_table + email_footer, str(order.id), "ReceivedAtStore", [], [])
5802 rajveer 629
        return True
630
    except Exception as e:
631
        print e
632
        return False
633
 
5966 rajveer 634
def enqueue_delivery_success_mail(order):
5807 rajveer 635
    html_header = """
636
    <html>
637
    <body>
638
    <div>
639
        <p>
640
            Dear $customer_name,<br /><br />
641
    """
642
 
643
    if order.pickupStoreId:
644
        pickup_text = "Pickup Date: " + order.delivery_timestamp.strftime("%A, %d. %B %Y %I:%M%p")
645
        thank_you_html = """
646
        Thank you for shopping with us and picking up your order in Store. Please do join us at our <a href="http://www.facebook.com/mysaholic">Facebook Page</a>, and share your experience with other shoppers.<br><br>
647
 
6029 rajveer 648
        Following are the details of your order for which the pickup has happened. If you have not picked up this product please <a href="$source_url/contact-us" target="_blank">contact us</a> immediately.<br>
5807 rajveer 649
        """
650
    else:
651
        pickup_text = ""
652
        thank_you_html = """
653
        Thank you for shopping with us. Please do join us at our <a href="http://www.facebook.com/mysaholic">Facebook Page</a>, and share your experience with other shoppers. Following are the details of your order.<br>
654
        """ 
655
 
656
    html_header = html_header + thank_you_html + """        
657
        </p>
658
        <div>
659
            Order Date: $order_date <br>
660
            $pickup_text
661
        </div>
662
        <div>
663
            <table>
664
            <tr><td colspan="5"><hr /></td></tr>
665
            <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
666
            <tr><td colspan="5"><hr /></td></tr>
667
            <tr>
668
                <th width="100">Order No.</th>
669
                <th>Product</th>
670
                <th width="100">Quantity</th>
671
                <th width="100">Unit Price</th>
672
                <th width="100">Amount</th>
673
            </tr>
674
    """
675
    total_amount = 0.0
676
    html_table = ""
5802 rajveer 677
 
5807 rajveer 678
    customer_name = order.customer_name
679
    order_date = order.created_timestamp
680
    user_email = order.customer_email
681
    html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
682
 
683
    for lineitem in order.lineitems:
684
        lineitem_total_price = round(lineitem.total_price, 2)
685
 
686
        html_tr += "<td>" + str(lineitem) + "</td>"
687
        html_tr += "<td align='center'>" + ("%.0f" % lineitem.quantity) + "</td>"
688
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem.unit_price) + "</td>"
689
        html_tr += "<td align='center'> Rs. " + ("%.2f" % lineitem_total_price) + "</td></tr>"
690
        total_amount += lineitem_total_price
691
        html_table += html_tr
692
 
693
    html_footer = """
694
        <tr><td colspan=5>&nbsp;</td></tr>
695
        <tr><td colspan=5><hr /></td></tr>
696
        <tr>
697
            <td colspan=4>Total Amount</td>
698
            <td> Rs. $total_amount</td>
699
        </tr>
700
        </table>
701
    </div>
702
    <p>
703
        Best Wishes,<br />
6029 rajveer 704
        $source_name Team
5807 rajveer 705
    </p>
706
    </div>
707
    </body>
708
    </html>
709
    """
710
 
711
    subject = "Your order for " + str(order.lineitems[0]) + " is now complete"
712
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
713
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
714
 
715
 
6029 rajveer 716
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date, customer_name = customer_name, pickup_text = pickup_text, source_url = source_url))
717
    email_footer = Template(html_footer).substitute(dict(total_amount = "%.2f" % total_amount, source_name = source_name))
5807 rajveer 718
 
719
    try:
5812 rajveer 720
        helper_client = HelperClient(host_key = "helper_service_server_host_prod").get_client()
6280 rajveer 721
        helper_client.saveUserEmailForSending([user_email], "", subject, email_header + html_table + email_footer, str(order.id), "DeliverySuccess", [], [])
5807 rajveer 722
        return True
723
    except Exception as e:
724
        print e
725
        return False
726
 
5802 rajveer 727
def __get_secret_code(order_id):
5855 rajveer 728
    return get_order_attribute_value(order_id, 'SECRET_CODE')
5806 rajveer 729
 
5833 rajveer 730
def get_order_attribute_value(order_id, attribute_name):
5808 rajveer 731
    existingAttribute = Attribute.query.filter(Attribute.orderId == order_id).filter(Attribute.name == attribute_name).first()
732
    if existingAttribute:
733
        return existingAttribute.value
5802 rajveer 734
    return ""
5806 rajveer 735
 
6019 rajveer 736
def change_jacket_number(order_id, jacket_number):
737
    order = get_order(order_id)
738
    if order.status == OrderStatus.BILLED:
739
        order.jacket_number = jacket_number
6047 rajveer 740
        session.commit()
6019 rajveer 741
        return True
742
    return False
743
 
744
def mark_order_as_rto_in_transit(order_id):
745
    order = get_order(order_id)
6032 rajveer 746
    if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.DELIVERED_AT_STORE, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DELIVERY_SUCCESS]:
6019 rajveer 747
        return False
748
    order.status = OrderStatus.RTO_IN_TRANSIT
749
    order.delivery_timestamp = datetime.datetime.now()
750
    order.statusDescription = "Order Returned to Origin:"
751
    update_trust_level(order)
6032 rajveer 752
    session.commit()
6019 rajveer 753
    return True
754
 
483 rajveer 755
def get_order(order_id):
756
    order = Order.get_by(id=order_id)
757
    if not order:
758
        raise TransactionServiceException(108, "no such order")
759
 
760
    return order
761
 
4999 phani.kuma 762
def get_order_list(order_ids):
763
    orders = Order.query.filter(Order.id.in_(tuple(order_ids)))
764
    return orders
765
 
5386 phani.kuma 766
def get_order_list_for_vendor(order_ids, vendor_id):
767
    if vendor_id == -1:
768
        return get_order_list(order_ids)
769
    else:
770
        orders = Order.query.filter_by(vendorId = vendor_id).filter(Order.id.in_(tuple(order_ids)))
771
        return orders
772
 
3014 chandransh 773
def get_orders_for_customer(customer_id, from_date, to_date, statuses):
483 rajveer 774
    if not customer_id:
775
        raise TransactionServiceException(101, "bad customer id")
776
    query = Order.query.filter(Order.customer_id == customer_id)
3014 chandransh 777
    if statuses:
778
        query = query.filter(Order.status.in_(tuple(statuses)))
483 rajveer 779
    if from_date:
780
        query = query.filter(Order.created_timestamp >from_date)
781
    if to_date:
782
        query = query.filter(Order.created_timestamp < to_date)
783
    return query.all()
784
 
1528 ankur.sing 785
def get_order_for_customer(order_id, customer_id):
786
    if not customer_id:
787
        raise TransactionServiceException(101, "bad customer id")
788
    order = get_order(order_id)
789
    if order.customer_id != customer_id:
790
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
791
    return order
792
 
4801 anupam.sin 793
def get_all_orders(statuses, from_date, to_date, warehouse_id):
794
    if not len(statuses):
795
        raise TransactionServiceException(101, "Status list is empty")
796
    query = Order.query.filter(Order.status.in_(statuses))
797
    if warehouse_id:
798
        query = query.filter(Order.warehouse_id == warehouse_id)
799
        #raise TransactionServiceException(101, "bad warehouse id")
483 rajveer 800
    if from_date:
801
        query = query.filter(Order.created_timestamp >from_date)
802
    if to_date:
803
        query = query.filter(Order.created_timestamp < to_date)
804
    return query.all()
805
 
4133 chandransh 806
def get_orders_in_batch(statuses=[], offset=0, limit=0, warehouse_id=None):
4296 rajveer 807
    query = Order.query
808
    if warehouse_id:
809
        query = query.filter(Order.warehouse_id == warehouse_id)
4133 chandransh 810
    if statuses:
811
        query = query.filter(Order.status.in_(statuses))
812
    query = query.offset(offset)
813
    if limit:
814
        query = query.limit(limit)
815
    return query.all()
816
 
817
def get_order_count(statuses=[], warehouse_id=None):
818
    if not warehouse_id:
819
        raise TransactionServiceException(101, "bad warehouse id")
820
    query = session.query(func.count(Order.id)).filter(Order.warehouse_id == warehouse_id)
821
    if statuses:
822
        query = query.filter(Order.status.in_(statuses))
823
    return query.scalar()
824
 
1382 varun.gupt 825
def get_returnable_orders_for_customer(customer_id, limit = None):
826
    if not customer_id:
827
        raise TransactionServiceException(101, "bad customer id")
828
 
829
    query = Order.query.filter(Order.customer_id == customer_id)
830
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
831
    query = query.filter(Order.status != OrderStatus.REJECTED)
832
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
833
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
834
    orders = query.all()
835
    order_ids = [order.id for order in orders]
836
    return order_ids
837
 
838
def get_cancellable_orders_for_customer(customer_id, limit = None):
839
    if not customer_id:
840
        raise TransactionServiceException(101, "bad customer id")
4815 phani.kuma 841
    cancellableOrderStatuses = OrderStatusGroups().codCancellable
1382 varun.gupt 842
    query = Order.query.filter(Order.customer_id == customer_id)
4815 phani.kuma 843
    query = query.filter(Order.status.in_(cancellableOrderStatuses))
1382 varun.gupt 844
    orders = query.all()
845
    return [order.id for order in orders]
846
 
995 varun.gupt 847
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
848
    if not warehouse_id:
849
        raise TransactionServiceException(101, "bad warehouse id")
850
 
851
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
852
 
853
    if status:
854
        query = query.filter(Order.status == status)
855
 
856
    if start_billing_date:
857
        query = query.filter(Order.billing_timestamp >= start_billing_date)
858
 
859
    if end_billing_date:
860
        query = query.filter(Order.billing_timestamp <= end_billing_date)
861
 
862
    return query.all()
863
 
3451 chandransh 864
def get_orders_by_shipping_date(from_shipping_date, to_shipping_date, provider_id, warehouse_id, cod):
865
    query = Order.query.filter(Order.cod == cod)
3427 chandransh 866
 
867
    if warehouse_id and warehouse_id != -1:
868
        query = query.filter(Order.warehouse_id == warehouse_id)
869
 
870
    if provider_id and provider_id != -1:
871
        query = query.filter(Order.logistics_provider_id == provider_id)
872
 
873
    if from_shipping_date:
874
        query = query.filter(Order.shipping_timestamp >= from_shipping_date)
875
 
876
    if to_shipping_date:
877
        query = query.filter(Order.shipping_timestamp <= to_shipping_date)
878
 
879
    query = query.order_by(Order.airwaybill_no)
880
 
881
    return query.all()
882
 
1528 ankur.sing 883
def get_orders_for_transaction(transaction_id, customer_id):
884
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
885
 
1208 chandransh 886
    if not orders:
887
        raise TransactionServiceException(101, "No order for the transaction")
888
    return orders
889
 
1405 ankur.sing 890
def get_undelivered_orders(provider_id, warehouse_id):
891
    query = Order.query
892
    if provider_id != -1:
893
        query = query.filter_by(Order.logistics_provider_id == provider_id)
894
    if warehouse_id != -1:
895
        query = query.filter(Order.warehouse_id == warehouse_id)
896
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
897
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 898
    #Get last midnight time instead of current time as courier company would have sent the 
899
    #delivery records updated at least till midnight and not by the current time.
900
    time_format = "%Y-%m-%d %H:%M:%S.%f"
901
    t = time.strptime(str(datetime.datetime.now()), time_format)
902
    midnightTime = datetime.datetime(*t[:3])
903
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 904
    orders = query.all()
905
    return orders
906
 
1208 chandransh 907
def get_line_items_for_order(order_id):
908
    query = LineItem.query.filter(LineItem.order_id == order_id)
909
    return query.all()
910
 
483 rajveer 911
def change_order_status(self, orderId, status, description):
912
    order = get_order(orderId)
913
    order.status = status
914
    order.statusDescription = description
915
    session.commit()
3578 mandeep.dh 916
    update_trust_level(order)
917
    return True
3499 mandeep.dh 918
 
3578 mandeep.dh 919
def update_trust_level(order):
3530 mandeep.dh 920
    try:
3578 mandeep.dh 921
        trust_level_delta = 0
922
        if order.cod == True:
923
            trust_level_delta = ORDER_STATUS_TO_USER_TRUST_LEVEL_DELTA_DICT.get(order.status, 0)
924
 
3530 mandeep.dh 925
        if (trust_level_delta != 0):
926
            user_client = UserClient().get_client()
927
            user_client.increaseTrustLevel(order.customer_id, trust_level_delta)
928
    except Exception as e:
929
        print e
3499 mandeep.dh 930
 
483 rajveer 931
    return True
3064 chandransh 932
 
933
def verify_order(self, orderId):
934
    logging.info("Verifying order no: " + str(orderId))
935
    order = get_order(orderId)
4662 rajveer 936
    if order.status == OrderStatus.COD_VERIFICATION_PENDING:
3064 chandransh 937
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
938
        order.statusDescription = "Submitted for processing"
939
        order.verification_timestamp = datetime.datetime.now()
940
        session.commit()
941
        logging.info("Successfully verified order no: " + str(orderId))
942
        return True
943
    else:
944
        logging.warning("Verify called for order no." + str(orderId) +" which is not in verification pending state");
945
        return False
946
 
4285 rajveer 947
def accept_order(orderId):
3064 chandransh 948
    logging.info("Accepting order no: " + str(orderId))
921 rajveer 949
    order = get_order(orderId)
5110 mandeep.dh 950
    if order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.CAPTURE_IN_PROCESS]:
3064 chandransh 951
        if not order.cod:
952
            if order.transaction.status == TransactionStatus.AUTHORIZED:
4421 mandeep.dh 953
                __capture_txn(order)
3010 chandransh 954
        order.status = OrderStatus.ACCEPTED
955
        order.statusDescription = "Order Accepted"
956
        order.accepted_timestamp = datetime.datetime.now()
5530 mandeep.dh 957
        __amend_fulfilment_warehouse(order)
3010 chandransh 958
        session.commit()
3064 chandransh 959
        logging.info("Successfully accepted the order no.:" + str(orderId))
3010 chandransh 960
        return True
961
    else:
3064 chandransh 962
        logging.warning("Accept called for the unacceptable order: " + str(orderId))
3010 chandransh 963
        return False
921 rajveer 964
 
4421 mandeep.dh 965
def __capture_txn(order):
966
    txnId = order.transaction_id
3010 chandransh 967
    logging.info("Capturing payment for merchant txn:" + str(txnId))
4421 mandeep.dh 968
    try:
969
        payment_client = PaymentClient().get_client()
970
        capture_result = payment_client.capturePayment(txnId)
971
        if capture_result:
972
            logging.info("Successfully captured payment for merchant txn:" + str(txnId))
5527 anupam.sin 973
            change_transaction_status(txnId, TransactionStatus.IN_PROCESS, "Payment received", PickUpType.COURIER, order.orderType)
4421 mandeep.dh 974
        else:
975
            raise TransactionServiceException(115, "Payment capture failed.")
976
    except PaymentException as e:
977
        if e.error_code == 106:
978
            order.status = OrderStatus.CAPTURE_IN_PROCESS
979
            session.commit()
980
            raise TransactionServiceException(122, "Unable to capture payment due to connection issue.")
981
        else:
982
            raise TransactionServiceException(115, "Payment capture failed.")
3010 chandransh 983
 
5530 mandeep.dh 984
def __amend_fulfilment_warehouse(order):
985
    itemId = order.lineitems[0].item_id
5944 mandeep.dh 986
    inventoryClient = InventoryClient().get_client()
987
    inventory = inventoryClient.getItemInventoryByItemId(itemId)
5530 mandeep.dh 988
    if not (inventory.availability.has_key(order.fulfilmentWarehouseId) and inventory.availability[order.fulfilmentWarehouseId]):
5944 mandeep.dh 989
        for warehouse in inventoryClient.getWarehouses(WarehouseType.OURS, InventoryType.GOOD, 0, order.warehouse_id, 0):
5558 mandeep.dh 990
            if inventory.availability.has_key(warehouse.id) and inventory.availability[warehouse.id] >= inventory.reserved[warehouse.id] + order.lineitems[0].quantity:
5966 rajveer 991
                inventoryClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, sourceId, order.id, order.lineitems[0].quantity)
992
                inventoryClient.reserveItemInWarehouse(itemId, warehouse.id, sourceId, order.id, to_java_date(order.created_timestamp), to_java_date(order.promised_shipping_time), order.lineitems[0].quantity)
5637 mandeep.dh 993
                order.fulfilmentWarehouseId = warehouse.id
5530 mandeep.dh 994
                break
995
 
5411 rajveer 996
def add_billing_details(orderId, invoice_number, serialNumbers, itemNumbers, billedBy, jacketNumber, billingType, fulfilmentWarehouseId, authorize):
4285 rajveer 997
    if jacketNumber is None or jacketNumber <= 0:
2783 chandransh 998
        raise TransactionServiceException(110, "Invalid jacket number")
999
 
4285 rajveer 1000
    if billedBy is None or billedBy.strip() == "":
2783 chandransh 1001
        raise TransactionServiceException(110, "Invalid Biller")
1002
 
1149 chandransh 1003
    order = Order.get_by(id=orderId)
1004
    if not order:
2783 chandransh 1005
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
5110 mandeep.dh 1006
 
5966 rajveer 1007
 
5110 mandeep.dh 1008
    lineitem = order.lineitems[0]
1009
    item_id = lineitem.item_id
5966 rajveer 1010
 
6007 rajveer 1011
#    inventoryClient = InventoryClient().get_client()
1012
#    if not inventoryClient.isOrderBillable(item_id, order.fulfilmentWarehouseId, sourceId, orderId):
1013
#        raise TransactionServiceException(101, "There are other orders to be billed before this order id " + str(orderId))
5966 rajveer 1014
 
5110 mandeep.dh 1015
    catalog_client = CatalogClient().get_client()
1016
    item = catalog_client.getItem(item_id)
4283 anupam.sin 1017
    if order.status == OrderStatus.ACCEPTED:
4285 rajveer 1018
        order.jacket_number = jacketNumber
1019
        if billingType == BillingType.OURS:
5411 rajveer 1020
            if itemNumbers:
1021
                lineitem.item_number = itemNumbers[0]    
4283 anupam.sin 1022
 
5411 rajveer 1023
            if ItemType.SERIALIZED == item.type and not (serialNumbers and serialNumbers[0]):
1024
                raise TransactionServiceException(110, "No Serial Number supplied")
1025
            if serialNumbers:
1026
                lineitem.serial_number = serialNumbers[0]
1027
 
5527 anupam.sin 1028
            order.invoice_number = get_next_invoice_number(order.orderType)
4283 anupam.sin 1029
        else:
1030
            order.invoice_number = invoice_number
4763 rajveer 1031
            # In case of hotspot billing, we should try to verify that color billed in ETP is same as color in order.
1032
            if billedOrdersColorMap.has_key(orderId):
1033
                etpColor = billedOrdersColorMap.get(orderId)
1034
                ourColor = order.lineitems[0].color
4781 rajveer 1035
                if ourColor and etpColor != ourColor and not authorize:
4763 rajveer 1036
                    raise TransactionServiceException(777, "ETP color: " + etpColor + " and Order color: " + ourColor)
1037
                else:
1038
                    billedOrdersColorMap.pop(orderId)
4283 anupam.sin 1039
 
2842 chandransh 1040
        order.status = OrderStatus.BILLED
1041
        order.statusDescription = "Order Billed"
1042
        order.billing_timestamp = datetime.datetime.now()
4285 rajveer 1043
        order.billed_by = billedBy
4435 mandeep.dh 1044
 
5436 mandeep.dh 1045
        # Letting the billing process fail in cases where we are unable to 
4435 mandeep.dh 1046
        # fill in transfer price
1047
        try:
5944 mandeep.dh 1048
            inventory_client = InventoryClient().get_client()
1049
            warehouse = inventory_client.getWarehouse(fulfilmentWarehouseId)
1050
            item_pricing = inventory_client.getItemPricing(item_id, warehouse.vendor.id)
5110 mandeep.dh 1051
            lineitem.transfer_price = item_pricing.transferPrice
6075 amit.gupta 1052
            lineitem.vatRate = catalog_client.getVatPercentageForItem(lineitem.item_id, lineitem.unit_price)
5110 mandeep.dh 1053
            order.vendorId = warehouse.vendor.id
4435 mandeep.dh 1054
        except InventoryServiceException as e:
1055
            print sys.exc_info()[0]
1056
            print e.message
5110 mandeep.dh 1057
            raise TransactionServiceException(110, 'Transfer price missing for itemId: ' + str(item_id) + ' and vendor: ' + str(warehouse.vendor.id))
4435 mandeep.dh 1058
 
5110 mandeep.dh 1059
        # For OUR warehouse, we need to scan out items for every billed order
1060
        if billingType == BillingType.OURS:
5530 mandeep.dh 1061
            for index, serialNumber in enumerate(serialNumbers):
5411 rajveer 1062
                try:
1063
                    warehouse_client = WarehouseClient().get_client()
5436 mandeep.dh 1064
                    # Fetching GOOD w/h corresponding to the virtual one here
5835 mandeep.dh 1065
                    if not warehouse.billingWarehouseId:
5950 mandeep.dh 1066
                        warehouse = inventory_client.getWarehouses(None, InventoryType.GOOD, warehouse.vendor.id, order.warehouse_id, 0)[0]
5436 mandeep.dh 1067
 
5411 rajveer 1068
                    if ItemType.SERIALIZED == item.type:
1069
                        inventoryItem = warehouse_client.getInventoryItem(serialNumber)
1070
                    else:
5661 mandeep.dh 1071
                        inventoryItem = warehouse_client.getNonSeralizedInventoryItem(itemNumbers[index], item_id, warehouse.id)
5411 rajveer 1072
 
1073
                    if (inventoryItem.itemId != item_id):
1074
                        catalog_client = CatalogClient().get_client()
1075
                        item = catalog_client.getItem(inventoryItem.itemId)
1076
                        scanItemString = " ".join([str(item.brand), str(item.modelName), str(item.modelNumber), str(item.color)])
1077
                        lineItemString = " ".join([str(lineitem.brand), str(lineitem.model_name), str(lineitem.model_number), str(lineitem.color)])
1078
                        raise TransactionServiceException(110, 'Trying to scan ' + scanItemString + ' instead of ' + lineItemString)
1079
 
1080
                    if ItemType.SERIALIZED == item.type:
5661 mandeep.dh 1081
                        inventoryItem = warehouse_client.scanSerializedItemForOrder(serialNumber, ScanType.SALE, orderId, warehouse.id, 1, order.warehouse_id)
5411 rajveer 1082
                    else:
5661 mandeep.dh 1083
                        inventoryItem = warehouse_client.scanForOrder(inventoryItem, ScanType.SALE, 1, order.id, warehouse.id, order.warehouse_id)
5411 rajveer 1084
 
1085
                    lineitem.transfer_price = inventoryItem.unitPrice
1086
                    order.vendorId = inventoryItem.supplierId
5636 amar.kumar 1087
                    catalog_client = CatalogClient().get_client()
5411 rajveer 1088
                except WarehouseServiceException as e:
1089
                    print sys.exc_info()[0]
1090
                    print 'Could not scan out orders due to: ' + e.message
1091
                    raise TransactionServiceException(110, e.message)
5123 mandeep.dh 1092
        else:
1093
            if not warehouse.isAvailabilityMonitored:
5944 mandeep.dh 1094
                inventory_client = InventoryClient().get_client()
1095
                inventory_client.addInventory(item.id, warehouse.id, -1 * lineitem.quantity)
4365 mandeep.dh 1096
 
5110 mandeep.dh 1097
        __update_inventory_reservation(order)
5661 mandeep.dh 1098
        order.fulfilmentWarehouseId = warehouse.id
4541 mandeep.dh 1099
        session.commit()
4283 anupam.sin 1100
        return True
1101
    else:
1102
        return False
1149 chandransh 1103
 
4763 rajveer 1104
def add_invoice_number(orderId, invoiceNumber, color):
4579 rajveer 1105
    order = Order.get_by(id=orderId)
1106
    if not order:
1107
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
1108
 
1109
    if order.status == OrderStatus.ACCEPTED:
1110
        order.invoice_number = invoiceNumber
4767 rajveer 1111
        if color:
1112
            billedOrdersColorMap[orderId] = color;
4579 rajveer 1113
    session.commit()
1114
 
1220 chandransh 1115
def batch_orders(warehouseId):
1116
    if not warehouseId:
1117
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 1118
 
1119
    batchno_generator = BatchNoGenerator()
1120
    session.commit()
1220 chandransh 1121
    query = Order.query.filter_by(warehouse_id=warehouseId)
4592 mandeep.dh 1122
    query = query.filter(Order.status == OrderStatus.LOW_INV_PO_RAISED)
1220 chandransh 1123
    query = query.order_by(Order.created_timestamp)
1124
    pending_orders = query.all()
1225 chandransh 1125
 
1220 chandransh 1126
    serial_no = 1
1127
    for order in pending_orders:
1276 chandransh 1128
        order.batchNo = batchno_generator.id
1220 chandransh 1129
        order.serialNo = serial_no
1130
        serial_no += 1
1131
    session.commit() 
1132
    pending_orders = query.all()
1133
    return pending_orders
1134
 
1135
def order_outofstock(orderId):
1911 chandransh 1136
    '''
1137
    Mark order as out of stock
1138
    '''
1220 chandransh 1139
    order = get_order(orderId)
1140
    order.status = OrderStatus.INVENTORY_LOW
1141
    order.statusDescription = "Low Inventory"
1142
    order.outofstock_timestamp = datetime.datetime.now()
1143
    session.commit()
1144
    return True
1145
 
4789 rajveer 1146
def mark_orders_as_shipped_from_warehouse(warehouseId, providerId, cod, orderIds):
4410 rajveer 1147
    try:
1148
        current_timestamp = datetime.datetime.now()
5822 rajveer 1149
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(warehouse_id = warehouseId, logistics_provider_id = providerId, status = OrderStatus.BILLED).all()
4410 rajveer 1150
        for order in orders:
5822 rajveer 1151
            order.status = OrderStatus.SHIPPED_FROM_WH
1152
            order.statusDescription = "Order shipped from warehouse"
1153
            order.shipping_timestamp = current_timestamp
1154
            try:
1155
                print "Trying to schedule alert"
1156
                monitoredEntity = MonitoredEntity();
1157
                monitoredEntity.entityType=EntityType.COURIER;
1158
                monitoredEntity.eventType=OrderStatus.SHIPPED_FROM_WH;
1159
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1160
                adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1161
                sec = datetime.datetime.now()
1162
                #Warn alert time is taken as 16 hrs
1163
                warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=16))
1164
                #Critical alert time is taken as 26 hrs                    
1165
                critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=26))
1166
                monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1167
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1168
                monitoredEntity.description="warehouseId = " + str(warehouseId) + " providerId = " + str(providerId) + " orderId = "  + str(order.id);
1169
                alert_client = AlertClient().get_client()
1170
                alert_client.scheduleAlert(monitoredEntity)
1171
            except Exception as e:
1172
                print "Exception in scheduling alert in ShippedFromWarehouse method"
1173
                print e
759 chandransh 1174
        session.commit()
5832 rajveer 1175
 
4749 varun.gupt 1176
 
1177
        try:
5832 rajveer 1178
            for order in orders:
1179
                if order.pickupStoreId:
1180
                    send_mails_to_bdms(order)
1181
                else:
1182
                    enqueue_shipping_confirmation_email(order)
4749 varun.gupt 1183
        except Exception as e:
1184
            print e
5832 rajveer 1185
 
759 chandransh 1186
        return True
1187
    except:
1188
        return False
4410 rajveer 1189
 
5832 rajveer 1190
def send_mails_to_bdms(order):
5816 rajveer 1191
    logistics_client = LogisticsClient().get_client()
5832 rajveer 1192
    store = logistics_client.getPickupStore(order.pickupStoreId)
1193
    provider = logistics_client.getProvider(order.logistics_provider_id)
6029 rajveer 1194
    subject = source_name + " order " + str(order.id) +" shipped to store" 
5832 rajveer 1195
    raw_message = '''
1196
    Dear Sir,
5816 rajveer 1197
 
5832 rajveer 1198
    Order mentioned below is being shipped to your store. Customer will pick it from your store. 
1199
 
1200
    Store Id: %(store_id)s
1201
    Order Id: %(order_id)s 
1202
    Product: %(product)s
1203
    Delivery By: %(provider)s
5844 mandeep.dh 1204
    Payment Mode: %(payMode)s
1205
 
1206
    %(note)s
1207
 
5832 rajveer 1208
    Thanks and Regards
1209
    Sandeep Sachdeva
1210
    '''
1211
 
5844 mandeep.dh 1212
    payMode = 'Prepaid'
1213
    note = ''
1214
    if order.cod:
1215
        payMode = 'COD'
1216
        note = 'Note: Please collect Rs. ' + str(order.total_amount) + ' from customer'
1217
 
5832 rajveer 1218
    message = dedent(raw_message) % { 'order_id' : str(order.id),
1219
                                     'store_id' : str(store.hotspotId),
1220
                                  'provider' : provider.name,
5844 mandeep.dh 1221
                                  'product' : str(order.lineitems[0]),
1222
                                  'payMode' : payMode,
1223
                                  'note'    : note
5832 rajveer 1224
                                  }
5894 rajveer 1225
    to_addresses = [store.email, store.bdmEmail, 'sandeep.sachdeva@shop2020.in', 'suraj.sharma@shop2020.in', 'manoj.kumar@shop2020.in']
1226
    cc = ['khushal.bhatia@spiceretail.co.in']
1227
    bcc = ['rajneesh.arora@spiceretail.co.in']
5966 rajveer 1228
    mail(mail_user, mail_password, to_addresses, subject, message, [], cc, bcc)
5816 rajveer 1229
 
5713 rajveer 1230
def mark_orders_as_returned_from_store(providerId, orderIds, awbs):
5676 rajveer 1231
    try:
1232
        current_timestamp = datetime.datetime.now()
5824 rajveer 1233
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(logistics_provider_id = providerId, status = OrderStatus.RET_PICKUP_REQUEST_RAISED).all()
5676 rajveer 1234
        for order in orders:
5824 rajveer 1235
            order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1236
            order.statusDescription = "Order returned from store"
1237
            order.doa_pickup_timestamp = current_timestamp
1238
            #order.airwaybill_no = awbs[orderIds.index(order.id)]
1239
            order.tracking_id = awbs[orderIds.index(order.id)]
5676 rajveer 1240
        session.commit()
1241
 
1242
        return True
1243
    except:
1244
        return False    
1245
 
1246
def set_order_attributes(orderId, attributes):
5871 rajveer 1247
    for attribute in attributes :
1248
        existingAttribute = Attribute.query.filter(Attribute.orderId == orderId).filter(Attribute.name == attribute.name).first()
1249
        if existingAttribute:
1250
            existingAttribute.value = attribute.value
1251
        else :                
1252
            attr = Attribute()
1253
            attr.orderId = orderId
1254
            attr.name = attribute.name
1255
            attr.value = attribute.value
5791 anupam.sin 1256
    session.commit()
5724 rajveer 1257
 
1113 chandransh 1258
def mark_orders_as_picked_up(provider_id, pickup_details):
1259
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 1260
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 1261
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 1262
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1263
            continue
1113 chandransh 1264
        order.status = OrderStatus.SHIPPED_TO_LOGST
1265
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 1266
        order.pickup_timestamp = pickup_timestamp
5636 amar.kumar 1267
 
1268
        try:
1269
            monitoredEntity = MonitoredEntity();
1270
            monitoredEntity.entityType=EntityType.COURIER;
1271
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_LOGST
1272
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1273
            adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1274
            sec = datetime.datetime.now()
1275
            #Warn alert time is taken as 16 hrs
5821 amit.gupta 1276
            warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=15))
5744 amar.kumar 1277
            #Critical alert time is taken as 26 hrs                    
5821 amit.gupta 1278
            critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=20))
5744 amar.kumar 1279
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1280
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5819 amit.gupta 1281
            monitoredEntity.description="providerId = " + str(provider_id)
5636 amar.kumar 1282
            alert_client = AlertClient().get_client()
1283
            alert_client.updateMonitoredObject(monitoredEntity)
1284
        except Exception as e:
5801 amar.kumar 1285
            print "Exception in updating alert in MarkOrdersAsPickedUp method"
5636 amar.kumar 1286
            print e
1113 chandransh 1287
    session.commit()
1217 chandransh 1288
 
4910 phani.kuma 1289
def get_orders_not_picked_up(provider_id):
1132 chandransh 1290
    current_time = datetime.datetime.now()
1291
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4741 phani.kuma 1292
    orders_not_picked_up = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.SHIPPED_FROM_WH).filter(Order.shipping_timestamp <= to_datetime).all()
1113 chandransh 1293
    return orders_not_picked_up
1294
 
1132 chandransh 1295
def mark_orders_as_delivered(provider_id, delivered_orders):
1296
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 1297
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 1298
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE]:
1911 chandransh 1299
            continue
1300
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
5555 rajveer 1301
        if order.pickupStoreId:
1302
            order.status = OrderStatus.DELIVERED_AT_STORE
1303
            order.statusDescription = "Order delivered At Store"
5762 amar.kumar 1304
            try:
1305
                monitoredEntity = MonitoredEntity();
1306
                monitoredEntity.entityType=EntityType.COURIER;
1307
                monitoredEntity.eventType=OrderStatus.RECEIVED_AT_STORE;
1308
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1309
                #adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1310
                sec = datetime.datetime.now()
1311
                #Critical alert time is taken as 26 hrs                    
1312
                critical_time = (sec + timedelta(hours=4))
1313
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1314
                monitoredEntity.description="deliveryTimeAtStore = " + str(order.delivery_timestamp) + " orderId = "  + str(order.id);
1315
                alert_client = AlertClient().get_client()
1316
                alert_client.updateMonitoredObject(monitoredEntity)
1317
            except Exception as e:
1318
                print e
5555 rajveer 1319
        else:
1320
            order.status = OrderStatus.DELIVERY_SUCCESS
1321
            order.statusDescription = "Order delivered"
5762 amar.kumar 1322
            update_trust_level(order)
5966 rajveer 1323
            enqueue_delivery_success_mail(order)
5762 amar.kumar 1324
            try:
1325
                alert_client = AlertClient().get_client()
1326
                alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1327
            except Exception as e:
5801 amar.kumar 1328
                print "Exception in scheduling alert in ShippedFromWarehouse method"
5762 amar.kumar 1329
                print e
4910 phani.kuma 1330
        timestamp, receiver = detail.split('|')
1331
        if order.first_dlvyatmp_timestamp is None:
1332
            order.first_dlvyatmp_timestamp = timestamp
1333
        order.delivery_timestamp = timestamp
1334
        order.receiver = receiver
5636 amar.kumar 1335
 
1132 chandransh 1336
    session.commit()
1337
 
4712 rajveer 1338
def mark_order_as_delivered(orderId, deliveryTimestamp, receiver):
1339
    order = Order.get_by(id=orderId)
5555 rajveer 1340
    if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_REQUEST_RECEIVED, OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_REQUEST_AUTHORIZED, OrderStatus.RET_PICKUP_REQUEST_RAISED, OrderStatus.RTO_IN_TRANSIT, OrderStatus.BILLED, OrderStatus.RECEIVED_AT_STORE]:
4712 rajveer 1341
        raise TransactionServiceException(101, "Either wrond order id or invalid state " + str(orderId))
5402 rajveer 1342
 
1343
    # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
1344
    if order.status == OrderStatus.BILLED and order.logistics_provider_id != 4:
5807 rajveer 1345
        raise TransactionServiceException(101, "Order is not marked for self pickup: " + str(orderId))
5402 rajveer 1346
 
5555 rajveer 1347
    if order.status in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.RTO_IN_TRANSIT, OrderStatus.BILLED, OrderStatus.RECEIVED_AT_STORE]:
4712 rajveer 1348
        order.delivery_timestamp = deliveryTimestamp
1349
        order.receiver = receiver
1350
    order.status = OrderStatus.DELIVERY_SUCCESS
1351
    order.statusDescription = "Order delivered"
1352
    update_trust_level(order)
1353
    session.commit()
5713 rajveer 1354
 
5812 rajveer 1355
    if order.pickupStoreId and order.cod:
5806 rajveer 1356
        __push_collection_to_hotspot(order, "SALE")
1357
 
5966 rajveer 1358
    enqueue_delivery_success_mail(order)
5713 rajveer 1359
#    if order.pickupStoreId:
1360
#        payment_client = PaymentClient().get_client()
1361
#        payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
1362
#        payment_client = PaymentClient().get_client()
1363
#        payment_client.partiallyCapturePayment(order.transaction.id, order.total_amount, xferBy, xferTxnId, now())
1364
#        order.cod_reconciliation_timestamp = datetime.datetime.now()
1365
#        session.commit()
1366
 
5636 amar.kumar 1367
    try:
1368
        alert_client = AlertClient().get_client()
5744 amar.kumar 1369
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1370
    except Exception as e:
5801 amar.kumar 1371
        print "Exception in ending alert in MarkOrderAsDelivered method"
5636 amar.kumar 1372
        print e
1373
 
4712 rajveer 1374
 
5555 rajveer 1375
def mark_order_as_received_at_store(orderId, deliveryTimestamp):
1376
    order = Order.get_by(id=orderId)
1377
    if order != None or order.status in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DELIVERED_AT_STORE]:
1378
        order.status = OrderStatus.RECEIVED_AT_STORE
1379
        order.statusDescription = "Order received at store"
1380
        order.delivery_timestamp = deliveryTimestamp
1381
    session.commit()
5713 rajveer 1382
    try:
5762 amar.kumar 1383
        alert_client = AlertClient().get_client()
1384
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1385
    except Exception as e:
1386
        print e
1387
 
1388
    try:
5713 rajveer 1389
        enqueue_received_at_store_email(order)
1390
    except Exception as e:
1391
        print e
1392
 
1393
 
5555 rajveer 1394
 
4910 phani.kuma 1395
def mark_orders_as_rto(provider_id, returned_orders):
1135 chandransh 1396
    for awb, detail in returned_orders.iteritems():
1397
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
5713 rajveer 1398
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.DELIVERED_AT_STORE, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE]:
2684 chandransh 1399
            continue
1400
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 1401
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 1402
        order.delivery_timestamp, reason = detail.split('|')
1403
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 1404
        update_trust_level(order)
1911 chandransh 1405
    session.commit()
5636 amar.kumar 1406
    try:
1407
        alert_client = AlertClient().get_client()
5801 amar.kumar 1408
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1409
    except Exception as e:
5801 amar.kumar 1410
        print "Exception in ending alert in MarkOrderAsRTO method"
5636 amar.kumar 1411
        print e
1135 chandransh 1412
 
4910 phani.kuma 1413
def get_rto_orders(provider_id):
1414
    current_time = datetime.datetime.now()
1415
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1416
    rto_orders = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.RTO_IN_TRANSIT).filter(Order.delivery_timestamp <= to_datetime).all()
1417
    return rto_orders
1418
 
5555 rajveer 1419
def get_receive_pending_orders(storeId):
1420
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.DELIVERED_AT_STORE))).all()
1421
 
1422
def get_received_at_store_orders(storeId):
5676 rajveer 1423
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.RECEIVED_AT_STORE, OrderStatus.RET_PICKUP_REQUEST_RAISED))).all()
5555 rajveer 1424
 
5713 rajveer 1425
def get_orders_collection_at_store(storeId, fromDate, toDate, onlyCod):
1426
    query = Order.query.filter(Order.status == OrderStatus.DELIVERY_SUCCESS)
1427
    if storeId:
1428
        query = query.filter_by(pickupStoreId = storeId)
5720 rajveer 1429
    else:
1430
        query = query.filter(Order.pickupStoreId != 0)
5713 rajveer 1431
    if onlyCod:
1432
        query = query.filter_by(cod = onlyCod)
1433
    if fromDate:
1434
        query = query.filter(Order.delivery_timestamp >= fromDate)
1435
    if toDate:
1436
        query = query.filter(Order.delivery_timestamp <= toDate)
1437
    return query.all()
1438
 
1246 chandransh 1439
def update_non_delivery_reason(provider_id, undelivered_orders):
1440
    for awb, reason in undelivered_orders.iteritems():
1441
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4920 phani.kuma 1442
        if order == None or order.status == OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE:
2684 chandransh 1443
            continue
1444
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 1445
        order.statusDescription = reason
1446
    session.commit()
4910 phani.kuma 1447
 
1448
def get_non_delivered_orders_by_courier(provider_id):
4581 phani.kuma 1449
    current_time = datetime.datetime.now()
1450
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1451
    upto_datetime = today_datetime - datetime.timedelta(4)
4910 phani.kuma 1452
    orders_not_delivered = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE))).filter(or_(Order.shipping_timestamp <= upto_datetime, Order.pickup_timestamp <= upto_datetime)).all()
4581 phani.kuma 1453
    return orders_not_delivered
1246 chandransh 1454
 
4910 phani.kuma 1455
def mark_orders_as_local_connected(provider_id, local_connected_orders):
1456
    for awb, timestamp in local_connected_orders.iteritems():
1457
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1458
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1459
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1460
            continue
1461
        order.status = OrderStatus.SHIPPED_TO_DESTINATION_CITY
1462
        order.statusDescription = "Left Out of Origin City"
5636 amar.kumar 1463
        current_time = datetime.datetime.now()
1464
        order.local_connected_timestamp = datetime.datetime(current_time.year, current_time.month, current_time.day)
1465
        try:
1466
            monitoredEntity = MonitoredEntity();
1467
            monitoredEntity.entityType=EntityType.COURIER;
1468
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_DESTINATION_CITY
1469
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1470
            #Warn alert time is taken as 23 hrs less than promised delivery time
5821 amit.gupta 1471
            warn_time = (order.expected_delivery_time-timedelta(hours = 15))
5744 amar.kumar 1472
            #Critical alert time is taken as 13 hrs less than promised delivery time                    
5821 amit.gupta 1473
            critical_time = (order.expected_delivery_time-timedelta(hours = 10))
5801 amar.kumar 1474
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1475
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1476
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1477
            alert_client = AlertClient().get_client()
1478
            alert_client.updateMonitoredObject(monitoredEntity)
1479
        except Exception as e:
5801 amar.kumar 1480
            print "Exception in updating alert in MarkOrderAsLocalConnected method"
5636 amar.kumar 1481
            print e
1482
        session.commit()
4910 phani.kuma 1483
 
1484
def get_orders_not_local_connected(provider_id):
1485
    current_time = datetime.datetime.now()
1486
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1487
    orders_pending_local_connection = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST))).filter(or_(Order.shipping_timestamp <= to_datetime, Order.pickup_timestamp <= to_datetime)).all()
1488
    return orders_pending_local_connection
1489
 
1490
def mark_orders_as_destinationCityReached(provider_id, destination_city_reached_orders):
1491
    for awb, timestamp in destination_city_reached_orders.iteritems():
1492
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1493
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY]:
1494
            continue
1495
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1496
        order.status = OrderStatus.REACHED_DESTINATION_CITY
1497
        order.statusDescription = "Reached Destination City"
1498
        order.reached_destination_timestamp = timestamp
5636 amar.kumar 1499
        try:
1500
            monitoredEntity = MonitoredEntity();
1501
            monitoredEntity.entityType=EntityType.COURIER;
1502
            monitoredEntity.eventType=OrderStatus.REACHED_DESTINATION_CITY
1503
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5764 amar.kumar 1504
            warn_time = (order.expected_delivery_time)
5801 amar.kumar 1505
            critical_time = (order.expected_delivery_time + timedelta(hours=12))
1506
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1507
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1508
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1509
            alert_client = AlertClient().get_client()
1510
            alert_client.updateMonitoredObject(monitoredEntity)
1511
        except Exception as e:
5801 amar.kumar 1512
            print "Exception in updating alert in MarkOrderAsDestCityReached method"
5636 amar.kumar 1513
            print e
4910 phani.kuma 1514
    session.commit()
1515
 
1516
def mark_orders_as_firstDeliveryAttempted(provider_id, first_atdl_orders):
1517
    for awb, detail in first_atdl_orders.iteritems():
1518
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1519
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY]:
1520
            continue
1521
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1522
        order.status = OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1523
        order.first_dlvyatmp_timestamp, reason = detail.split('|')
1524
        order.statusDescription = reason
5636 amar.kumar 1525
        try:
1526
            monitoredEntity = MonitoredEntity();
1527
            monitoredEntity.entityType=EntityType.COURIER;
1528
            monitoredEntity.eventType=OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1529
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1530
            adjustedDeliveryDaysfor1day = adjust_delivery_time(datetime.datetime.now(), 1);
1531
            adjustedDeliveryDaysfor2days = adjust_delivery_time(datetime.datetime.now(), 2);
1532
            sec = datetime.datetime.now()
1533
            #Warn alert time is taken as 16 hrs
1534
            warn_time = (sec + timedelta(days=(adjustedDeliveryDaysfor1day-1)) + timedelta(hours=24))
1535
            #Critical alert time is taken as 26 hrs                    
1536
            critical_time = (sec + timedelta(days=(adjustedDeliveryDaysfor2days-1)) + timedelta(hours=36))
1537
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1538
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1539
            monitoredEntity.description="providerId = " + str(provider_id) + " first attempt timestamp" + order.first_dlvyatmp_timestamp
1540
            alert_client = AlertClient().get_client()
1541
            alert_client.updateMonitoredObject(monitoredEntity)
1542
        except Exception as e:
5801 amar.kumar 1543
            print "Exception in updating alert in MarkOrdersAsFirstDeliveryAttempted method"
5636 amar.kumar 1544
            print e
4910 phani.kuma 1545
    session.commit()
1546
 
4783 phani.kuma 1547
def get_orders_not_met_expected_delivery_date():
1548
    current_time = datetime.datetime.now()
1549
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4910 phani.kuma 1550
    orders_not_delivered = Order.query.filter(Order.status.in_((OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY))).filter(Order.expected_delivery_time <= today_datetime).all()
4783 phani.kuma 1551
    return orders_not_delivered
1552
 
4444 rajveer 1553
def get_alerts(type, warehouseId, status, timestamp):
1554
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
1555
    if type != -1 :
1556
        query = query.filter(Alert.type == type)
1557
    if status != -1 :
1558
        query = query.filter(Alert.status == status)
4394 rajveer 1559
    if timestamp:
1560
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 1561
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 1562
    return query.all()
1563
 
4447 rajveer 1564
def add_alert(type, warehouseId, description):
4394 rajveer 1565
    alert = Alert()
1566
    alert.type = type
1567
    alert.status = 1
1568
    alert.description = description
1569
    alert.timestamp = datetime.datetime.now()
4447 rajveer 1570
    alert.warehouseId = warehouseId
4444 rajveer 1571
    session.commit()
766 rajveer 1572
 
4444 rajveer 1573
def mark_alerts_as_seen(warehouseId):
1574
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
1575
    alerts = query.all()
1576
    for alert in alerts:
1577
        alert.status = 0    
1578
    session.commit()
1579
 
1596 ankur.sing 1580
def get_valid_order_count():
2851 chandransh 1581
    '''
1582
    Returns the number of orders which we processed. The reshipped orders are not
1583
    counted since there'll always be a new compensating order present.
1584
    '''
4682 rajveer 1585
    return Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).filter(not_(Order.status.in_((OrderStatus.RTO_RESHIPPED, OrderStatus.DOA_INVALID_RESHIPPED, OrderStatus.DOA_VALID_RESHIPPED, OrderStatus.COD_VERIFICATION_FAILED)))).count()
1596 ankur.sing 1586
 
1627 ankur.sing 1587
def get_cust_count_with_successful_txn():
2851 chandransh 1588
    '''
1589
    Returns the number of distinct customers who have done successful transactions.
1590
    It uses the sqlalchemy func module to construct an efficient query.
1591
    '''
1592
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 1593
 
1730 ankur.sing 1594
def get_valid_orders_amount_range():
2851 chandransh 1595
    '''
1596
    Returns a list containing the minimum and maximum amount across all
1597
    orders placed with us. No need to consider reshippped orders for min/max
1598
    amount of orders.
1599
    '''
1600
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 1601
 
5874 rajveer 1602
def get_valid_orders(limit, onlyStore):
2851 chandransh 1603
    '''
1604
    Returns the last limit number of valid orders placed with us. Ignored the
1605
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
1606
    less than 0. 
1607
    '''
1608
    if limit < 0:
1609
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
4662 rajveer 1610
    query = Order.query.filter(Order.status >= OrderStatus.COD_VERIFICATION_PENDING)
5874 rajveer 1611
    if onlyStore:
1612
        query = query.filter(Order.pickupStoreId != 0)
1886 ankur.sing 1613
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 1614
    if limit != 0:
1886 ankur.sing 1615
        query = query.limit(limit)
1616
    return query.all()
1617
 
5527 anupam.sin 1618
def get_next_invoice_number(orderType):
1619
    if OrderType.B2Cbulk == orderType:
1620
        orderType = OrderType.B2C
1621
    entity_id = InvoiceIDGenerator.query.filter(InvoiceIDGenerator.orderType == orderType).with_lockmode("update").one()
2783 chandransh 1622
    invoice_number = entity_id.id + 1
1623
    entity_id.id = invoice_number
1624
    return invoice_number
1625
 
2536 chandransh 1626
def toggle_doa_flag(order_id):
1627
    order = get_order(order_id)
1628
    if(order.doaFlag):
1629
        order.doaFlag = False
1630
    else:
1631
        order.doaFlag = True
1632
    session.commit()
1633
    return order.doaFlag
1634
 
4454 rajveer 1635
def mark_order_doa_request_received(orderId):
1636
    order = get_order(orderId)
1637
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1638
        return False
1639
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 1640
    order.statusDescription = "DOA Request Received"
4454 rajveer 1641
    session.commit()
1642
    return True
1643
 
1644
def mark_order_doa_request_authorized(orderId, isAuthorized):
1645
    order = get_order(orderId)
1646
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
1647
        return False
1648
    if isAuthorized:
1649
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 1650
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 1651
    else:
1652
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 1653
        order.statusDescription = "Order delivered"
4454 rajveer 1654
    session.commit()
1655
    return True
1656
 
4488 rajveer 1657
def mark_order_return_request_received(orderId):
1658
    order = get_order(orderId)
1659
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1660
        return False
1661
    order.status = OrderStatus.RET_REQUEST_RECEIVED
1662
    order.statusDescription = "Return Request Received"
1663
    session.commit()
1664
    return True
1665
 
1666
def mark_order_return_request_authorized(orderId, isAuthorized):
1667
    order = get_order(orderId)
1668
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
1669
        return False
1670
    if isAuthorized:
1671
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
1672
        order.statusDescription = "Return Request Authorized"
1673
    else:
1674
        order.status = OrderStatus.DELIVERY_SUCCESS
1675
        order.statusDescription = "Order delivered"
1676
    session.commit()
1677
    return True
1678
 
4579 rajveer 1679
def request_pickup_number(order_id, providerId):
2536 chandransh 1680
    order = get_order(order_id)
4495 rajveer 1681
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 1682
        return False
1683
 
4227 rajveer 1684
    subject = "Pickup request from " + order.customer_city
2536 chandransh 1685
    try:
5944 mandeep.dh 1686
        inventory_client = InventoryClient().get_client()
1687
        warehouse = inventory_client.getWarehouse(order.warehouse_id)
2536 chandransh 1688
 
1689
        logistics_client = LogisticsClient().get_client()
4579 rajveer 1690
        provider = logistics_client.getProvider(providerId)
3051 chandransh 1691
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 1692
        raw_message = '''
1693
        Dear Sir/Madam,
1694
 
2559 chandransh 1695
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 1696
 
1697
        Pickup CODE: %(provider_code)s
1698
        Total Weight: %(order_weight)s kg
1699
 
2559 chandransh 1700
        Pickup Address:
2536 chandransh 1701
 
1702
        %(customer_address)s
1703
 
1704
        Delivery Address:
1705
 
1706
        %(warehouse_executive)s
1707
        %(warehouse_address)s
1708
        PIN %(warehouse_pin)s
1709
 
1710
        Thanks and Regards
4227 rajveer 1711
        Sandeep Sachdeva
2536 chandransh 1712
        '''
4579 rajveer 1713
 
1714
        if warehouse.id == 7:
1715
            executive = 'Amit Kumar'
1716
        else:
4966 phani.kuma 1717
            executive = 'Dinesh Kumar'
4579 rajveer 1718
 
2559 chandransh 1719
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 1720
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
2536 chandransh 1721
                                          'order_weight' : str(order.total_weight),
1722
                                          'customer_address' : __get_order_address(order),
4579 rajveer 1723
                                          'warehouse_executive' : executive,
2536 chandransh 1724
                                          'warehouse_address' : warehouse.location,
4966 phani.kuma 1725
                                          'warehouse_pin' : warehouse.pincode}
5860 rajveer 1726
        to_addresses = [to_addr, 'gaurabh.verma@shop2020.in', 'suraj.sharma@shop2020.in']
4966 phani.kuma 1727
 
5966 rajveer 1728
        mail(mail_user, mail_password, to_addresses, subject, message)
4495 rajveer 1729
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
1730
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
1731
            order.statusDescription = "Pick up requested for RETURN"
1732
        else:
1733
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
1734
            order.statusDescription = "Pick up requested for DOA"
4815 phani.kuma 1735
        order.doa_logistics_provider_id = providerId
2536 chandransh 1736
        session.commit()
1737
        return True
1738
    except Exception as e:
1739
        print sys.exc_info()[0]
1740
        return False
1741
 
4602 rajveer 1742
def authorize_pickup(order_id, pickup_number, providerId):
2536 chandransh 1743
    order = get_order(order_id)
4495 rajveer 1744
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 1745
        return False
4815 phani.kuma 1746
    if order.doa_logistics_provider_id is not None:
1747
        providerId = order.doa_logistics_provider_id    #previously we are not storing this so data is taken from omdashboarduser
2536 chandransh 1748
    subject = 'Pickup details'
1749
    filename = "/tmp/" +  str(order.id) +".pdf" 
1750
    try:
5944 mandeep.dh 1751
        inventory_client = InventoryClient().get_client()
1752
        warehouse = inventory_client.getWarehouse(order.warehouse_id)
2536 chandransh 1753
 
1754
        logistics_client = LogisticsClient().get_client()
4602 rajveer 1755
        provider = logistics_client.getProvider(providerId)
2536 chandransh 1756
        provider_name = provider.name
1757
 
1758
        to_addr = order.customer_email
1759
        today = date.today().strftime("%d-%B-%Y (%A)")
1760
 
1761
        raw_message = '''
1762
        Dear Mr. %(customer_name)s,
1763
 
4815 phani.kuma 1764
        In reference to the return of order ID %(order_id)d, ''' + __generate_mail_body_for_authorize_pickup(order)
1765
        raw_message = raw_message + '''
2536 chandransh 1766
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
1767
        We have instructed %(provider_name)s to pick up the material from the below mentioned address on %(date)s. %(provider_name)s pickup request number is %(pickup_request_no)s. Kindly keep the parcel ready.
1768
 
1769
        Pickup will happen from the below mentioned address:-
1770
 
1771
        %(customer_address)s
1772
 
1773
        Do let us know in case of any concerns
1774
 
1775
        Thanks & Regards
6029 rajveer 1776
        %(source_name)s Team
2536 chandransh 1777
        '''
1778
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
1779
                                         'order_id' : order_id,
1780
                                         'provider_name' : provider_name,
1781
                                         'date': today,
1782
                                         'pickup_request_no' : pickup_number,
6029 rajveer 1783
                                         'customer_address' : __get_order_address(order),
1784
                                         'source_name' : source_name}
2536 chandransh 1785
        print message
1786
        __generate_return_advice(order, warehouse, provider, filename)
5966 rajveer 1787
        mail(help_user, help_password, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 1788
        order.pickupRequestNo = pickup_number
4495 rajveer 1789
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1790
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
1791
            order.statusDescription = "RETURN pick up confirmed"
1792
        else:
1793
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
1794
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 1795
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 1796
        session.commit()
1797
        return True
1798
    except Exception as e:
4234 rajveer 1799
        print sys.exc_info()
4506 phani.kuma 1800
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 1801
        return False
1802
    finally:
1803
        if os.path.exists(filename):
1804
            os.remove(filename)
1805
 
4815 phani.kuma 1806
def __generate_mail_body_for_authorize_pickup(order):
1807
    brand_msgbody_map = {'Nokia' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1808
                         'Micromax' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1809
                         'Karbonn' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1810
                         'Sony Ericsson' : 'we request you to kindly pack the original DOA certificate and the invoice.',
1811
                         'Others Handsets' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original "DOA" certificate and the invoice. Please paste the original DOA on the sealed box. Kindly ensure that the product is properly sealed. If we receive open sealed products, we will not be able to accept.',
1812
                         'Handsets Return' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the all original accessories, original handset and the invoice.',
1813
                         'Accessories' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original product and the invoice.'}
1814
    categories = ["Handsets", "Tablets", "Laptops"]
1815
    lineitem = order.lineitems[0]
1816
    brand = lineitem.brand
1817
    productGroup = lineitem.productGroup
1818
    searchkey = None
1819
    if productGroup not in categories:
1820
        searchkey = 'Accessories'
1821
    elif order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1822
        searchkey = 'Handsets Return'
1823
    elif brand == 'Nokia':
1824
        searchkey = 'Nokia'
1825
    elif brand == 'Micromax':
1826
        searchkey = 'Micromax'
1827
    elif brand == 'Karbonn':
1828
        searchkey = 'Karbonn'
1829
    elif brand == 'Sony Ericsson':
1830
        searchkey = 'Sony Ericsson'
1831
    else:
1832
        searchkey = 'Others Handsets'
1833
    return brand_msgbody_map.get(searchkey)
1834
 
2764 chandransh 1835
def mark_doas_as_picked_up(provider_id, pickup_details):
1836
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1837
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4452 rajveer 1838
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 1839
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1840
            continue
1841
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
1842
        order.statusDescription = "DOA picked up by Courier Company"
1843
        order.doa_pickup_timestamp = doa_pickup_timestamp
1844
    session.commit()
1845
 
4910 phani.kuma 1846
def get_doas_not_picked_up(provider_id):
2764 chandransh 1847
    current_time = datetime.datetime.now()
1848
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1849
    orders_not_picked_up = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter_by(status=OrderStatus.DOA_PICKUP_CONFIRMED).filter(Order.doa_auth_timestamp <= to_datetime).all()
2764 chandransh 1850
    return orders_not_picked_up
1851
 
4741 phani.kuma 1852
def mark_return_orders_as_picked_up(provider_id, pickup_details):
1853
    for pickupNo, return_order_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1854
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4741 phani.kuma 1855
        if order == None or order.status != OrderStatus.RET_PICKUP_CONFIRMED:
1856
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1857
            continue
1858
        order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1859
        order.statusDescription = "Return order picked up by Courier Company"
1860
        order.doa_pickup_timestamp = return_order_pickup_timestamp
1861
    session.commit()
1862
 
4910 phani.kuma 1863
def get_return_orders_not_picked_up(provider_id):
4741 phani.kuma 1864
    current_time = datetime.datetime.now()
1865
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1866
    orders_not_picked_up = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter_by(status=OrderStatus.RET_PICKUP_CONFIRMED).filter(Order.doa_auth_timestamp <= to_datetime).all()
4741 phani.kuma 1867
    return orders_not_picked_up
1868
 
4479 rajveer 1869
def receive_return(order_id, receiveCondition):
2591 chandransh 1870
    order = get_order(order_id)
4365 mandeep.dh 1871
 
4452 rajveer 1872
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 1873
        if receiveCondition == 0:
1874
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
1875
            order.statusDescription = "DOA package received"
1876
        elif receiveCondition == 1:
1877
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
1878
            order.statusDescription = "DOA received damaged"
1879
        elif receiveCondition == 2:
1880
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
1881
            order.statusDescription = "DOA lost in transit"
2764 chandransh 1882
        order.received_return_timestamp = datetime.datetime.now()
4495 rajveer 1883
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
1884
        if receiveCondition == 0:
1885
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
1886
            order.statusDescription = "RETURN package received"
1887
        elif receiveCondition == 1:
1888
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
1889
            order.statusDescription = "RETURN received damaged"
1890
        elif receiveCondition == 2:
1891
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
1892
            order.statusDescription = "RETURN lost in transit"
1893
        order.received_return_timestamp = datetime.datetime.now()
4484 rajveer 1894
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 1895
        if receiveCondition == 0:
1896
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 1897
            order.statusDescription = "Returned to origin"
4486 rajveer 1898
        elif receiveCondition == 1:
1899
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
1900
            order.statusDescription = "RTO received damaged"
1901
        elif receiveCondition == 2:
1902
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
1903
            order.statusDescription = "RTO lost in transit"
2764 chandransh 1904
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1905
    else:
2591 chandransh 1906
        return False
5110 mandeep.dh 1907
 
1908
    # For OUR warehouses, we need to scan in items for every return
5944 mandeep.dh 1909
    inventoryClient = InventoryClient().get_client()
1910
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
5110 mandeep.dh 1911
    if warehouse.billingType == BillingType.OURS:
5361 mandeep.dh 1912
        scanMap = {
1913
            OrderStatus.RTO_RECEIVED_PRESTINE : ScanType.SALE_RET,
1914
            OrderStatus.RTO_RECEIVED_DAMAGED  : ScanType.SALE_RET_UNUSABLE,
1915
            OrderStatus.RTO_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT,
1916
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
1917
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
1918
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
1919
        }
5110 mandeep.dh 1920
 
5419 mandeep.dh 1921
        if scanMap.has_key(order.status):
1922
            scanType = scanMap[order.status]
5361 mandeep.dh 1923
            lineitem = order.lineitems[0]
5944 mandeep.dh 1924
            catalogClient = CatalogClient().get_client()
5361 mandeep.dh 1925
            item = catalogClient.getItem(lineitem.item_id)
1926
            warehouseClient = WarehouseClient().get_client()
1927
            if item.type == ItemType.SERIALIZED:
5110 mandeep.dh 1928
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 1929
            else:
1930
                warehouseClient.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
5110 mandeep.dh 1931
 
5558 mandeep.dh 1932
    session.commit()
2591 chandransh 1933
    return True
1934
 
1935
def validate_doa(order_id, is_valid):
1936
    order = get_order(order_id)
4452 rajveer 1937
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 1938
        return False
1939
    if is_valid:
2609 chandransh 1940
        order.status = OrderStatus.DOA_CERT_VALID
1941
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 1942
    else:
1943
        order.status = OrderStatus.DOA_CERT_INVALID
1944
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 1945
        update_trust_level(order)
2591 chandransh 1946
    session.commit()
1947
    return True
1948
 
4495 rajveer 1949
def validate_return_product(order_id, is_usable):
1950
    order = get_order(order_id)
1951
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
1952
        return False
5110 mandeep.dh 1953
 
1954
    scanType = ScanType.SALE_RET_UNUSABLE
4495 rajveer 1955
    if is_usable:
1956
        order.status = OrderStatus.RET_PRODUCT_USABLE
1957
        order.statusDescription = "Return product usable"
5110 mandeep.dh 1958
        scanType = ScanType.SALE_RET
4495 rajveer 1959
    else:
1960
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
1961
        order.statusDescription = "Return product unusable"
1962
        update_trust_level(order)
1963
    session.commit()
5110 mandeep.dh 1964
 
1965
    # For OUR warehouses, we need to scan in items for every return
5944 mandeep.dh 1966
    inventoryClient = InventoryClient().get_client()
1967
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
5110 mandeep.dh 1968
    if warehouse.billingType == BillingType.OURS:
1969
        lineitem = order.lineitems[0]
5944 mandeep.dh 1970
        catalogClient = CatalogClient().get_client()
5361 mandeep.dh 1971
        item = catalogClient.getItem(lineitem.item_id)
5110 mandeep.dh 1972
        warehouse_client = WarehouseClient().get_client()
5361 mandeep.dh 1973
        if item.type == ItemType.SERIALIZED:
1974
            warehouse_client.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
1975
        else:
1976
            warehouse_client.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4495 rajveer 1977
    return True
1978
 
2628 chandransh 1979
def reship_order(order_id):
1980
    """
4484 rajveer 1981
    If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1982
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
4484 rajveer 1983
        2. Marks the current order as one of the final states RTO_RESHIPPED and DOA_INVALID_RESHIPPED depending on what state the order started in.
2628 chandransh 1984
 
1985
    If the order is in DOA_CERT_VALID state, it does the following:
1986
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
1987
        2. Creates a return order for the warehouse executive to return the DOA material.
4452 rajveer 1988
        3. Marks the current order as the final DOA_VALID_RESHIPPED state.
2628 chandransh 1989
 
1990
    Returns the id of the newly created order.
1991
 
1992
    Throws an exception if the order with the given id couldn't be found.
1993
 
1994
    Parameters:
1995
     - orderId
1996
    """
1997
    order = get_order(order_id)
4484 rajveer 1998
    if order.status == OrderStatus.RTO_RECEIVED_PRESTINE:
4220 rajveer 1999
        new_order = __clone_order(order, True, order.cod)
4484 rajveer 2000
        order.status = OrderStatus.RTO_RESHIPPED
2628 chandransh 2001
        order.statusDescription = "Order Reshipped"
2002
        session.commit()
3578 mandeep.dh 2003
        update_trust_level(order)
4486 rajveer 2004
    elif order.status == OrderStatus.RTO_RECEIVED_DAMAGED:
2005
        new_order = __clone_order(order, False, order.cod)
2006
        ret_order = __create_return_order(order)
2007
        order.status = OrderStatus.RTO_DAMAGED_RESHIPPED
2008
        order.statusDescription = "Order Reshipped Received Damaged"
2009
        session.commit()
2010
    elif order.status == OrderStatus.RTO_LOST_IN_TRANSIT:
2011
        new_order = __clone_order(order, False, order.cod)
2012
        order.status = OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED
2013
        order.statusDescription = "Order Reshipped Lost In Transit"
2014
        session.commit()
4662 rajveer 2015
    elif order.status == OrderStatus.LOST_IN_TRANSIT:
2016
        new_order = __clone_order(order, False, order.cod)
2017
        order.status = OrderStatus.LOST_IN_TRANSIT_RESHIPPED
2018
        order.statusDescription = "Order Reshipped Lost In Transit"
2019
        session.commit()
2628 chandransh 2020
    elif order.status == OrderStatus.DOA_CERT_INVALID:
4220 rajveer 2021
        new_order = __clone_order(order, True, False)
2628 chandransh 2022
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
2023
        order.statusDescription = "Order Reshipped"
2024
        session.commit()
5620 mandeep.dh 2025
        warehouseClient = WarehouseClient().get_client()
2026
        inventoryItem = warehouseClient.getInventoryItemFromOrder(order_id)
2027
        warehouseClient.scanForOrder(inventoryItem, ScanType.SALE, new_order.lineitems[0].quantity, new_order.id, new_order.fulfilmentWarehouseId, new_order.warehouse_id)
2628 chandransh 2028
    elif order.status == OrderStatus.DOA_CERT_VALID:
4220 rajveer 2029
        new_order = __clone_order(order, False, False)
2628 chandransh 2030
        ret_order = __create_return_order(order)
4452 rajveer 2031
        order.status = OrderStatus.DOA_VALID_RESHIPPED
2628 chandransh 2032
        order.statusDescription = "Order Reshipped"
2033
        session.commit()
4479 rajveer 2034
    elif order.status == OrderStatus.DOA_RECEIVED_DAMAGED:
2035
        new_order = __clone_order(order, False, False)
2036
        ret_order = __create_return_order(order)
2037
        order.status = OrderStatus.DOA_RESHIPPED_RCVD_DAMAGED
2038
        order.statusDescription = "Order Reshipped Received Damaged"
2039
        session.commit()
2040
    elif order.status == OrderStatus.DOA_LOST_IN_TRANSIT:
2041
        new_order = __clone_order(order, False, False)
2042
        order.status = OrderStatus.DOA_RESHIPPED_LOST_IN_TRANSIT
2043
        order.statusDescription = "Order Reshipped Lost In Transit"
2044
        session.commit()
4614 rajveer 2045
    elif order.status == OrderStatus.RET_PRODUCT_USABLE:
5620 mandeep.dh 2046
        new_order = __clone_order(order, False, False)
4614 rajveer 2047
        order.status = OrderStatus.RET_PRODUCT_USABLE_RESHIPPED
4495 rajveer 2048
        order.statusDescription = "Order Reshipped"
2049
        session.commit()
4614 rajveer 2050
    elif order.status == OrderStatus.RET_PRODUCT_UNUSABLE:
4495 rajveer 2051
        new_order = __clone_order(order, False, False)
2052
        ret_order = __create_return_order(order)
4614 rajveer 2053
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE_RESHIPPED
4495 rajveer 2054
        order.statusDescription = "Order Reshipped"
2055
        session.commit()
2056
    elif order.status == OrderStatus.RET_RECEIVED_DAMAGED:
2057
        new_order = __clone_order(order, False, False)
2058
        ret_order = __create_return_order(order)
2059
        order.status = OrderStatus.RET_RESHIPPED_RCVD_DAMAGED
2060
        order.statusDescription = "Order Reshipped Received Damaged"
2061
        session.commit()
2062
    elif order.status == OrderStatus.RET_LOST_IN_TRANSIT:
2063
        new_order = __clone_order(order, False, False)
2064
        order.status = OrderStatus.RET_RESHIPPED_LOST_IN_TRANSIT
2065
        order.statusDescription = "Order Reshipped Lost In Transit"
2066
        session.commit()
2628 chandransh 2067
    else:
2068
        raise TransactionServiceException(112, "This order can't be reshipped")
2069
 
2764 chandransh 2070
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 2071
    order.new_order_id = new_order.id
2072
    session.commit()
2073
 
2074
    return new_order.id
2075
 
3226 chandransh 2076
def refund_order(order_id, refunded_by, reason):
2628 chandransh 2077
    """
4484 rajveer 2078
    If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2628 chandransh 2079
        1. Creates a refund request for batch processing.
2080
        2. Creates a return order for the warehouse executive to return the shipped material.
4484 rajveer 2081
        3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2628 chandransh 2082
 
2083
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2084
        1. Creates a refund request for batch processing.
3226 chandransh 2085
        2. Cancels the reservation of the item in the warehouse.
2086
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 2087
 
3226 chandransh 2088
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2089
        1. Cancels the reservation of the item in the warehouse.
2090
        2. Marks the current order as CANCELED.
2091
 
2092
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
2093
 
2094
    Returns True if it is successful, False otherwise.
2628 chandransh 2095
 
2096
    Throws an exception if the order with the given id couldn't be found.
2097
 
2098
    Parameters:
3226 chandransh 2099
     - order_id
2100
     - refunded_by
2101
     - reason
2628 chandransh 2102
    """
3414 chandransh 2103
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 2104
    order = get_order(order_id)
3186 chandransh 2105
 
3226 chandransh 2106
    if order.cod:
3414 chandransh 2107
        logging.info("Refunding COD order with status " + str(order.status))
4662 rajveer 2108
        status_transition = { OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2109
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2110
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2111
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2112
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2113
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2114
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2115
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2116
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2117
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2118
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2119
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2120
                     OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.COD_VERIFICATION_FAILED,
2121
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2122
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2123
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2124
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2125
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2126
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2127
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2128
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST
3366 chandransh 2129
                     }
2130
        if order.status not in status_transition.keys():
2131
            raise TransactionServiceException(114, "This order can't be refunded")
2132
 
5199 mandeep.dh 2133
        if order.status in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
3226 chandransh 2134
            __update_inventory_reservation(order)
2135
            order.statusDescription = "Order Cancelled"
3415 chandransh 2136
        elif order.status == OrderStatus.BILLED:
3413 chandransh 2137
            __create_return_order(order)
2138
            order.statusDescription = "Order Cancelled"
4486 rajveer 2139
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
5386 phani.kuma 2140
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2141
                __create_return_order(order)
4486 rajveer 2142
            order.statusDescription = "RTO Refunded"
4662 rajveer 2143
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2144
            #__create_return_order(order)
4662 rajveer 2145
            order.statusDescription = "Lost in Transit Refunded"
4479 rajveer 2146
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2147
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2148
                __create_return_order(order)
3226 chandransh 2149
            __create_refund(order)
4495 rajveer 2150
            order.statusDescription = "DOA Refunded"
2151
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2152
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2153
                __create_return_order(order)
4495 rajveer 2154
            __create_refund(order)
2155
            order.statusDescription = "Return Refunded"
4247 rajveer 2156
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5199 mandeep.dh 2157
            if order.previousStatus in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
4247 rajveer 2158
                __update_inventory_reservation(order)
2159
                order.statusDescription = "Order Cancelled on customer request"
2160
            elif order.previousStatus == OrderStatus.BILLED:
2161
                __create_return_order(order)
2162
                order.statusDescription = "Order Cancelled on customer request"
3226 chandransh 2163
    else:
4662 rajveer 2164
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2165
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2166
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2167
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2168
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2169
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2170
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2171
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2172
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2173
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2174
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2175
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2176
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2177
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2178
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2179
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2180
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2181
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2182
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2183
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
2184
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 2185
                     }
2186
        if order.status not in status_transition.keys():
2187
            raise TransactionServiceException(114, "This order can't be refunded")
2188
 
4495 rajveer 2189
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
5386 phani.kuma 2190
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2191
                __create_return_order(order)
3226 chandransh 2192
            __create_refund(order)
4495 rajveer 2193
            order.statusDescription = "RTO Refunded"
4662 rajveer 2194
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2195
            #__create_return_order(order)
4662 rajveer 2196
            __create_refund(order)
2197
            order.statusDescription = "Lost in Transit Refunded"
4495 rajveer 2198
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2199
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2200
                __create_return_order(order)
4495 rajveer 2201
            __create_refund(order)
2202
            order.statusDescription = "DOA Refunded"
2203
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2204
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2205
                __create_return_order(order)
4495 rajveer 2206
            __create_refund(order)
2207
            order.statusDescription = "Return Refunded"
5199 mandeep.dh 2208
        elif order.status in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
3226 chandransh 2209
            __update_inventory_reservation(order)
2210
            order.statusDescription = "Order Refunded"
4247 rajveer 2211
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5272 mandeep.dh 2212
            if order.previousStatus in [OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.PAYMENT_FLAGGED, OrderStatus.ACCEPTED]:
4672 rajveer 2213
                if order.previousStatus == OrderStatus.ACCEPTED:
2214
                    __create_refund(order)
4247 rajveer 2215
                __update_inventory_reservation(order)
2216
                order.statusDescription = "Order Cancelled on customer request"
2217
            elif order.previousStatus == OrderStatus.BILLED:
2218
                __create_return_order(order)
2219
                __create_refund(order)
2220
                order.statusDescription = "Order Cancelled on customer request"
2221
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
2222
            __update_inventory_reservation(order)
2223
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 2224
 
4873 mandeep.dh 2225
    # For orders that are cancelled after being billed, we need to scan in the scanned out
2226
    # inventory item and change availability accordingly
5944 mandeep.dh 2227
    inventoryClient = InventoryClient().get_client()
2228
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
5110 mandeep.dh 2229
    if warehouse.billingType == BillingType.OURS:
4873 mandeep.dh 2230
        if order.status in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH] or (order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED and order.previousStatus in [OrderStatus.BILLED, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_FROM_WH]):
2231
            lineitem = order.lineitems[0]
5944 mandeep.dh 2232
            catalogClient = CatalogClient().get_client()
5177 mandeep.dh 2233
            item = catalogClient.getItem(lineitem.item_id)
5361 mandeep.dh 2234
            warehouseClient = WarehouseClient().get_client()
5177 mandeep.dh 2235
            if ItemType.SERIALIZED == item.type:
2236
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 2237
            else:
2238
                warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4873 mandeep.dh 2239
 
3195 chandransh 2240
    order.status = status_transition[order.status]
2241
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 2242
    order.refunded_by = refunded_by
2243
    order.refund_reason = reason
4873 mandeep.dh 2244
 
2628 chandransh 2245
    session.commit()
2246
    return True
2247
 
3186 chandransh 2248
def __update_inventory_reservation(order):
3191 chandransh 2249
    '''
2250
    Reduce the reservation count for all line items of the given order.
2251
    '''
3186 chandransh 2252
    try:
5944 mandeep.dh 2253
        inventoryClient = InventoryClient().get_client()
3186 chandransh 2254
        for lineitem in order.lineitems:
5966 rajveer 2255
            inventoryClient.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3186 chandransh 2256
    except:
2257
        print "Unable to reduce reservation count"
2258
 
4220 rajveer 2259
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 2260
    current_time = datetime.datetime.now()
2261
    new_order = Order()
2262
    new_order.customer_id = order.customer_id
2263
    new_order.customer_name = order.customer_name
2264
    new_order.customer_city = order.customer_city
2265
    new_order.customer_state = order.customer_state
2266
    new_order.customer_mobilenumber = order.customer_mobilenumber
2267
    new_order.customer_pincode = order.customer_pincode
2268
    new_order.customer_address1 = order.customer_address1
2269
    new_order.customer_address2 = order.customer_address2
2270
    new_order.customer_email = order.customer_email
2271
    new_order.total_amount = order.total_amount
2272
    new_order.total_weight = order.total_weight
2273
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2274
    new_order.statusDescription = 'Submitted for Processing'
2275
    new_order.created_timestamp = current_time
5062 varun.gupt 2276
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 2277
 
2278
    new_order.transaction = order.transaction
4220 rajveer 2279
    new_order.cod = is_cod
5527 anupam.sin 2280
    new_order.orderType = order.orderType
2628 chandransh 2281
 
2282
    for line_item in order.lineitems:
2283
        litem = LineItem()
2284
        litem.item_id = line_item.item_id
2285
        litem.productGroup = line_item.productGroup
2286
        litem.brand = line_item.brand
2287
        if line_item.model_number:
2288
            litem.model_number = line_item.model_number
2289
        if line_item.model_name:    
2290
            litem.model_name = line_item.model_name
2291
        if line_item.color:
2292
            litem.color = line_item.color
2293
        if line_item.extra_info:
2294
            litem.extra_info = line_item.extra_info
2295
        litem.quantity = line_item.quantity
2296
        litem.unit_price = line_item.unit_price
2297
        litem.unit_weight = line_item.unit_weight
2298
        litem.total_price = line_item.total_price
2299
        litem.total_weight = line_item.total_weight
2300
        litem.transfer_price = line_item.transfer_price
4840 mandeep.dh 2301
        litem.dealText = line_item.dealText
2628 chandransh 2302
        litem.order = new_order
2303
 
2304
    logistics_client = LogisticsClient().get_client()
2305
    item_id = new_order.lineitems[0].item_id
5785 mandeep.dh 2306
    logistics_info = logistics_client.getLogisticsInfo(new_order.customer_pincode, item_id, is_cod, PickUpType.COURIER) #TODO: We should be able to pass another flag to suggest ignoring the inventory situation.
2628 chandransh 2307
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2308
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 2309
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 2310
    new_order.logistics_provider_id = logistics_info.providerId
2311
    new_order.airwaybill_no = logistics_info.airway_billno
2312
    new_order.tracking_id = new_order.airwaybill_no
2313
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 2314
    new_order.promised_delivery_time = new_order.expected_delivery_time
4299 rajveer 2315
 
2628 chandransh 2316
    if should_copy_billing_info:
5388 phani.kuma 2317
        new_order.vendorId = order.vendorId
2628 chandransh 2318
        new_order.invoice_number = order.invoice_number
2319
        new_order.billed_by = order.billed_by
2320
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 2321
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
5620 mandeep.dh 2322
        new_order.jacket_number = order.jacket_number
2323
        new_order.lineitems[0].serial_number = order.lineitems[0].serial_number
2324
        new_order.lineitems[0].item_number   = order.lineitems[0].item_number
2628 chandransh 2325
        new_order.accepted_timestamp = current_time
2326
        new_order.billing_timestamp = current_time    
2327
        new_order.status = OrderStatus.BILLED
2328
        new_order.statusDescription = 'Order Billed'
5966 rajveer 2329
    else:
2330
        session.commit()       
5944 mandeep.dh 2331
        inventoryClient = InventoryClient().get_client()
5966 rajveer 2332
        inventoryClient.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, sourceId, new_order.id, to_java_date(new_order.created_timestamp), to_java_date(new_order.promised_shipping_time), new_order.lineitems[0].quantity)
2628 chandransh 2333
 
2334
    return new_order
2335
 
2336
def __create_return_order(order):
2687 chandransh 2337
    ret_order = ReturnOrder(order)
2628 chandransh 2338
    return ret_order
2339
 
2340
def __create_refund(order):
4078 chandransh 2341
    payment_client = PaymentClient().get_client()
2342
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 2343
    return
2628 chandransh 2344
 
2536 chandransh 2345
def __get_order_address(order):
2346
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
2347
    if order.customer_address2:
2348
        address = address + order.customer_address2 + "\n"
2349
    address = address + order.customer_city + "\n"
2350
    address = address + order.customer_state + "\n"
2351
    address = address + "PIN " + order.customer_pincode + "\n"
2352
    address = address + "Phone: " + order.customer_mobilenumber
2353
    return address
2354
 
5767 rajveer 2355
def __get_store_address(store):
2356
    address = store.name + "\n" + store.line1 + "\n"
2357
    if store.line2:
2358
        address = address + store.line2 + "\n"
2359
    address = address + store.city + "\n"
2360
    address = address + store.state + "\n"
5802 rajveer 2361
    address = address + "PIN - " + store.pin + "\n"
5793 rajveer 2362
    if store.phone:
5802 rajveer 2363
        address = address + "Phone - " + store.phone + "\n"
5855 rajveer 2364
    address = address +  "Store timings - 11AM to 8PM (7 days)\n"
5767 rajveer 2365
    return address
2366
 
5793 rajveer 2367
def __get_store_address_html(store):
2368
    address = store.name + "<br>" + store.line1 + "<br>"
2369
    if store.line2:
2370
        address = address + store.line2 + "<br>"
2371
    address = address + store.city + "<br>"
2372
    address = address + store.state + "<br>"
5802 rajveer 2373
    address = address + "PIN - " + store.pin + "<br>"
5793 rajveer 2374
    if store.phone:
5802 rajveer 2375
        address = address + "Phone - " + store.phone + "<br>"
5855 rajveer 2376
    address = address +  "Store timings - 7 days: 11AM to 8PM  (7 days)<br>"
5793 rajveer 2377
    return address
2378
 
4815 phani.kuma 2379
def __generate_return_advice(order, warehouse, provider, filename):
2380
    if warehouse.id == 7:
2381
        executive = 'Amit Kumar'
2382
    else:
4966 phani.kuma 2383
        executive = 'Dinesh Kumar'
2536 chandransh 2384
    pdf = Canvas(filename)
2385
    pdf.setFont('Times-Bold',16)
2386
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
2387
    address_text.textLine("To")
4815 phani.kuma 2388
    address_text.textLine(executive)
2536 chandransh 2389
    for line in warehouse.location.split("\n"):
2390
        address_text.textLine(line)
2391
    address_text.textLine("PIN " + warehouse.pincode)
2392
    pdf.drawText(address_text)
2393
 
2394
    pdf.setFont('Times-Roman',12)
2395
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 2396
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 2397
    lineitem = order.lineitems[0] 
4234 rajveer 2398
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 2399
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
2400
    order_text.textLine("Order ID : " + str(order.id))
2401
    pdf.drawText(order_text)
2402
    pdf.showPage()
2403
    pdf.save()
2404
    return filename
2405
 
5806 rajveer 2406
def __push_collection_to_hotspot(order, type):
2407
    try:
2408
        logistics_client = LogisticsClient().get_client()
2409
        store = logistics_client.getPickupStore(order.pickupStoreId)
2410
        store_string = "<store>" + store.hotspotId + "</store>"
2411
        order_string = "<orderno>" + str(order.id) + "</orderno>"
2412
        collection_type = "<Type>" + type + "</Type>"
5833 rajveer 2413
        payment_mode = get_order_attribute_value(order.id, "PAYMENT_MODE")
5806 rajveer 2414
        if type == "SALE":
2415
            amount = int(order.total_amount)
2416
            ts = order.delivery_timestamp
2417
        if type == "SALE RETURN":
2418
            amount = -int(order.total_amount)
2419
            ts = order.refund_timestamp
2420
        if payment_mode == "Cash":
2421
            cash_string = "<cash>" + str(amount) + "</cash>"
2422
            card_string = "<hdfc>0</hdfc>"
2423
        if payment_mode == "Card":
2424
            cash_string = "<cash>0</cash>"
2425
            card_string = "<hdfc>" + str(amount) + "</hdfc>"
2426
        date_string = "<date>" + ts.strftime("%Y%m%d") + "</date>"
2427
        time_string = "<time>" + ts.strftime("%H%M%S") + "</time>"
2428
 
2429
        conn = httplib.HTTPConnection("182.71.104.182")
2430
        XML="""
2431
        <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
2432
          <soap:Body>
2433
            <SaholicDataTransfer xmlns="http://tempuri.org/">
2434
        """
2435
 
2436
        XML = XML + store_string + order_string + collection_type + cash_string + card_string + date_string + time_string 
2437
 
2438
        footer = """
2439
            </SaholicDataTransfer>
2440
          </soap:Body>
2441
        </soap:Envelope>
2442
        """
2443
        XML = XML + footer
2444
 
2445
        params = urllib.urlencode({'op': 'SaholicDataTransfer'})
2446
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
2447
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
2448
        conn.send(XML)
2449
        response = conn.getresponse()
2450
        print response.status, response.reason
2451
        resp = response.read()
2452
        conn.close()
2453
        print resp
2454
        if "Saved Successfully" in resp:
2455
            return True
2456
        elif "Error in Saving Data" in resp:
2457
            return False
2458
        else: 
2459
            return False
2460
    except Exception as e:
2461
        print e
2462
        return False
2463
 
2697 chandransh 2464
def get_return_orders(warehouse_id, from_date, to_date):
2465
    query = ReturnOrder.query.filter_by(processedStatus = False)
2466
    if warehouse_id != -1:
2467
        query = query.filter_by(warehouseId = warehouse_id)
2468
    if from_date:
4118 chandransh 2469
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 2470
    if to_date:
4118 chandransh 2471
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 2472
    return [return_order.to_thrift_object() for return_order in query.all()]
2473
 
5481 phani.kuma 2474
def get_all_return_orders(onlyNotProcessed, from_date, to_date):
2475
    query = ReturnOrder.query
2476
    if onlyNotProcessed:
2477
        query = query.filter_by(processedStatus = False)
2478
    if from_date:
2479
        query = query.filter(ReturnOrder.createdAt >= from_date)
2480
    if to_date:
2481
        query = query.filter(ReturnOrder.createdAt <= to_date)
2482
    return [return_order.to_thrift_object() for return_order in query.all()]
2483
 
2700 chandransh 2484
def get_return_order(id):
2485
    ret_order = ReturnOrder.get_by(orderId = id)
2486
    if ret_order is None:
2487
        raise TransactionServiceException(116, "No return order found for the given order id")
2488
    return ret_order.to_thrift_object()
2489
 
2697 chandransh 2490
def process_return(ret_order_id):
2491
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
2492
    if ret_order is None:
2493
        raise TransactionServiceException(116, "No return order found for the given order id")
2494
    ret_order.processedStatus = True
2701 chandransh 2495
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 2496
    session.commit()
2497
 
4757 mandeep.dh 2498
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
2499
    """
2500
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
2501
    the quantities for which the PO is raised.
2502
 
2503
    Parameters:
2504
     - itemIdQuantityMap
2505
     - purchaseOrderId
2506
     - warehouseId
2507
    """
3451 chandransh 2508
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 2509
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 2510
    query = query.filter_by(purchase_order_id=None)
2511
    query = query.order_by(Order.created_timestamp)
2512
    pending_orders = query.all()
4586 mandeep.dh 2513
 
2514
    for order in pending_orders:
4757 mandeep.dh 2515
        lineitem = order.lineitems[0]
2516
        if itemIdQuantityMap.has_key(lineitem.item_id):
2517
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
2518
                order.status = OrderStatus.LOW_INV_PO_RAISED
2519
                order.statusDescription = 'In Process'
2520
                order.purchase_order_id = purchaseOrderId
2521
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 2522
 
2819 chandransh 2523
    session.commit()
2524
 
3451 chandransh 2525
def update_weight(order_id, weight):
3469 chandransh 2526
    '''
2527
    Update the weight of order
2528
    '''
3451 chandransh 2529
    order = get_order(order_id)
2530
    order.total_weight = weight
3469 chandransh 2531
    lineitem = order.lineitems[0]
2532
    lineitem.total_weight = weight
2533
    lineitem.unit_weight = weight
3451 chandransh 2534
 
3469 chandransh 2535
    session.commit()
2536
    return order
2537
 
2538
def change_product(order_id, item_id):
2539
    '''
2540
    Ship a product of a different color to the customer.
2541
    '''
2542
    order = get_order(order_id)
4662 rajveer 2543
    if order.status not in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT]:
3469 chandransh 2544
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
2545
 
2546
    lineitem = order.lineitems[0]
3451 chandransh 2547
 
3469 chandransh 2548
    catalog_client = CatalogClient().get_client()
2549
 
2550
    old_item = catalog_client.getItem(lineitem.item_id)
2551
    item = catalog_client.getItem(item_id)
2552
    if old_item.catalogItemId != item.catalogItemId:
2553
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
2554
 
5944 mandeep.dh 2555
    inventoryClient = InventoryClient().get_client()
5966 rajveer 2556
    inventoryClient.reserveItemInWarehouse(item_id, order.fulfilmentWarehouseId, sourceId, order.id, to_java_date(order.created_timestamp), to_java_date(order.promised_shipping_time), order.lineitems[0].quantity)
5110 mandeep.dh 2557
    __update_inventory_reservation(order)
3469 chandransh 2558
    #TODO: Check that this new item has the same price
2559
 
2560
    lineitem.item_id = item_id
2561
    lineitem.color = item.color
2562
 
3451 chandransh 2563
    session.commit()
3469 chandransh 2564
 
2565
    order = get_order(order_id)
3451 chandransh 2566
    return order
3469 chandransh 2567
 
2568
def change_warehouse(order_id, warehouse_id):
2569
    '''
2570
    Update the warehouse which will be used to fulfil this order.
2571
    '''
2572
    order = get_order(order_id)
6019 rajveer 2573
    if order.status not in [OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT, OrderStatus.ACCEPTED]:
3469 chandransh 2574
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
2575
 
2576
    if warehouse_id == order.warehouse_id:
2577
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
2578
 
2579
    lineitem = order.lineitems[0]
2580
    catalog_client = CatalogClient().get_client()
5944 mandeep.dh 2581
    inventoryClient = InventoryClient().get_client()
3469 chandransh 2582
    try:
5944 mandeep.dh 2583
        warehouse = inventoryClient.getWarehouse(warehouse_id)
3469 chandransh 2584
    except:
2585
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 2586
 
5147 mandeep.dh 2587
    if warehouse.billingWarehouseId is None:
2588
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 2589
 
5620 mandeep.dh 2590
    # If One gives a billing warehouse for warehouse shift, we should assign order to the GOOD warehouse
2591
    # present within it with maximum availability
2592
    if warehouse.id == warehouse.billingWarehouseId:
5944 mandeep.dh 2593
        warehouses = inventoryClient.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
5147 mandeep.dh 2594
        if warehouses:
5944 mandeep.dh 2595
            itemInventory = inventoryClient.getItemInventoryByItemId(lineitem.item_id)
5147 mandeep.dh 2596
            warehouse = warehouses[0]
2597
            maxAvailability = 0
2598
            for goodWarehouse in warehouses:
2599
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
2600
                    warehouse = goodWarehouse
2601
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
2602
 
2603
            # Use preferred vendor's warehouse if not available anywhere
2604
            if not maxAvailability:
2605
                item = catalog_client.getItem(lineitem.item_id)
2606
                if item.preferredVendor:
2607
                    for goodWarehouse in warehouses:
2608
                        if goodWarehouse.vendor.id == item.preferredVendor:
2609
                            warehouse = goodWarehouse
2610
        else:
2611
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
2612
 
6007 rajveer 2613
    inventoryClient.reserveItemInWarehouse(lineitem.item_id, warehouse.id, sourceId, order.id, to_java_date(order.created_timestamp), to_java_date(order.promised_shipping_time), lineitem.quantity)
5110 mandeep.dh 2614
    __update_inventory_reservation(order)
2615
 
2616
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 2617
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 2618
    session.commit()
2619
    return order
3553 chandransh 2620
 
4647 rajveer 2621
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 2622
    '''
3994 chandransh 2623
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 2624
    '''
2625
    order = get_order(order_id)
2626
    try:
3581 chandransh 2627
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 2628
        order.delayReasonText = delayReasonText
4009 chandransh 2629
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
2630
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 2631
 
4842 rajveer 2632
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
2633
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 2634
 
3553 chandransh 2635
        session.commit()
4008 mandeep.dh 2636
 
2637
        try:
2638
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
2639
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
2640
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
2641
            session.commit()
2642
        except Exception as e:
4065 mandeep.dh 2643
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 2644
 
3553 chandransh 2645
        return True
2646
    except:
3994 chandransh 2647
        print sys.exc_info()[0]
3553 chandransh 2648
        return False
3956 chandransh 2649
 
2650
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
2651
    unprocessed_awbs = {}
2652
    for awb, amount in collected_amount_map.iteritems():
2653
        try:
2654
            order = Order.query.filter_by(airwaybill_no=awb).one()
2655
        except NoResultFound:
2656
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
2657
            continue
2658
        except MultipleResultsFound:
2659
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
2660
            continue
2661
 
2662
        if order.cod_reconciliation_timestamp:
2663
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
2664
            continue
2665
 
2666
        if order.status < OrderStatus.DELIVERY_SUCCESS:
2667
            #Order has not been delivered yet. No way we can receive the payment.
2668
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
2669
            continue
2670
 
4252 rajveer 2671
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
2672
        if abs(amount - order.total_amount) > 0.5:
3956 chandransh 2673
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
2674
            unprocessed_awbs[awb] = "Payment of Rs. " + str(amount) + " has been received against the total value of Rs. " + str(order.total_amount) + " for order: " + str(order.id)
2675
            continue
2676
 
2677
        try:
2678
            payment_client = PaymentClient().get_client()
2679
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
2680
        except Exception:
2681
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
2682
            continue
2683
 
2684
        #Payment has been recorded now. We can update the order peacefully.
2685
        order.cod_reconciliation_timestamp = datetime.datetime.now()
2686
        session.commit()
3469 chandransh 2687
 
3956 chandransh 2688
    return unprocessed_awbs
4008 mandeep.dh 2689
 
2690
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 2691
    """
2692
    Returns the list of transaction ids that require some extra processing and
2693
    which belong to a particular category. This is currently used by CRM
2694
    application. If no such transaction ids are present, it returns an empty list.
2695
    """
2696
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 2697
 
4065 mandeep.dh 2698
    if category is not None:
2699
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 2700
 
4065 mandeep.dh 2701
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 2702
 
2703
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 2704
    """
2705
    Marks a particular transaction as processed for a particular cateogory.
2706
    It essentially deletes the transaction id record for a particular
2707
    processing type category (if present) from DB.
2708
    This is currently used by CRM application.
2709
    """
4008 mandeep.dh 2710
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
2711
    session.commit()
2712
 
4018 chandransh 2713
def get_item_wise_risky_orders_count():
2714
    """
2715
    Returns a map containing the number of risky orders keyed by item id. A risky order
2716
    is defined as one whose shipping date is about to expire.
2717
    """
2718
    item_wise_risky_orders_count = {}
4019 chandransh 2719
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 2720
    orders = Order.query.filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.ACCEPTED]))).filter(Order.expected_shipping_time <= shipping_cutoff_time).all()
2721
    for order in orders:
2722
        for lineitem in order.lineitems:
2723
            quantity = lineitem.quantity
2724
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
2725
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
2726
 
2727
            item_wise_risky_orders_count[lineitem.item_id] = quantity
2728
    return item_wise_risky_orders_count
2729
 
4324 mandeep.dh 2730
def update_shipment_address(order_id, address_id):
2731
    """
2732
    Updates shipment address of an order. Delivery and shipping date estimates
2733
    etc. are also updated here.
2734
 
2735
    Throws TransactionServiceException in case address change is not
2736
    possible due to certain reasons such as new pincode in address is
2737
    not serviceable etc.
2738
 
2739
    Parameters:
2740
     - orderId
2741
     - addressId
2742
    """
2743
    user_client = UserClient().get_client()
2744
    address     = user_client.getAddressById(address_id)
2745
    order       = get_order(order_id)
2746
 
4630 mandeep.dh 2747
    type = DeliveryType.PREPAID
2748
    if order.cod:
2749
        type = DeliveryType.COD
2750
 
4324 mandeep.dh 2751
    logistics_client = LogisticsClient().get_client()
5886 mandeep.dh 2752
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type)
4324 mandeep.dh 2753
 
2754
    # Check for new estimate. Raise exception if new address is not serviceable
2755
    if logistics_info.deliveryTime == -1:
2756
        raise TransactionServiceException(1, 'Location not serviceable')
2757
 
2758
    # COD services are not available everywhere
2759
    if order.cod:
4868 rajveer 2760
        if not logistics_info.codAllowed:
4324 mandeep.dh 2761
            raise TransactionServiceException(2, 'COD service not available')
2762
 
5593 mandeep.dh 2763
    if logistics_info.providerId != order.logistics_provider_id:
5887 mandeep.dh 2764
        logistics_info = logistics_client.getLogisticsInfo(address.pin, order.lineitems[0].item_id, type, PickUpType.COURIER)
5593 mandeep.dh 2765
        order.tracking_id = logistics_info.airway_billno
2766
        order.airwaybill_no = logistics_info.airway_billno
2767
        order.logistics_provider_id = logistics_info.providerId
2768
 
4324 mandeep.dh 2769
    current_time = datetime.datetime.now()
2770
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2771
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2772
 
2773
    order.customer_name         = address.name
2774
    order.customer_pincode      = address.pin
2775
    order.customer_address1     = address.line1
2776
    order.customer_address2     = address.line2
2777
    order.customer_city         = address.city
2778
    order.customer_state        = address.state
2779
    order.customer_mobilenumber = address.phone
2780
 
2781
    if order.cod:
2782
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2783
    else:
2784
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2785
 
2786
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
2787
    order.promised_shipping_time = order.expected_shipping_time
2788
    order.promised_delivery_time = order.expected_delivery_time 
2789
 
2790
    session.commit()
2791
 
4247 rajveer 2792
def mark_order_cancellation_request_received(orderId):
2793
    """
2794
    Mark order as cancellation request received. If customer sends request of cancellation of
2795
    a particular order, this method will be called. It will just change status of the order
2796
    depending on its current status. It also records the previous status, so that we can move
2797
    back to that status if cancellation request is denied.
2798
 
2799
    Parameters:
2800
     - orderId
2801
    """
4662 rajveer 2802
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2803
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
2804
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 2805
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2806
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
2807
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2808
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2809
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2810
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
2811
             }
4662 rajveer 2812
 
2813
    order = get_order(orderId)
4247 rajveer 2814
    if order.status not in status_transition.keys():
2815
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
2816
 
4662 rajveer 2817
 
4247 rajveer 2818
    order.previousStatus = order.status
2819
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
2820
    order.statusDescription = "Cancellation request received from user"
2821
    session.commit()
2822
 
4662 rajveer 2823
def mark_order_as_lost_in_transit(orderId):
2824
    """
2825
    Parameters:
2826
     - orderId
2827
    """
2828
    order = get_order(orderId)
4910 phani.kuma 2829
    if order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY, OrderStatus.REACHED_DESTINATION_CITY, OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE]:
4662 rajveer 2830
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
2831
    order.status = OrderStatus.LOST_IN_TRANSIT
2832
    order.statusDescription = "Lost in Transit"
2833
    session.commit()
2834
 
4258 rajveer 2835
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 2836
    """
4258 rajveer 2837
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
2838
    Changed transaction and all orders status to payment accepted.
4247 rajveer 2839
 
2840
    Parameters:
4258 rajveer 2841
     - transactionId
4247 rajveer 2842
    """
4258 rajveer 2843
    transaction = get_transaction(transactionId)
2844
    transaction.status = TransactionStatus.AUTHORIZED
2845
    for order in transaction.orders:
2846
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2847
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 2848
    session.commit()
2849
 
4259 anupam.sin 2850
def refund_transaction(transactionId, refundedBy, reason):
2851
    """
2852
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
2853
    need to be cancelled
2854
 
2855
    Parameters:
2856
     - transactionId
2857
    """
2858
    transaction = get_transaction(transactionId)
2859
    transaction.status = TransactionStatus.FAILED
2860
    for order in transaction.orders:
2861
        refund_order(order.id, refundedBy, reason)
2862
    session.commit()
2863
 
4247 rajveer 2864
def mark_order_cancellation_request_denied(orderId):
2865
    """
4283 anupam.sin 2866
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 2867
 
2868
    Parameters:
2869
     - orderId
2870
    """
2871
    order = get_order(orderId)
2872
    order.status = order.previousStatus
2873
    order.previousStatus = None
2874
    order.statusDescription = "Cancellation request denied"
2875
    session.commit()
2876
 
2877
def mark_order_cancellation_request_confirmed(orderId):
2878
    """
2879
    If we decide to to cancel order, CRM will call this method to move the status of order to
2880
    cancellation request confirmed. After this OM will be able to cancel the order.
2881
 
2882
    Parameters:
2883
     - orderId
2884
    """
2885
    order = get_order(orderId)
2886
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
2887
    order.statusDescription = "Cancellation request confirmed"
2888
    session.commit()
2889
 
4285 rajveer 2890
def accept_orders_for_item_id(itemId, inventory):
2891
    """
2892
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
2893
    given order is not a COD order, it also captures the payment if the same has not been captured.
2894
 
2895
    Parameters:
2896
     - itemId
2897
     - inventory
2898
    """
4938 rajveer 2899
    orders = Order.query.filter(Order.warehouse_id == 5).filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS]))).order_by(Order.expected_shipping_time).all()
4285 rajveer 2900
    for order in orders:
4301 rajveer 2901
        if inventory > 0:
2902
            lineitem = order.lineitems[0]
2903
            if itemId == lineitem.item_id:
2904
                try:
2905
                    accept_order(order.id)
2906
                    inventory = inventory - lineitem.quantity
2907
                except:
2908
                    logging.info("Unable to accept the order")
2909
        else:
2910
            order_outofstock(order.id)
4285 rajveer 2911
    return
2912
 
4607 rajveer 2913
def get_slipped_sipping_date_orders():
4662 rajveer 2914
    return Order.query.filter(Order.status.in_(tuple([OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS, OrderStatus.ACCEPTED, OrderStatus.BILLED]))).filter(Order.promised_shipping_time <= datetime.datetime.now()).order_by(Order.promised_shipping_time).all()
4709 rajveer 2915
 
2916
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
2917
    return Order.query.filter(Order.status == OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY).filter(Order.refund_timestamp >= cancelDateFrom).filter(Order.refund_timestamp <= cancelDateTo).all()
4607 rajveer 2918
 
4369 rajveer 2919
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
2920
    if isReminder:
2921
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2922
    else:
2923
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2924
 
2925
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2926
    for order in orders:
2927
        lineitem = order.lineitems[0]
2928
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2929
            if estimate > 0:
2930
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2931
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 2932
            order.statusDescription = "PO Raised"
4303 rajveer 2933
            quantity = quantity - lineitem.quantity
2934
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
2935
            session.commit()
2936
 
4369 rajveer 2937
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
2938
    if isReminder:
2939
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2940
    else:
2941
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2942
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2943
    for order in orders:
2944
        lineitem = order.lineitems[0]
2945
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2946
            if estimate > 0:
2947
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2948
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 2949
            order.statusDescription = "Reversal Initiated"
4303 rajveer 2950
            quantity = quantity - lineitem.quantity
2951
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
2952
            session.commit()
2953
 
4369 rajveer 2954
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
2955
    if isReminder:
2956
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2957
    else:
2958
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2959
 
2960
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2961
    for order in orders:
2962
        lineitem = order.lineitems[0]
2963
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2964
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 2965
            order.statusDescription = "Not Available"
4303 rajveer 2966
            quantity = quantity - lineitem.quantity
2967
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
2968
            session.commit()
2969
 
2970
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 2971
    orderInv = OrderInventory.get_by(order_id=order.id)
2972
    if not orderInv:
2973
        orderInv = OrderInventory()
2974
        orderInv.order = order
4303 rajveer 2975
    orderInv.hotspotAction = hotspotAction  
2976
    orderInv.estimate = estimate
2977
    orderInv.itemId = itemId
2978
    orderInv.timestamp = datetime.datetime.now()
2979
    orderInv.quantity = quantity
2980
 
4556 mandeep.dh 2981
'''    
4369 rajveer 2982
def mark_orders_as_timeout(vendorId):
2983
    ret_timeouts = {}
2984
    orderInvs = OrderInventory.query.all()
2985
    for orderInv in orderInvs:
2986
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
2987
            if not ret_timeouts.has_key(orderInv.itemId):
2988
                timeout = TimeoutSummary()
2989
                ret_timeouts[orderInv.itemId] = timeout
2990
            else:
2991
                timeout = ret_timeouts.get(orderInv.itemId)
2992
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2993
                if timeout.poRaised:
2994
                    timeout.poRaised += 1
2995
                else:
2996
                    timeout.poRaised = 1
2997
 
2998
                if timeout.poEstimate:
2999
                    timeout.poEstimate += orderInv.estimate
3000
                else:
3001
                    timeout.poEstimate = orderInv.estimate
3002
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
3003
                orderInv.order.statusDescription = "PO Raised Timeout"
3004
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3005
                if timeout.reversalInitiated:
3006
                    timeout.reversalInitiated += 1
3007
                else:
3008
                    timeout.reversalInitiated = 1
3009
 
3010
                if timeout.reversalEstimate:
3011
                    timeout.reversalEstimate += orderInv.estimate
3012
                else:
3013
                    timeout.reversalEstimate = orderInv.estimate
3014
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
3015
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
3016
            else:
3017
                orderInv.delete()
3018
    session.commit()
3019
    return ret_timeouts
4556 mandeep.dh 3020
'''
3021
 
3022
 
3023
def mark_orders_as_timeout(vendorId):
3024
    ret_timeouts = {}
3025
    orderInvs = OrderInventory.query.all()
3026
    for orderInv in orderInvs:
3027
        if not ret_timeouts.has_key(orderInv.itemId):
3028
            timeout = TimeoutSummary()
3029
            ret_timeouts[orderInv.itemId] = timeout
3030
        else:
3031
            timeout = ret_timeouts.get(orderInv.itemId)
3032
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3033
            if timeout.poRaised:
3034
                timeout.poRaised += 1
3035
            else:
3036
                timeout.poRaised = 1
3037
 
3038
            if timeout.poEstimate:
3039
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
3040
            else:
3041
                timeout.poEstimate = orderInv.estimate
3042
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3043
            if timeout.reversalInitiated:
3044
                timeout.reversalInitiated += 1
3045
            else:
3046
                timeout.reversalInitiated = 1
3047
 
3048
            if timeout.reversalEstimate:
3049
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
3050
            else:
3051
                timeout.reversalEstimate = orderInv.estimate
3052
        orderInv.order.status = OrderStatus.INVENTORY_LOW
3053
        orderInv.order.statusDescription = "Low Inventory"
3054
        orderInv.delete()
3055
    session.commit()
3056
    return ret_timeouts
3057
 
4386 anupam.sin 3058
def get_order_for_awb(awb):
3059
    order = Order.get_by(airwaybill_no=awb)
3060
    if not order:
3061
        raise TransactionServiceException(108, "no such order")
3062
 
3063
    return order
4369 rajveer 3064
 
4910 phani.kuma 3065
def get_orders_for_provider_for_status(provider_id, order_status_list):
3066
    if not provider_id or not order_status_list:
4506 phani.kuma 3067
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 3068
    doa_provider = False
3069
    for order_status in order_status_list:
3070
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
3071
            doa_provider = True
3072
    if doa_provider:
3073
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 3074
    else:
4910 phani.kuma 3075
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 3076
    return query.all()
4386 anupam.sin 3077
 
4600 varun.gupt 3078
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 3079
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
3080
 
3081
    if vendor_id:
3082
        query = query.filter_by(vendorId = vendor_id)
3083
 
4600 varun.gupt 3084
    if billing_date_from:
3085
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 3086
 
4600 varun.gupt 3087
    if billing_date_to:
3088
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 3089
 
4600 varun.gupt 3090
    return query.all()
3091
 
5481 phani.kuma 3092
def get_billed_orders(vendor_id, onlyVendorNotPaid, billing_date_from, billing_date_to):
5386 phani.kuma 3093
    query = Order.query.filter(Order.billing_timestamp != None)
5481 phani.kuma 3094
 
3095
    if onlyVendorNotPaid:
5488 phani.kuma 3096
        query = query.filter_by(vendor_paid = False)
5481 phani.kuma 3097
 
5386 phani.kuma 3098
    if vendor_id != -1:
3099
        query = query.filter_by(vendorId = vendor_id)
3100
 
5481 phani.kuma 3101
    if billing_date_from:
3102
        query = query.filter(Order.billing_timestamp >= billing_date_from)
3103
 
3104
    if billing_date_to:
3105
        query = query.filter(Order.billing_timestamp <= billing_date_to)
3106
 
4885 varun.gupt 3107
    return query.all()
4875 varun.gupt 3108
 
4600 varun.gupt 3109
def save_bluedart_settlements(map_awb_and_amount):
3110
    payment_client = PaymentClient().get_client()
3111
 
3112
    for awb, amount in map_awb_and_amount.iteritems():
3113
        order = Order.get_by(airwaybill_no = awb)
3114
 
3115
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
3116
        settlement = PaymentSettlement()
3117
        settlement.paymentId = payment.paymentId
3118
        settlement.paymentGatewayId = payment.gatewayId
3119
        settlement.netCollection = amount
3120
        session.commit()
3121
 
4905 varun.gupt 3122
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 3123
    originalOrderId = None
3124
    if paymentGatewayId == 4:
3125
        cod_order = Order.get_by(id = referenceId)
3126
        if cod_order.originalOrderId:
3127
            originalOrderId = cod_order.originalOrderId
3128
        else:
3129
            originalOrderId = referenceId
4600 varun.gupt 3130
    settlement = PaymentSettlement()
3131
    settlement.settlementDate = settlementDate
3132
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 3133
    if originalOrderId is not None:
3134
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 3135
    settlement.referenceId = referenceId
4600 varun.gupt 3136
    settlement.serviceTax = serviceTax
3137
    settlement.otherCharges = otherCharges
3138
    settlement.netCollection = netCollection
3139
    session.commit()
3140
 
5386 phani.kuma 3141
def get_settlement_for_Prepaid(reference_id, is_refund = False):
3142
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 3143
 
5189 varun.gupt 3144
    if is_refund:
3145
        query = query.filter(PaymentSettlement.netCollection < 0)
3146
    else:
3147
        query = query.filter(PaymentSettlement.netCollection > 0)
3148
 
5386 phani.kuma 3149
    return query.first()
3150
 
3151
def get_settlement_for_Cod(orderId, is_refund = False):
3152
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 3153
 
5386 phani.kuma 3154
    if is_refund:
3155
        query = query.filter(PaymentSettlement.netCollection < 0)
3156
    else:
3157
        query = query.filter(PaymentSettlement.netCollection > 0)
3158
 
5189 varun.gupt 3159
    return query.first()
4600 varun.gupt 3160
 
3161
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
5551 phani.kuma 3162
    summary = EBSSettlementSummary.query.filter_by(settlementId = settlement_id).first()
5481 phani.kuma 3163
    if summary is None:
3164
        summary = EBSSettlementSummary()
3165
        summary.settlementId = settlement_id
3166
        summary.settlementDate = settlement_date
3167
        summary.transactionDateFrom = transaction_date_from
3168
        summary.transactionDateTo = transaction_date_to
3169
        summary.amount = amount
3170
        summary.detailsUploaded = False
3171
        session.commit()
4600 varun.gupt 3172
 
3173
def get_ebs_settlement_summaries():
3174
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
3175
    summary_map = {}
3176
 
3177
    for summary in summaries:
3178
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
3179
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
3180
 
3181
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
3182
 
3183
    return summary_map
3184
 
3185
def get_ebs_settlement_date(settlement_id):
3186
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3187
 
3188
    if summary:
3189
        return summary.settlementDate
3190
 
3191
def mark_ebs_settlement_uploaded(settlement_id):
3192
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3193
 
3194
    if summary:
3195
        summary.detailsUploaded = True
3196
        session.commit()
4715 varun.gupt 3197
 
3198
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
3199
    query = PaymentSettlement.query
4600 varun.gupt 3200
 
4715 varun.gupt 3201
    if settlement_date_from:
3202
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
3203
 
3204
    if settlement_date_to:
3205
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
3206
 
4749 varun.gupt 3207
    if is_refund is True:
3208
        query = query.filter(PaymentSettlement.netCollection < 0.0)
3209
    else:
3210
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 3211
 
4749 varun.gupt 3212
    return query.all()
4715 varun.gupt 3213
 
3214
def get_reshipped_order_ids(order_ids):
3215
    reshipped_order_ids = []
3216
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
3217
 
4749 varun.gupt 3218
def get_shipping_confirmation_email_body(order):
3219
 
3220
    html = """
3221
<html>
3222
<body>
3223
<div>
3224
    <p>Dear Customer,</p>
3225
    <p>
4885 varun.gupt 3226
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 3227
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
4749 varun.gupt 3228
    </p>
3229
    <p>
3230
        Expected delivery date for your order is $expected_delivery_date. 
3231
        The product can be delivered to you between business hours of 10am to 6pm. 
3232
        You can login to your account on our site and under "Open Orders", please click the AWB and check the current shipment updates for your product.
3233
    </p>
3234
    <p>
5573 amit.gupta 3235
        For scheduling the delivery of your product at some specific timings, we recommend you to contact the helpline for $courier_name with your complete AWB#.
4749 varun.gupt 3236
    </p>
5139 varun.gupt 3237
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 3238
    <p>
3239
        Warm Regards,<br />
6029 rajveer 3240
        $source_name Team
4749 varun.gupt 3241
    </p>
4750 varun.gupt 3242
</div>
4749 varun.gupt 3243
</body>
3244
</html>
3245
    """
5573 amit.gupta 3246
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}}
5139 varun.gupt 3247
    provider_name = logistics_providers[order.logistics_provider_id]['name']
3248
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
3249
 
5868 rajveer 3250
    lclient = LogisticsClient().get_client()
3251
    logistics_info = lclient.getLogisticsEstimation(order.lineitems[0].item_id, order.customer_pincode, DeliveryType.PREPAID)
4749 varun.gupt 3252
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 3253
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
4749 varun.gupt 3254
    product = "%s %s %s" % (order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number)
5868 rajveer 3255
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (logistics_info.deliveryTime - logistics_info.shippingTime)))
4885 varun.gupt 3256
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
6029 rajveer 3257
    info = dict(order_id = order.id, product_name = product, shipping_datetime = shipping_date, awb = order.airwaybill_no, expected_delivery_date = new_expected_delivery_date, courier_name = provider_name, courier_phone = provider_phone, source_name = source_name)
4885 varun.gupt 3258
    return Template(html).substitute(info)
4749 varun.gupt 3259
 
5832 rajveer 3260
def enqueue_shipping_confirmation_email(order):
4915 varun.gupt 3261
    # Calling helper service on production
3262
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5832 rajveer 3263
    try:
3264
        emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
3265
        emailBody = get_shipping_confirmation_email_body(order)
5866 rajveer 3266
        helperClient.saveUserEmailForSending([order.customer_email], None, emailSubject, emailBody, str(order.id), 'ShippingConfirmation', [], [])
5832 rajveer 3267
    except Exception as e:
3268
        print e
5139 varun.gupt 3269
 
4915 varun.gupt 3270
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 3271
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
3272
    query = query.filter(Order.created_timestamp >= start_date)
3273
    query = query.filter(Order.created_timestamp <= end_date)
3274
    return query.all()
4915 varun.gupt 3275
 
5067 varun.gupt 3276
def get_order_ids_for_status(status, start_datetime, end_datetime):
3277
    query = Order.query.filter(Order.status == status)
3278
    query = query.filter(Order.created_timestamp >= start_datetime)
3279
    query = query.filter(Order.created_timestamp <= end_datetime)
3280
    return query.all()
3281
 
5099 varun.gupt 3282
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 3283
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 3284
 
5139 varun.gupt 3285
    if paid_order.originalOrderId is None:
3286
        paid_order.vendor_paid = True
5099 varun.gupt 3287
        session.commit()
5139 varun.gupt 3288
 
3289
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
3290
            order.vendor_paid = True
3291
            session.commit()
3292
    else:
5208 varun.gupt 3293
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 3294
 
5208 varun.gupt 3295
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 3296
            order.vendor_paid = True
3297
            session.commit()
3298
 
3299
        original_order = Order.get_by(id = original_order_id)
3300
        if original_order:  original_order.vendor_paid = True
3301
        session.commit()
5348 anupam.sin 3302
 
3303
def update_COD_agent(agentEmailId, orderId):
3304
    order = Order.get_by(id=orderId)
3305
    if not order:
3306
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
3307
    agent = CodVerificationAgent()
3308
    agent.orderId = orderId
3309
    agent.verificationAgent = agentEmailId
3310
    session.commit()
3311
 
5099 varun.gupt 3312
 
5386 phani.kuma 3313
def update_order_only_as_paid_to_vendor(order_id):
3314
    paid_order = Order.get_by(id = order_id)
3315
    if paid_order is None:
3316
        raise TransactionServiceException(116, "No order found for the given order id")
3317
    paid_order.vendor_paid = True
3318
    session.commit()
3319
 
5208 varun.gupt 3320
def get_refunded_orders_marked_paid():
3321
    orderStatusGroup = OrderStatusGroups()
3322
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
3323
 
5447 anupam.sin 3324
def get_all_verification_agents(minOrderId, maxOrderId):
3325
    return CodVerificationAgent.query.filter(CodVerificationAgent.orderId >= minOrderId).filter(CodVerificationAgent.orderId <= maxOrderId).all()
3326
 
5527 anupam.sin 3327
def get_all_attributes_for_order_id(orderId):
3328
    return Attribute.query.filter(Attribute.orderId == orderId).all()
3329
 
3330
def set_order_attribute_for_transaction(transactionId, t_attribute):
3331
    for order in Order.query.filter_by(transaction_id = transactionId).all():
3332
        attribute = Attribute()
3333
        attribute.orderId = order.id
3334
        attribute.name = t_attribute.name
3335
        attribute.value = t_attribute.value
3336
        session.commit()
5593 mandeep.dh 3337
 
5558 mandeep.dh 3338
def accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
5944 mandeep.dh 3339
    inventoryClient = InventoryClient().get_client()
3340
    inventory = inventoryClient.getItemInventoryByItemId(itemId)
5684 mandeep.dh 3341
    orders = Order.query.filter(Order.fulfilmentWarehouseId != fulfilmentWarehouseId).filter(Order.warehouse_id == billingWarehouseId).filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.COD_VERIFICATION_PENDING, OrderStatus.ACCEPTED, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS]))).order_by(Order.expected_shipping_time).all()
5558 mandeep.dh 3342
    for order in orders:
5593 mandeep.dh 3343
        lineitem = order.lineitems[0]
5558 mandeep.dh 3344
        if lineitem.item_id == itemId and lineitem.quantity <= quantity:
5944 mandeep.dh 3345
            warehouse = inventoryClient.getWarehouse(order.fulfilmentWarehouseId)
5684 mandeep.dh 3346
            if not warehouse.billingWarehouseId and warehouse.warehouseType == WarehouseType.THIRD_PARTY:
3347
                if (inventory.availability[fulfilmentWarehouseId] >= inventory.reserved[fulfilmentWarehouseId] + lineitem.quantity) and inventory.availability[order.fulfilmentWarehouseId] < inventory.reserved[order.fulfilmentWarehouseId]:
5966 rajveer 3348
                    inventoryClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3349
                    inventoryClient.reserveItemInWarehouse(itemId, fulfilmentWarehouseId, sourceId, order.id, to_java_date(order.created_timestamp), to_java_date(order.promised_shipping_time), lineitem.quantity)
5684 mandeep.dh 3350
                    order.fulfilmentWarehouseId = fulfilmentWarehouseId
5558 mandeep.dh 3351
                    quantity -= lineitem.quantity
5684 mandeep.dh 3352
                    session.commit()
5593 mandeep.dh 3353
                    if not quantity:
3354
                        break
5558 mandeep.dh 3355
 
6031 rajveer 3356
def get_recharge_order(rechargeOrderId):
6048 rajveer 3357
    return RechargeOrder.get_by(id = rechargeOrderId)
6031 rajveer 3358
 
3359
def get_recharge_orders(userId):
3360
    return RechargeOrder.query.filter_by(userId = userId).all()
3361
 
6279 rajveer 3362
def update_recharge_order_status(rechargeOrderId, rechargeOrderStatus, refundDate=None):
6031 rajveer 3363
    recharge_order = get_recharge_order(rechargeOrderId)
3364
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_FAILED:
3365
        recharge_order.status = RechargeOrderStatus.PAYMENT_FAILED
3366
        session.commit()
3367
        return True
6214 rajveer 3368
 
3369
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED:
3370
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
3371
        session.commit()
3372
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
3373
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount, recharge_order.id)
3374
        enqueue_recharge_info_email(recharge_order)
3375
        return True
3376
 
3377
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3378
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
3379
        session.commit()
6285 rajveer 3380
        gvs = allocate_gift_voucher(recharge_order)
3381
        enqueue_recharge_info_email(recharge_order, gvs)
6214 rajveer 3382
        return True
3383
 
6279 rajveer 3384
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3385
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED
3386
        order.responseTimestamp = refundDate
3387
        session.commit()
3388
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
3389
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount, recharge_order.id)
3390
        enqueue_recharge_info_email(recharge_order)
3391
        return True
3392
 
6031 rajveer 3393
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6285 rajveer 3394
        gvs = {}
6206 rajveer 3395
        recharge_order.status = RechargeOrderStatus.PAYMENT_SUCCESSFUL
3396
        session.commit()
6031 rajveer 3397
        if recharge_order.walletAmount > 0:
3398
            wallet = get_user_wallet(recharge_order.userId)
3399
            if wallet and wallet.amount >= recharge_order.walletAmount:
3400
                update_amount_in_wallet(recharge_order.userId, -recharge_order.walletAmount, recharge_order.id)
3401
            else:
3402
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount, recharge_order.id)
3403
                raise TransactionServiceException(103, 'Wallet amount has already been used')
3404
 
6092 rajveer 3405
        try:
3406
            if activate_recharge_txn(recharge_order):
3407
                recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
3408
                session.commit()
6285 rajveer 3409
                gvs = allocate_gift_voucher(recharge_order)
6092 rajveer 3410
                return True
3411
            else:
3412
                update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
3413
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount, recharge_order.id)
3414
                session.commit()
3415
                return False
3416
        except:
3417
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
3418
            transaction_requiring_extra_processing.category = 'RECHARGE_UNKNOWN'
3419
            transaction_requiring_extra_processing.transaction_id = recharge_order.transaction_id
6031 rajveer 3420
            session.commit()
3421
            return False
6102 rajveer 3422
        finally:
6285 rajveer 3423
            enqueue_recharge_info_email(recharge_order, gvs)
6102 rajveer 3424
 
6031 rajveer 3425
 
6285 rajveer 3426
def allocate_gift_voucher(recharge_order):            
3427
    totalAmount = recharge_order.totalAmount
3428
    gvs = {}
6287 rajveer 3429
    return gvs
6285 rajveer 3430
    if totalAmount > 100:
3431
        totalAmount=500 if totalAmount > 500 else totalAmount
3432
        try:
3433
            pc = PromotionClient().get_client()
3434
            enddate = datetime.datetime.now() + datetime.timedelta(days=60)
3435
            while totalAmount > 0:
3436
                gvAmount = totalAmount if totalAmount < 250 else 250
3437
                totalAmount = totalAmount - gvAmount
3438
                gv = pc.createCoupon(26, to_java_date(enddate), recharge_order.userEmailId, gvAmount, 1)
3439
                gvs[gv] = gvAmount  
3440
        except:
3441
            print "Not able to create gift voucher for user " + recharge_order.userEmailId
3442
    return gvs     
3443
 
6048 rajveer 3444
def activate_recharge_txn(recharge_order):
3445
    if isinstance(recharge_order, MobileRechargeOrder):
3446
        rechargeType = 'MTP'
3447
        deviceNumber = recharge_order.mobileNumber
3448
        strProviderCode = get_provider_code(recharge_order.mobileOperatorId)
6161 rajveer 3449
        plan = recharge_order.rechargePlan
6048 rajveer 3450
    if isinstance(recharge_order, DTHRechargeOrder):
3451
        rechargeType = 'RCH'
3452
        deviceNumber = recharge_order.dthAccountNumber
3453
        strProviderCode = get_provider_code(recharge_order.dthOperatorId)
6161 rajveer 3454
        plan = ''
3455
    retStatus, retCode, spiceTID, description = RechargeService.rechargeDevice(recharge_order.id, rechargeType, strProviderCode, deviceNumber, recharge_order.totalAmount, plan)
6231 rajveer 3456
    recharge_order.spiceTID = spiceTID
3457
    recharge_order.responseTimestamp = datetime.datetime.now()
3458
    recharge_order.description = description
3459
    session.commit()
6092 rajveer 3460
    if retCode == '00' and retStatus == 'S':
3461
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
3462
        session.commit()
3463
        return True
6259 rajveer 3464
    elif retCode in ('STO', 'US', 'UP') and retStatus == 'S':
6231 rajveer 3465
        raise TransactionServiceException(111, "No response from operator within specified time")
6092 rajveer 3466
    else:
3467
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
6265 rajveer 3468
        if retCode in ('SVAI', 'SVIA', 'AI', 'IA', 'EAI', 'SVEAI'):
3469
            recharge_order.description = "Invalid Amount"
3470
        elif retCode in ('ECL', 'SVECL', 'SCL'):
3471
            recharge_order.description = "Customer Exceeded Daily Limit"
3472
        elif retCode in ('CI', 'ECI', 'ESP', 'SVCI', 'SVECI', 'SVESP', 'SV_ECI', 'SV ECI'):
3473
            recharge_order.description = "Invalid Mobile Number"
6092 rajveer 3474
        session.commit()
6048 rajveer 3475
        return False
6031 rajveer 3476
 
6092 rajveer 3477
 
6031 rajveer 3478
def get_user_wallet(userId):
3479
    wallet = UserWallet.get_by(userId = userId)
3480
    if not wallet:
3481
        wallet = UserWallet()
3482
        wallet.amount = 0
3483
        wallet.userId = userId
3484
    return wallet
3485
 
3486
def get_user_wallet_history(userId):
3487
    wallet = get_user_wallet(userId)
3488
    if wallet.id:
3489
        return UserWalletHistory.query.filter_by(wallet = wallet).all()
3490
    else:
3491
        return []
3492
 
6125 rajveer 3493
def get_provider(providerId):
3494
    return ServiceProvider.query.filter_by(id = providerId).one()
3495
 
6048 rajveer 3496
def get_provider_code(providerId):
3497
    return ServiceProvider.query.filter_by(id = providerId).one().code
6031 rajveer 3498
 
6049 rajveer 3499
def get_provider_id(providerCode):
3500
    return ServiceProvider.query.filter_by(code = providerCode).one().id
3501
 
6206 rajveer 3502
def get_service_providers(recharge_type, only_active):
3503
    query = ServiceProvider.query.filter_by(type = recharge_type)
3504
    if only_active:
3505
        query = query.filter_by(status = only_active)
3506
    providers = query.all()
6048 rajveer 3507
    serviceProviders = {}
3508
    for provider in providers:
3509
        serviceProviders[provider.id] = provider.name
3510
    return serviceProviders
3511
 
6049 rajveer 3512
def get_service_provider_for_device(rechargeType, deviceNumber):
3513
    if rechargeType == RechargeType.MOBILE:
3514
        serviceType = 'MTP'
3515
    if rechargeType == RechargeType.DTH:
3516
        serviceType = 'RCH'
6048 rajveer 3517
 
6049 rajveer 3518
    try:    
6235 rajveer 3519
        providerCode, operatorCircle = RechargeService.checkServiceProviderApi(serviceType, deviceNumber)
6092 rajveer 3520
        if providerCode == 'SNS' or providerCode == '':
3521
            providerId = 0
3522
        else:
3523
            providerId = get_provider_id(providerCode)
6049 rajveer 3524
    except:
6092 rajveer 3525
        providerId = -1
3526
 
6289 anupam.sin 3527
    deviceNumberInfo = DeviceNumberInfo()
3528
    deviceNumberInfo.circleName = operatorCircle
3529
    deviceNumberInfo.operatorId = providerId
3530
    return deviceNumberInfo
6269 rajveer 3531
 
3532
def validate_recharge(rechargeType, deviceNumber):
3533
    if get_service_provider_for_device(rechargeType, deviceNumber) == -1:
3534
        return "Oops! There seems to be a problem. Please try after some time"
6271 rajveer 3535
    allcounts, successcounts  = get_previous_transactions(rechargeType, deviceNumber)
6269 rajveer 3536
    if allcounts >= 15 or successcounts >= 5:
3537
        return "You have exceeded daily limit for this mobile number."
3538
    return "SUCCESS"
6049 rajveer 3539
 
6271 rajveer 3540
def get_previous_transactions(rechargeType, deviceNumber):
3541
    limittime = datetime.datetime.now() - datetime.timedelta(hours=24)
3542
    if rechargeType == RechargeType.MOBILE:
3543
        allcounts = session.query(func.count(MobileRechargeOrder.mobileNumber)).filter(MobileRechargeOrder.mobileNumber == deviceNumber).filter(MobileRechargeOrder.creationTimestamp  > limittime).scalar()
3544
        successcounts = session.query(func.count(MobileRechargeOrder.mobileNumber)).filter(MobileRechargeOrder.mobileNumber == deviceNumber).filter(MobileRechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).filter(MobileRechargeOrder.creationTimestamp > limittime).scalar()
3545
    else:
3546
        allcounts = session.query(func.count(DTHRechargeOrder.dthAccountNumber)).filter(DTHRechargeOrder.dthAccountNumber == deviceNumber).filter(MobileRechargeOrder.creationTimestamp  > limittime).scalar()
3547
        successcounts = session.query(func.count(DTHRechargeOrder.dthAccountNumber)).filter(DTHRechargeOrder.dthAccountNumber == deviceNumber).filter(DTHRechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).filter(MobileRechargeOrder.creationTimestamp > limittime).scalar()
6269 rajveer 3548
    return allcounts, successcounts    
3549
 
6031 rajveer 3550
def update_amount_in_wallet(userId, amount, orderId):
3551
    if amount == 0:
3552
        return
3553
    wallet = get_user_wallet(userId)
3554
    wallet.amount = wallet.amount + amount
3555
 
3556
    history = UserWalletHistory()
3557
    history.amount = amount
3558
    history.orderId = orderId
3559
    history.wallet = wallet
3560
    history.timestamp = datetime.datetime.now()
3561
    session.commit()
6056 amit.gupta 3562
 
6094 rajveer 3563
def get_recharge_orders_for_device(deviceNumber):
3564
    orders = MobileRechargeOrder.query.filter_by(mobileNumber = deviceNumber).all()
3565
    if orders is None:
3566
        orders = DTHRechargeOrder.query.filter_by(dthAccountNumber = deviceNumber).all()
3567
    return orders
3568
 
6154 rajveer 3569
def get_recharge_orders_for_status(status):
3570
    if status == -1:
6161 rajveer 3571
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).all()
6154 rajveer 3572
    else:
6161 rajveer 3573
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = status).all()
6154 rajveer 3574
    return orders
3575
 
6188 rajveer 3576
def get_recharge_statistics():
3577
    rs = RechargeStatistics()
3578
    statusCounts = {}
3579
    operatorCounts = {}
3580
    currentOrders = {}
3581
    amounts = {}
3582
 
3583
    sorders = session.query(RechargeOrder.status, func.count(RechargeOrder.status)).group_by(RechargeOrder.status).all()
3584
    for sorder in sorders:
6190 rajveer 3585
        statusCounts[sorder[0]] = sorder[1]
6188 rajveer 3586
 
3587
    oorders = session.query(MobileRechargeOrder.mobileOperatorId, func.count(MobileRechargeOrder.mobileOperatorId)).group_by(MobileRechargeOrder.mobileOperatorId).all()
3588
    for oorder in oorders:
6190 rajveer 3589
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 3590
 
3591
    oorders = session.query(DTHRechargeOrder.dthOperatorId, func.count(DTHRechargeOrder.dthOperatorId)).group_by(DTHRechargeOrder.dthOperatorId).all()
3592
    for oorder in oorders:
6190 rajveer 3593
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 3594
 
6219 rajveer 3595
    forders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED).limit(20).all()
6188 rajveer 3596
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED)] = [order.to_thrift_object() for order in forders]
3597
    sorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_SUCCESSFUL).limit(20).all()
6197 rajveer 3598
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_SUCCESSFUL)] = [order.to_thrift_object() for order in sorders]
6216 rajveer 3599
    porders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.PAYMENT_SUCCESSFUL).limit(20).all()
3600
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.PAYMENT_SUCCESSFUL)] = [order.to_thrift_object() for order in porders]
6238 rajveer 3601
    rorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).limit(20).all()
3602
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)] = [order.to_thrift_object() for order in rorders]
6188 rajveer 3603
 
6190 rajveer 3604
    twa = session.query(func.sum(UserWallet.amount)).one()
3605
    tra = session.query(func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
3606
    gwa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId > 100000).one()
6278 rajveer 3607
    #tpa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId < 100000).one()
3608
    tpa = session.query(func.sum(RechargeOrder.totalAmount-RechargeOrder.walletAmount)).filter(RechargeOrder.status.in_((RechargeOrderStatus.RECHARGE_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED, RechargeOrderStatus.PAYMENT_SUCCESSFUL, RechargeOrderStatus.RECHARGE_FAILED_REFUNDED))).one()
6190 rajveer 3609
    amounts['Total Wallet Amount'] = twa[0]
3610
    amounts['Total Recharge Amount'] = tra[0]
3611
    amounts['Gift Wallet Amount'] = gwa[0]
6278 rajveer 3612
    #amounts['Total Payment Amount'] = tra[0] + twa[0] - gwa[0]
3613
    amounts['Total Payment Amount'] = tpa
3614
 
6188 rajveer 3615
    rs.statusCounts = statusCounts
3616
    rs.operatorCounts = operatorCounts    
3617
    rs.currentOrders = currentOrders
3618
    rs.amounts = amounts
3619
 
3620
    return rs
3621
 
3622
 
6159 rajveer 3623
def get_plans_for_operator(operator_id):
3624
    return RechargePlan.query.filter_by(operatorId = operator_id).all()
3625
 
6056 amit.gupta 3626
def get_recharge_orders_for_transaction(txId):
3627
    return RechargeOrder.query.filter_by(transaction_id = txId).first()
6102 rajveer 3628
 
6285 rajveer 3629
def enqueue_recharge_info_email(recharge_order, gvs={}):
6102 rajveer 3630
    status = ""
3631
    message = ""
3632
    html_header = """
3633
 
3634
    <html>
3635
    <body>
3636
    <div>
3637
        <p>
3638
            Hello $email,<br /><br />
6127 rajveer 3639
            Thanks for placing recharge order with us. Following are the details of your recharge order:
6102 rajveer 3640
        </p>
3641
        <div>
6136 rajveer 3642
            Order Id : $order_id <br/>
3643
            Order Date : $order_date <br/>
3644
            Order Amount : Rs. $order_amount <br/>
3645
            Order Status : $order_status <br/>
3646
            Device Number : $device_number <br/>
3647
            Service Provider : $service_provider <br/>
6102 rajveer 3648
        </div>
6048 rajveer 3649
 
6102 rajveer 3650
    <br /><br />
3651
    """
6288 rajveer 3652
 
3653
    FailureReasonMap = {}
3654
    FailureReasonMap["Invalid Amount"] = "the amount you tried seems to be invalid. Please try another amount."
3655
    FailureReasonMap["Customer Exceeded Daily Limit"] = "you have exceeded daily recharge limit for this number. Please try after 12 hours."
3656
    FailureReasonMap["Invalid Mobile Number"] = "it seems that your mobile number is not being recognized by selected operator. Please make sure the number you tried is correct."
3657
 
3658
    failureReason = FailureReasonMap.get(recharge_order.description)
3659
    if failureReason is None:
3660
        failureReason = "of network failure."
6102 rajveer 3661
    if recharge_order.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3662
        status = "Recharge Successful"
3663
        message = ""
3664
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED:
3665
        status = "Recharge Failed"
6127 rajveer 3666
        message = """
6288 rajveer 3667
                We could not process your recharge because $failureReason We have credited the amount to your recharge wallet. You can use wallet amount to recharge again. <a href="$source_url/static/recharge-faq">Learn More</a>
6127 rajveer 3668
                """
6206 rajveer 3669
    elif recharge_order.status == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6102 rajveer 3670
        status = "Recharge Under Process"
6127 rajveer 3671
        message = """
6288 rajveer 3672
                Your Payment was successful but due to some internal error with the operator's system we are not sure if the recharge was successful. In case your recharge is not processed, we will credit amount to your recharge wallet. You can use wallet amount to recharge again. <a href="$source_url/static/recharge-faq">Learn More</a>
6127 rajveer 3673
                """
6279 rajveer 3674
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3675
        status = "Recharge Failed, Amount Refunded"
3676
        message = """
3677
                It seems operator could not process your recharge request. We are crediting the refund amount to your recharge wallet. You can use wallet amount to recharge again. <a href="$source_url/static/recharge-faq">Learn More</a>
3678
                """
6285 rajveer 3679
    if len(gvs) > 0:
3680
        message = message  + '<br />  You have been awarded with following Gift Voucher(s). You can redeem Gift Voucher(s) using to purchase any product above 5000.'
3681
        message = message + " <br />  Voucher Code          Amount"
3682
        for gv in gvs.keys():
3683
            gvAmount = gvs.get(gv)
3684
            message = message + " <br />  " + gv + "       "  + gvAmount
3685
 
6114 rajveer 3686
    message = message  + '<br />  In case of any problem, please  <a href="$source_url/contact-us">contact us</a>'
6102 rajveer 3687
 
6136 rajveer 3688
    html_header = html_header + message
6102 rajveer 3689
    html_footer = """
3690
    <p>
3691
        Best Wishes,<br />
3692
        $source_name Team
3693
    </p>
3694
    </div>
3695
    </body>
3696
    </html>
3697
    """
3698
 
6125 rajveer 3699
    if isinstance(recharge_order, MobileRechargeOrder):
3700
        deviceNumber = recharge_order.mobileNumber
3701
        providerName = get_provider(recharge_order.mobileOperatorId).name
3702
    if isinstance(recharge_order, DTHRechargeOrder):
3703
        deviceNumber = recharge_order.dthAccountNumber
3704
        providerName = get_provider(recharge_order.dthOperatorId).name
3705
 
6127 rajveer 3706
    display_order_id = recharge_order.idPrefix + str(recharge_order.id)
6102 rajveer 3707
    email = recharge_order.userEmailId
3708
    dt = datetime.datetime.strptime(str(recharge_order.creationTimestamp), "%Y-%m-%d %H:%M:%S")
3709
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
3710
 
6288 rajveer 3711
    email_header = Template(html_header).substitute(dict(order_id = display_order_id, order_date = formated_order_date, email = email, source_url = source_url, order_amount = recharge_order.totalAmount, order_status = status, device_number = deviceNumber, service_provider = providerName, failureReason = failureReason))
6102 rajveer 3712
    email_footer = Template(html_footer).substitute(dict(source_url = source_url, source_name = source_name))
3713
 
3714
    try:
3715
        helper_client = HelperClient().get_client()
6288 rajveer 3716
        helper_client.saveUserEmailForSending([email], "", source_name + " - Recharge Order Details", email_header + email_footer, str(recharge_order.id), "RechargeInfo", [], ['anupam.singh@shop2020.in', 'rajneesh.arora@shop2020.in', 'abhishek.mathur@shop2020.in', 'suraj.sharma@shop2020.in', 'rajveer.singh@shop2020.in'])
6102 rajveer 3717
        return True
3718
    except Exception as e:
3719
        print e
3720
        return False
3721
 
6289 anupam.sin 3722
def get_recharge_denominations(operator_id, circleName, denomination_type):
3723
    circle_id = TelecomCircle.query.filter_by(code = circleName).first().id
3724
    return RechargeDenomination.query.filter_by(operatorId = operator_id).filter_by(circleId = circle_id).filter_by(denominationType = denomination_type).all()
6102 rajveer 3725
 
766 rajveer 3726
def close_session():
3727
    if session.is_active:
3728
        print "session is active. closing it."
2783 chandransh 3729
        session.close()
3376 rajveer 3730
 
3731
def is_alive():
3732
    try:
3733
        session.query(Transaction.id).limit(1).one()
3734
        return True
3735
    except:
6000 mandeep.dh 3736
        return False
3737
 
3738
if __name__ == '__main__':
3739
    print 'Inside main'
3740
    DataService.initialize()
3741
    a = MobileRechargeOrder()
3742
    a.mobileNumber = 89564785666
3743
    session.commit()