Subversion Repositories SmartDukaan

Rev

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