Subversion Repositories SmartDukaan

Rev

Rev 5879 | Rev 5886 | 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
                                  }
5863 rajveer 1190
    to_addresses = [store.email, store.bdmEmail, 'sandeep.sachdeva@shop2020.in', 'suraj.sharma@shop2020.in', 'manoj.kumar@shop2020.in']
5832 rajveer 1191
    mail(from_user, from_pwd, to_addresses, subject, message)
5816 rajveer 1192
 
5713 rajveer 1193
def mark_orders_as_returned_from_store(providerId, orderIds, awbs):
5676 rajveer 1194
    try:
1195
        current_timestamp = datetime.datetime.now()
5824 rajveer 1196
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(logistics_provider_id = providerId, status = OrderStatus.RET_PICKUP_REQUEST_RAISED).all()
5676 rajveer 1197
        for order in orders:
5824 rajveer 1198
            order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1199
            order.statusDescription = "Order returned from store"
1200
            order.doa_pickup_timestamp = current_timestamp
1201
            #order.airwaybill_no = awbs[orderIds.index(order.id)]
1202
            order.tracking_id = awbs[orderIds.index(order.id)]
5676 rajveer 1203
        session.commit()
1204
 
1205
        return True
1206
    except:
1207
        return False    
1208
 
1209
def set_order_attributes(orderId, attributes):
5871 rajveer 1210
    for attribute in attributes :
1211
        existingAttribute = Attribute.query.filter(Attribute.orderId == orderId).filter(Attribute.name == attribute.name).first()
1212
        if existingAttribute:
1213
            existingAttribute.value = attribute.value
1214
        else :                
1215
            attr = Attribute()
1216
            attr.orderId = orderId
1217
            attr.name = attribute.name
1218
            attr.value = attribute.value
5791 anupam.sin 1219
    session.commit()
5724 rajveer 1220
 
1113 chandransh 1221
def mark_orders_as_picked_up(provider_id, pickup_details):
1222
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 1223
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 1224
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 1225
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1226
            continue
1113 chandransh 1227
        order.status = OrderStatus.SHIPPED_TO_LOGST
1228
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 1229
        order.pickup_timestamp = pickup_timestamp
5636 amar.kumar 1230
 
1231
        try:
1232
            monitoredEntity = MonitoredEntity();
1233
            monitoredEntity.entityType=EntityType.COURIER;
1234
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_LOGST
1235
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1236
            adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1237
            sec = datetime.datetime.now()
1238
            #Warn alert time is taken as 16 hrs
5821 amit.gupta 1239
            warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=15))
5744 amar.kumar 1240
            #Critical alert time is taken as 26 hrs                    
5821 amit.gupta 1241
            critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=20))
5744 amar.kumar 1242
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1243
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5819 amit.gupta 1244
            monitoredEntity.description="providerId = " + str(provider_id)
5636 amar.kumar 1245
            alert_client = AlertClient().get_client()
1246
            alert_client.updateMonitoredObject(monitoredEntity)
1247
        except Exception as e:
5801 amar.kumar 1248
            print "Exception in updating alert in MarkOrdersAsPickedUp method"
5636 amar.kumar 1249
            print e
1113 chandransh 1250
    session.commit()
1217 chandransh 1251
 
4910 phani.kuma 1252
def get_orders_not_picked_up(provider_id):
1132 chandransh 1253
    current_time = datetime.datetime.now()
1254
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4741 phani.kuma 1255
    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 1256
    return orders_not_picked_up
1257
 
1132 chandransh 1258
def mark_orders_as_delivered(provider_id, delivered_orders):
1259
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 1260
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 1261
        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 1262
            continue
1263
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
5555 rajveer 1264
        if order.pickupStoreId:
1265
            order.status = OrderStatus.DELIVERED_AT_STORE
1266
            order.statusDescription = "Order delivered At Store"
5762 amar.kumar 1267
            try:
1268
                monitoredEntity = MonitoredEntity();
1269
                monitoredEntity.entityType=EntityType.COURIER;
1270
                monitoredEntity.eventType=OrderStatus.RECEIVED_AT_STORE;
1271
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1272
                #adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1273
                sec = datetime.datetime.now()
1274
                #Critical alert time is taken as 26 hrs                    
1275
                critical_time = (sec + timedelta(hours=4))
1276
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1277
                monitoredEntity.description="deliveryTimeAtStore = " + str(order.delivery_timestamp) + " orderId = "  + str(order.id);
1278
                alert_client = AlertClient().get_client()
1279
                alert_client.updateMonitoredObject(monitoredEntity)
1280
            except Exception as e:
1281
                print e
5555 rajveer 1282
        else:
1283
            order.status = OrderStatus.DELIVERY_SUCCESS
1284
            order.statusDescription = "Order delivered"
5762 amar.kumar 1285
            update_trust_level(order)
5807 rajveer 1286
            enqueue_delivery_successe_mail(order)
5762 amar.kumar 1287
            try:
1288
                alert_client = AlertClient().get_client()
1289
                alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1290
            except Exception as e:
5801 amar.kumar 1291
                print "Exception in scheduling alert in ShippedFromWarehouse method"
5762 amar.kumar 1292
                print e
4910 phani.kuma 1293
        timestamp, receiver = detail.split('|')
1294
        if order.first_dlvyatmp_timestamp is None:
1295
            order.first_dlvyatmp_timestamp = timestamp
1296
        order.delivery_timestamp = timestamp
1297
        order.receiver = receiver
5636 amar.kumar 1298
 
1132 chandransh 1299
    session.commit()
1300
 
4712 rajveer 1301
def mark_order_as_delivered(orderId, deliveryTimestamp, receiver):
1302
    order = Order.get_by(id=orderId)
5555 rajveer 1303
    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 1304
        raise TransactionServiceException(101, "Either wrond order id or invalid state " + str(orderId))
5402 rajveer 1305
 
1306
    # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
1307
    if order.status == OrderStatus.BILLED and order.logistics_provider_id != 4:
5807 rajveer 1308
        raise TransactionServiceException(101, "Order is not marked for self pickup: " + str(orderId))
5402 rajveer 1309
 
5555 rajveer 1310
    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 1311
        order.delivery_timestamp = deliveryTimestamp
1312
        order.receiver = receiver
1313
    order.status = OrderStatus.DELIVERY_SUCCESS
1314
    order.statusDescription = "Order delivered"
1315
    update_trust_level(order)
1316
    session.commit()
5713 rajveer 1317
 
5812 rajveer 1318
    if order.pickupStoreId and order.cod:
5806 rajveer 1319
        __push_collection_to_hotspot(order, "SALE")
1320
 
5807 rajveer 1321
    enqueue_delivery_successe_mail(order)
5713 rajveer 1322
#    if order.pickupStoreId:
1323
#        payment_client = PaymentClient().get_client()
1324
#        payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
1325
#        payment_client = PaymentClient().get_client()
1326
#        payment_client.partiallyCapturePayment(order.transaction.id, order.total_amount, xferBy, xferTxnId, now())
1327
#        order.cod_reconciliation_timestamp = datetime.datetime.now()
1328
#        session.commit()
1329
 
5636 amar.kumar 1330
    try:
1331
        alert_client = AlertClient().get_client()
5744 amar.kumar 1332
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1333
    except Exception as e:
5801 amar.kumar 1334
        print "Exception in ending alert in MarkOrderAsDelivered method"
5636 amar.kumar 1335
        print e
1336
 
4712 rajveer 1337
 
5555 rajveer 1338
def mark_order_as_received_at_store(orderId, deliveryTimestamp):
1339
    order = Order.get_by(id=orderId)
1340
    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]:
1341
        order.status = OrderStatus.RECEIVED_AT_STORE
1342
        order.statusDescription = "Order received at store"
1343
        order.delivery_timestamp = deliveryTimestamp
1344
    session.commit()
5713 rajveer 1345
    try:
5762 amar.kumar 1346
        alert_client = AlertClient().get_client()
1347
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1348
    except Exception as e:
1349
        print e
1350
 
1351
    try:
5713 rajveer 1352
        enqueue_received_at_store_email(order)
1353
    except Exception as e:
1354
        print e
1355
 
1356
 
5555 rajveer 1357
 
4910 phani.kuma 1358
def mark_orders_as_rto(provider_id, returned_orders):
1135 chandransh 1359
    for awb, detail in returned_orders.iteritems():
1360
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
5713 rajveer 1361
        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 1362
            continue
1363
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 1364
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 1365
        order.delivery_timestamp, reason = detail.split('|')
1366
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 1367
        update_trust_level(order)
1911 chandransh 1368
    session.commit()
5636 amar.kumar 1369
    try:
1370
        alert_client = AlertClient().get_client()
5801 amar.kumar 1371
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1372
    except Exception as e:
5801 amar.kumar 1373
        print "Exception in ending alert in MarkOrderAsRTO method"
5636 amar.kumar 1374
        print e
1135 chandransh 1375
 
4910 phani.kuma 1376
def get_rto_orders(provider_id):
1377
    current_time = datetime.datetime.now()
1378
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1379
    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()
1380
    return rto_orders
1381
 
5555 rajveer 1382
def get_receive_pending_orders(storeId):
1383
    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()
1384
 
1385
def get_received_at_store_orders(storeId):
5676 rajveer 1386
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.RECEIVED_AT_STORE, OrderStatus.RET_PICKUP_REQUEST_RAISED))).all()
5555 rajveer 1387
 
5713 rajveer 1388
def get_orders_collection_at_store(storeId, fromDate, toDate, onlyCod):
1389
    query = Order.query.filter(Order.status == OrderStatus.DELIVERY_SUCCESS)
1390
    if storeId:
1391
        query = query.filter_by(pickupStoreId = storeId)
5720 rajveer 1392
    else:
1393
        query = query.filter(Order.pickupStoreId != 0)
5713 rajveer 1394
    if onlyCod:
1395
        query = query.filter_by(cod = onlyCod)
1396
    if fromDate:
1397
        query = query.filter(Order.delivery_timestamp >= fromDate)
1398
    if toDate:
1399
        query = query.filter(Order.delivery_timestamp <= toDate)
1400
    return query.all()
1401
 
1246 chandransh 1402
def update_non_delivery_reason(provider_id, undelivered_orders):
1403
    for awb, reason in undelivered_orders.iteritems():
1404
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4920 phani.kuma 1405
        if order == None or order.status == OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE:
2684 chandransh 1406
            continue
1407
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 1408
        order.statusDescription = reason
1409
    session.commit()
4910 phani.kuma 1410
 
1411
def get_non_delivered_orders_by_courier(provider_id):
4581 phani.kuma 1412
    current_time = datetime.datetime.now()
1413
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1414
    upto_datetime = today_datetime - datetime.timedelta(4)
4910 phani.kuma 1415
    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 1416
    return orders_not_delivered
1246 chandransh 1417
 
4910 phani.kuma 1418
def mark_orders_as_local_connected(provider_id, local_connected_orders):
1419
    for awb, timestamp in local_connected_orders.iteritems():
1420
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1421
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1422
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1423
            continue
1424
        order.status = OrderStatus.SHIPPED_TO_DESTINATION_CITY
1425
        order.statusDescription = "Left Out of Origin City"
5636 amar.kumar 1426
        current_time = datetime.datetime.now()
1427
        order.local_connected_timestamp = datetime.datetime(current_time.year, current_time.month, current_time.day)
1428
        try:
1429
            monitoredEntity = MonitoredEntity();
1430
            monitoredEntity.entityType=EntityType.COURIER;
1431
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_DESTINATION_CITY
1432
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1433
            #Warn alert time is taken as 23 hrs less than promised delivery time
5821 amit.gupta 1434
            warn_time = (order.expected_delivery_time-timedelta(hours = 15))
5744 amar.kumar 1435
            #Critical alert time is taken as 13 hrs less than promised delivery time                    
5821 amit.gupta 1436
            critical_time = (order.expected_delivery_time-timedelta(hours = 10))
5801 amar.kumar 1437
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1438
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1439
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1440
            alert_client = AlertClient().get_client()
1441
            alert_client.updateMonitoredObject(monitoredEntity)
1442
        except Exception as e:
5801 amar.kumar 1443
            print "Exception in updating alert in MarkOrderAsLocalConnected method"
5636 amar.kumar 1444
            print e
1445
        session.commit()
4910 phani.kuma 1446
 
1447
def get_orders_not_local_connected(provider_id):
1448
    current_time = datetime.datetime.now()
1449
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1450
    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()
1451
    return orders_pending_local_connection
1452
 
1453
def mark_orders_as_destinationCityReached(provider_id, destination_city_reached_orders):
1454
    for awb, timestamp in destination_city_reached_orders.iteritems():
1455
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1456
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY]:
1457
            continue
1458
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1459
        order.status = OrderStatus.REACHED_DESTINATION_CITY
1460
        order.statusDescription = "Reached Destination City"
1461
        order.reached_destination_timestamp = timestamp
5636 amar.kumar 1462
        try:
1463
            monitoredEntity = MonitoredEntity();
1464
            monitoredEntity.entityType=EntityType.COURIER;
1465
            monitoredEntity.eventType=OrderStatus.REACHED_DESTINATION_CITY
1466
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5764 amar.kumar 1467
            warn_time = (order.expected_delivery_time)
5801 amar.kumar 1468
            critical_time = (order.expected_delivery_time + timedelta(hours=12))
1469
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1470
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1471
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1472
            alert_client = AlertClient().get_client()
1473
            alert_client.updateMonitoredObject(monitoredEntity)
1474
        except Exception as e:
5801 amar.kumar 1475
            print "Exception in updating alert in MarkOrderAsDestCityReached method"
5636 amar.kumar 1476
            print e
4910 phani.kuma 1477
    session.commit()
1478
 
1479
def mark_orders_as_firstDeliveryAttempted(provider_id, first_atdl_orders):
1480
    for awb, detail in first_atdl_orders.iteritems():
1481
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1482
        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]:
1483
            continue
1484
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1485
        order.status = OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1486
        order.first_dlvyatmp_timestamp, reason = detail.split('|')
1487
        order.statusDescription = reason
5636 amar.kumar 1488
        try:
1489
            monitoredEntity = MonitoredEntity();
1490
            monitoredEntity.entityType=EntityType.COURIER;
1491
            monitoredEntity.eventType=OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1492
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1493
            adjustedDeliveryDaysfor1day = adjust_delivery_time(datetime.datetime.now(), 1);
1494
            adjustedDeliveryDaysfor2days = adjust_delivery_time(datetime.datetime.now(), 2);
1495
            sec = datetime.datetime.now()
1496
            #Warn alert time is taken as 16 hrs
1497
            warn_time = (sec + timedelta(days=(adjustedDeliveryDaysfor1day-1)) + timedelta(hours=24))
1498
            #Critical alert time is taken as 26 hrs                    
1499
            critical_time = (sec + timedelta(days=(adjustedDeliveryDaysfor2days-1)) + timedelta(hours=36))
1500
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1501
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1502
            monitoredEntity.description="providerId = " + str(provider_id) + " first attempt timestamp" + order.first_dlvyatmp_timestamp
1503
            alert_client = AlertClient().get_client()
1504
            alert_client.updateMonitoredObject(monitoredEntity)
1505
        except Exception as e:
5801 amar.kumar 1506
            print "Exception in updating alert in MarkOrdersAsFirstDeliveryAttempted method"
5636 amar.kumar 1507
            print e
4910 phani.kuma 1508
    session.commit()
1509
 
4783 phani.kuma 1510
def get_orders_not_met_expected_delivery_date():
1511
    current_time = datetime.datetime.now()
1512
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4910 phani.kuma 1513
    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 1514
    return orders_not_delivered
1515
 
4444 rajveer 1516
def get_alerts(type, warehouseId, status, timestamp):
1517
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
1518
    if type != -1 :
1519
        query = query.filter(Alert.type == type)
1520
    if status != -1 :
1521
        query = query.filter(Alert.status == status)
4394 rajveer 1522
    if timestamp:
1523
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 1524
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 1525
    return query.all()
1526
 
4447 rajveer 1527
def add_alert(type, warehouseId, description):
4394 rajveer 1528
    alert = Alert()
1529
    alert.type = type
1530
    alert.status = 1
1531
    alert.description = description
1532
    alert.timestamp = datetime.datetime.now()
4447 rajveer 1533
    alert.warehouseId = warehouseId
4444 rajveer 1534
    session.commit()
766 rajveer 1535
 
4444 rajveer 1536
def mark_alerts_as_seen(warehouseId):
1537
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
1538
    alerts = query.all()
1539
    for alert in alerts:
1540
        alert.status = 0    
1541
    session.commit()
1542
 
1596 ankur.sing 1543
def get_valid_order_count():
2851 chandransh 1544
    '''
1545
    Returns the number of orders which we processed. The reshipped orders are not
1546
    counted since there'll always be a new compensating order present.
1547
    '''
4682 rajveer 1548
    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 1549
 
1627 ankur.sing 1550
def get_cust_count_with_successful_txn():
2851 chandransh 1551
    '''
1552
    Returns the number of distinct customers who have done successful transactions.
1553
    It uses the sqlalchemy func module to construct an efficient query.
1554
    '''
1555
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 1556
 
1730 ankur.sing 1557
def get_valid_orders_amount_range():
2851 chandransh 1558
    '''
1559
    Returns a list containing the minimum and maximum amount across all
1560
    orders placed with us. No need to consider reshippped orders for min/max
1561
    amount of orders.
1562
    '''
1563
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 1564
 
5874 rajveer 1565
def get_valid_orders(limit, onlyStore):
2851 chandransh 1566
    '''
1567
    Returns the last limit number of valid orders placed with us. Ignored the
1568
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
1569
    less than 0. 
1570
    '''
1571
    if limit < 0:
1572
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
4662 rajveer 1573
    query = Order.query.filter(Order.status >= OrderStatus.COD_VERIFICATION_PENDING)
5874 rajveer 1574
    if onlyStore:
1575
        query = query.filter(Order.pickupStoreId != 0)
1886 ankur.sing 1576
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 1577
    if limit != 0:
1886 ankur.sing 1578
        query = query.limit(limit)
1579
    return query.all()
1580
 
5527 anupam.sin 1581
def get_next_invoice_number(orderType):
1582
    if OrderType.B2Cbulk == orderType:
1583
        orderType = OrderType.B2C
1584
    entity_id = InvoiceIDGenerator.query.filter(InvoiceIDGenerator.orderType == orderType).with_lockmode("update").one()
2783 chandransh 1585
    invoice_number = entity_id.id + 1
1586
    entity_id.id = invoice_number
1587
    return invoice_number
1588
 
2536 chandransh 1589
def toggle_doa_flag(order_id):
1590
    order = get_order(order_id)
1591
    if(order.doaFlag):
1592
        order.doaFlag = False
1593
    else:
1594
        order.doaFlag = True
1595
    session.commit()
1596
    return order.doaFlag
1597
 
4454 rajveer 1598
def mark_order_doa_request_received(orderId):
1599
    order = get_order(orderId)
1600
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1601
        return False
1602
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 1603
    order.statusDescription = "DOA Request Received"
4454 rajveer 1604
    session.commit()
1605
    return True
1606
 
1607
def mark_order_doa_request_authorized(orderId, isAuthorized):
1608
    order = get_order(orderId)
1609
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
1610
        return False
1611
    if isAuthorized:
1612
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 1613
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 1614
    else:
1615
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 1616
        order.statusDescription = "Order delivered"
4454 rajveer 1617
    session.commit()
1618
    return True
1619
 
4488 rajveer 1620
def mark_order_return_request_received(orderId):
1621
    order = get_order(orderId)
1622
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1623
        return False
1624
    order.status = OrderStatus.RET_REQUEST_RECEIVED
1625
    order.statusDescription = "Return Request Received"
1626
    session.commit()
1627
    return True
1628
 
1629
def mark_order_return_request_authorized(orderId, isAuthorized):
1630
    order = get_order(orderId)
1631
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
1632
        return False
1633
    if isAuthorized:
1634
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
1635
        order.statusDescription = "Return Request Authorized"
1636
    else:
1637
        order.status = OrderStatus.DELIVERY_SUCCESS
1638
        order.statusDescription = "Order delivered"
1639
    session.commit()
1640
    return True
1641
 
4579 rajveer 1642
def request_pickup_number(order_id, providerId):
2536 chandransh 1643
    order = get_order(order_id)
4495 rajveer 1644
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 1645
        return False
1646
    from_user = 'cnc.center@shop2020.in'
1647
    from_pwd = '5h0p2o2o'
1648
 
4227 rajveer 1649
    subject = "Pickup request from " + order.customer_city
2536 chandransh 1650
    try:
3133 rajveer 1651
        catalog_client = CatalogClient().get_client()
2536 chandransh 1652
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1653
 
1654
        logistics_client = LogisticsClient().get_client()
4579 rajveer 1655
        provider = logistics_client.getProvider(providerId)
3051 chandransh 1656
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 1657
        raw_message = '''
1658
        Dear Sir/Madam,
1659
 
2559 chandransh 1660
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 1661
 
1662
        Pickup CODE: %(provider_code)s
1663
        Total Weight: %(order_weight)s kg
1664
 
2559 chandransh 1665
        Pickup Address:
2536 chandransh 1666
 
1667
        %(customer_address)s
1668
 
1669
        Delivery Address:
1670
 
1671
        %(warehouse_executive)s
1672
        %(warehouse_address)s
1673
        PIN %(warehouse_pin)s
1674
 
1675
        Thanks and Regards
4227 rajveer 1676
        Sandeep Sachdeva
2536 chandransh 1677
        '''
4579 rajveer 1678
 
1679
        if warehouse.id == 7:
1680
            executive = 'Amit Kumar'
1681
        else:
4966 phani.kuma 1682
            executive = 'Dinesh Kumar'
4579 rajveer 1683
 
2559 chandransh 1684
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 1685
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
2536 chandransh 1686
                                          'order_weight' : str(order.total_weight),
1687
                                          'customer_address' : __get_order_address(order),
4579 rajveer 1688
                                          'warehouse_executive' : executive,
2536 chandransh 1689
                                          'warehouse_address' : warehouse.location,
4966 phani.kuma 1690
                                          'warehouse_pin' : warehouse.pincode}
5860 rajveer 1691
        to_addresses = [to_addr, 'gaurabh.verma@shop2020.in', 'suraj.sharma@shop2020.in']
4966 phani.kuma 1692
 
4606 rajveer 1693
        mail(from_user, from_pwd, to_addresses, subject, message)
4495 rajveer 1694
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
1695
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
1696
            order.statusDescription = "Pick up requested for RETURN"
1697
        else:
1698
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
1699
            order.statusDescription = "Pick up requested for DOA"
4815 phani.kuma 1700
        order.doa_logistics_provider_id = providerId
2536 chandransh 1701
        session.commit()
1702
        return True
1703
    except Exception as e:
1704
        print sys.exc_info()[0]
1705
        return False
1706
 
4602 rajveer 1707
def authorize_pickup(order_id, pickup_number, providerId):
2536 chandransh 1708
    order = get_order(order_id)
4495 rajveer 1709
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 1710
        return False
4815 phani.kuma 1711
    if order.doa_logistics_provider_id is not None:
1712
        providerId = order.doa_logistics_provider_id    #previously we are not storing this so data is taken from omdashboarduser
2536 chandransh 1713
    from_user = 'help@shop2020.in'
1714
    from_pwd = '5h0p2o2o'
1715
    subject = 'Pickup details'
1716
    filename = "/tmp/" +  str(order.id) +".pdf" 
1717
    try:
3133 rajveer 1718
        catalog_client = CatalogClient().get_client()
2536 chandransh 1719
        warehouse = catalog_client.getWarehouse(order.warehouse_id)
1720
 
1721
        logistics_client = LogisticsClient().get_client()
4602 rajveer 1722
        provider = logistics_client.getProvider(providerId)
2536 chandransh 1723
        provider_name = provider.name
1724
 
1725
        to_addr = order.customer_email
1726
        today = date.today().strftime("%d-%B-%Y (%A)")
1727
 
1728
        raw_message = '''
1729
        Dear Mr. %(customer_name)s,
1730
 
4815 phani.kuma 1731
        In reference to the return of order ID %(order_id)d, ''' + __generate_mail_body_for_authorize_pickup(order)
1732
        raw_message = raw_message + '''
2536 chandransh 1733
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
1734
        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.
1735
 
1736
        Pickup will happen from the below mentioned address:-
1737
 
1738
        %(customer_address)s
1739
 
1740
        Do let us know in case of any concerns
1741
 
1742
        Thanks & Regards
1743
        Saholic Team
1744
        '''
1745
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
1746
                                         'order_id' : order_id,
1747
                                         'provider_name' : provider_name,
1748
                                         'date': today,
1749
                                         'pickup_request_no' : pickup_number,
1750
                                         'customer_address' : __get_order_address(order)}
1751
        print message
1752
        __generate_return_advice(order, warehouse, provider, filename)
3527 chandransh 1753
        mail(from_user, from_pwd, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 1754
        order.pickupRequestNo = pickup_number
4495 rajveer 1755
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1756
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
1757
            order.statusDescription = "RETURN pick up confirmed"
1758
        else:
1759
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
1760
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 1761
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 1762
        session.commit()
1763
        return True
1764
    except Exception as e:
4234 rajveer 1765
        print sys.exc_info()
4506 phani.kuma 1766
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 1767
        return False
1768
    finally:
1769
        if os.path.exists(filename):
1770
            os.remove(filename)
1771
 
4815 phani.kuma 1772
def __generate_mail_body_for_authorize_pickup(order):
1773
    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.',
1774
                         '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.',
1775
                         '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.',
1776
                         'Sony Ericsson' : 'we request you to kindly pack the original DOA certificate and the invoice.',
1777
                         '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.',
1778
                         '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.',
1779
                         'Accessories' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original product and the invoice.'}
1780
    categories = ["Handsets", "Tablets", "Laptops"]
1781
    lineitem = order.lineitems[0]
1782
    brand = lineitem.brand
1783
    productGroup = lineitem.productGroup
1784
    searchkey = None
1785
    if productGroup not in categories:
1786
        searchkey = 'Accessories'
1787
    elif order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1788
        searchkey = 'Handsets Return'
1789
    elif brand == 'Nokia':
1790
        searchkey = 'Nokia'
1791
    elif brand == 'Micromax':
1792
        searchkey = 'Micromax'
1793
    elif brand == 'Karbonn':
1794
        searchkey = 'Karbonn'
1795
    elif brand == 'Sony Ericsson':
1796
        searchkey = 'Sony Ericsson'
1797
    else:
1798
        searchkey = 'Others Handsets'
1799
    return brand_msgbody_map.get(searchkey)
1800
 
2764 chandransh 1801
def mark_doas_as_picked_up(provider_id, pickup_details):
1802
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1803
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4452 rajveer 1804
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 1805
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1806
            continue
1807
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
1808
        order.statusDescription = "DOA picked up by Courier Company"
1809
        order.doa_pickup_timestamp = doa_pickup_timestamp
1810
    session.commit()
1811
 
4910 phani.kuma 1812
def get_doas_not_picked_up(provider_id):
2764 chandransh 1813
    current_time = datetime.datetime.now()
1814
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1815
    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 1816
    return orders_not_picked_up
1817
 
4741 phani.kuma 1818
def mark_return_orders_as_picked_up(provider_id, pickup_details):
1819
    for pickupNo, return_order_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 1820
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4741 phani.kuma 1821
        if order == None or order.status != OrderStatus.RET_PICKUP_CONFIRMED:
1822
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1823
            continue
1824
        order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1825
        order.statusDescription = "Return order picked up by Courier Company"
1826
        order.doa_pickup_timestamp = return_order_pickup_timestamp
1827
    session.commit()
1828
 
4910 phani.kuma 1829
def get_return_orders_not_picked_up(provider_id):
4741 phani.kuma 1830
    current_time = datetime.datetime.now()
1831
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 1832
    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 1833
    return orders_not_picked_up
1834
 
4479 rajveer 1835
def receive_return(order_id, receiveCondition):
2591 chandransh 1836
    order = get_order(order_id)
4365 mandeep.dh 1837
 
4452 rajveer 1838
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 1839
        if receiveCondition == 0:
1840
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
1841
            order.statusDescription = "DOA package received"
1842
        elif receiveCondition == 1:
1843
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
1844
            order.statusDescription = "DOA received damaged"
1845
        elif receiveCondition == 2:
1846
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
1847
            order.statusDescription = "DOA lost in transit"
2764 chandransh 1848
        order.received_return_timestamp = datetime.datetime.now()
4495 rajveer 1849
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
1850
        if receiveCondition == 0:
1851
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
1852
            order.statusDescription = "RETURN package received"
1853
        elif receiveCondition == 1:
1854
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
1855
            order.statusDescription = "RETURN received damaged"
1856
        elif receiveCondition == 2:
1857
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
1858
            order.statusDescription = "RETURN lost in transit"
1859
        order.received_return_timestamp = datetime.datetime.now()
4484 rajveer 1860
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 1861
        if receiveCondition == 0:
1862
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 1863
            order.statusDescription = "Returned to origin"
4486 rajveer 1864
        elif receiveCondition == 1:
1865
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
1866
            order.statusDescription = "RTO received damaged"
1867
        elif receiveCondition == 2:
1868
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
1869
            order.statusDescription = "RTO lost in transit"
2764 chandransh 1870
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 1871
    else:
2591 chandransh 1872
        return False
5110 mandeep.dh 1873
 
1874
    # For OUR warehouses, we need to scan in items for every return
1875
    catalogClient = CatalogClient().get_client()
1876
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1877
    if warehouse.billingType == BillingType.OURS:
5361 mandeep.dh 1878
        scanMap = {
1879
            OrderStatus.RTO_RECEIVED_PRESTINE : ScanType.SALE_RET,
1880
            OrderStatus.RTO_RECEIVED_DAMAGED  : ScanType.SALE_RET_UNUSABLE,
1881
            OrderStatus.RTO_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT,
1882
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
1883
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
1884
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
1885
        }
5110 mandeep.dh 1886
 
5419 mandeep.dh 1887
        if scanMap.has_key(order.status):
1888
            scanType = scanMap[order.status]
5361 mandeep.dh 1889
            lineitem = order.lineitems[0]
1890
            item = catalogClient.getItem(lineitem.item_id)
1891
            warehouseClient = WarehouseClient().get_client()
1892
            if item.type == ItemType.SERIALIZED:
5110 mandeep.dh 1893
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 1894
            else:
1895
                warehouseClient.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
5110 mandeep.dh 1896
 
5558 mandeep.dh 1897
    session.commit()
2591 chandransh 1898
    return True
1899
 
1900
def validate_doa(order_id, is_valid):
1901
    order = get_order(order_id)
4452 rajveer 1902
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 1903
        return False
1904
    if is_valid:
2609 chandransh 1905
        order.status = OrderStatus.DOA_CERT_VALID
1906
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 1907
    else:
1908
        order.status = OrderStatus.DOA_CERT_INVALID
1909
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 1910
        update_trust_level(order)
2591 chandransh 1911
    session.commit()
1912
    return True
1913
 
4495 rajveer 1914
def validate_return_product(order_id, is_usable):
1915
    order = get_order(order_id)
1916
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
1917
        return False
5110 mandeep.dh 1918
 
1919
    scanType = ScanType.SALE_RET_UNUSABLE
4495 rajveer 1920
    if is_usable:
1921
        order.status = OrderStatus.RET_PRODUCT_USABLE
1922
        order.statusDescription = "Return product usable"
5110 mandeep.dh 1923
        scanType = ScanType.SALE_RET
4495 rajveer 1924
    else:
1925
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
1926
        order.statusDescription = "Return product unusable"
1927
        update_trust_level(order)
1928
    session.commit()
5110 mandeep.dh 1929
 
1930
    # For OUR warehouses, we need to scan in items for every return
1931
    catalogClient = CatalogClient().get_client()
1932
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
1933
    if warehouse.billingType == BillingType.OURS:
1934
        lineitem = order.lineitems[0]
5361 mandeep.dh 1935
        item = catalogClient.getItem(lineitem.item_id)
5110 mandeep.dh 1936
        warehouse_client = WarehouseClient().get_client()
5361 mandeep.dh 1937
        if item.type == ItemType.SERIALIZED:
1938
            warehouse_client.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
1939
        else:
1940
            warehouse_client.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4495 rajveer 1941
    return True
1942
 
2628 chandransh 1943
def reship_order(order_id):
1944
    """
4484 rajveer 1945
    If the order is in RTO_RECEIVED_PRESTINE or DOA_CERT_INVALID state, it does the following:
2628 chandransh 1946
        1. Creates a new order for processing in the BILLED state. All billing information is saved.
4484 rajveer 1947
        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 1948
 
1949
    If the order is in DOA_CERT_VALID state, it does the following:
1950
        1. Creates a new order for processing in the SUBMITTED_FOR_PROCESSING state.
1951
        2. Creates a return order for the warehouse executive to return the DOA material.
4452 rajveer 1952
        3. Marks the current order as the final DOA_VALID_RESHIPPED state.
2628 chandransh 1953
 
1954
    Returns the id of the newly created order.
1955
 
1956
    Throws an exception if the order with the given id couldn't be found.
1957
 
1958
    Parameters:
1959
     - orderId
1960
    """
1961
    order = get_order(order_id)
4484 rajveer 1962
    if order.status == OrderStatus.RTO_RECEIVED_PRESTINE:
4220 rajveer 1963
        new_order = __clone_order(order, True, order.cod)
4484 rajveer 1964
        order.status = OrderStatus.RTO_RESHIPPED
2628 chandransh 1965
        order.statusDescription = "Order Reshipped"
1966
        session.commit()
3578 mandeep.dh 1967
        update_trust_level(order)
4486 rajveer 1968
    elif order.status == OrderStatus.RTO_RECEIVED_DAMAGED:
1969
        new_order = __clone_order(order, False, order.cod)
1970
        ret_order = __create_return_order(order)
1971
        order.status = OrderStatus.RTO_DAMAGED_RESHIPPED
1972
        order.statusDescription = "Order Reshipped Received Damaged"
1973
        session.commit()
1974
    elif order.status == OrderStatus.RTO_LOST_IN_TRANSIT:
1975
        new_order = __clone_order(order, False, order.cod)
1976
        order.status = OrderStatus.RTO_LOST_IN_TRANSIT_RESHIPPED
1977
        order.statusDescription = "Order Reshipped Lost In Transit"
1978
        session.commit()
4662 rajveer 1979
    elif order.status == OrderStatus.LOST_IN_TRANSIT:
1980
        new_order = __clone_order(order, False, order.cod)
1981
        order.status = OrderStatus.LOST_IN_TRANSIT_RESHIPPED
1982
        order.statusDescription = "Order Reshipped Lost In Transit"
1983
        session.commit()
2628 chandransh 1984
    elif order.status == OrderStatus.DOA_CERT_INVALID:
4220 rajveer 1985
        new_order = __clone_order(order, True, False)
2628 chandransh 1986
        order.status = OrderStatus.DOA_INVALID_RESHIPPED
1987
        order.statusDescription = "Order Reshipped"
1988
        session.commit()
5620 mandeep.dh 1989
        warehouseClient = WarehouseClient().get_client()
1990
        inventoryItem = warehouseClient.getInventoryItemFromOrder(order_id)
1991
        warehouseClient.scanForOrder(inventoryItem, ScanType.SALE, new_order.lineitems[0].quantity, new_order.id, new_order.fulfilmentWarehouseId, new_order.warehouse_id)
2628 chandransh 1992
    elif order.status == OrderStatus.DOA_CERT_VALID:
4220 rajveer 1993
        new_order = __clone_order(order, False, False)
2628 chandransh 1994
        ret_order = __create_return_order(order)
4452 rajveer 1995
        order.status = OrderStatus.DOA_VALID_RESHIPPED
2628 chandransh 1996
        order.statusDescription = "Order Reshipped"
1997
        session.commit()
4479 rajveer 1998
    elif order.status == OrderStatus.DOA_RECEIVED_DAMAGED:
1999
        new_order = __clone_order(order, False, False)
2000
        ret_order = __create_return_order(order)
2001
        order.status = OrderStatus.DOA_RESHIPPED_RCVD_DAMAGED
2002
        order.statusDescription = "Order Reshipped Received Damaged"
2003
        session.commit()
2004
    elif order.status == OrderStatus.DOA_LOST_IN_TRANSIT:
2005
        new_order = __clone_order(order, False, False)
2006
        order.status = OrderStatus.DOA_RESHIPPED_LOST_IN_TRANSIT
2007
        order.statusDescription = "Order Reshipped Lost In Transit"
2008
        session.commit()
4614 rajveer 2009
    elif order.status == OrderStatus.RET_PRODUCT_USABLE:
5620 mandeep.dh 2010
        new_order = __clone_order(order, False, False)
4614 rajveer 2011
        order.status = OrderStatus.RET_PRODUCT_USABLE_RESHIPPED
4495 rajveer 2012
        order.statusDescription = "Order Reshipped"
2013
        session.commit()
4614 rajveer 2014
    elif order.status == OrderStatus.RET_PRODUCT_UNUSABLE:
4495 rajveer 2015
        new_order = __clone_order(order, False, False)
2016
        ret_order = __create_return_order(order)
4614 rajveer 2017
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE_RESHIPPED
4495 rajveer 2018
        order.statusDescription = "Order Reshipped"
2019
        session.commit()
2020
    elif order.status == OrderStatus.RET_RECEIVED_DAMAGED:
2021
        new_order = __clone_order(order, False, False)
2022
        ret_order = __create_return_order(order)
2023
        order.status = OrderStatus.RET_RESHIPPED_RCVD_DAMAGED
2024
        order.statusDescription = "Order Reshipped Received Damaged"
2025
        session.commit()
2026
    elif order.status == OrderStatus.RET_LOST_IN_TRANSIT:
2027
        new_order = __clone_order(order, False, False)
2028
        order.status = OrderStatus.RET_RESHIPPED_LOST_IN_TRANSIT
2029
        order.statusDescription = "Order Reshipped Lost In Transit"
2030
        session.commit()
2628 chandransh 2031
    else:
2032
        raise TransactionServiceException(112, "This order can't be reshipped")
2033
 
2764 chandransh 2034
    order.reship_timestamp = datetime.datetime.now()
2628 chandransh 2035
    order.new_order_id = new_order.id
2036
    session.commit()
2037
 
2038
    return new_order.id
2039
 
3226 chandransh 2040
def refund_order(order_id, refunded_by, reason):
2628 chandransh 2041
    """
4484 rajveer 2042
    If the order is in RTO_RECEIVED_PRESTINE, DOA_CERT_VALID or DOA_CERT_INVALID state, it does the following:
2628 chandransh 2043
        1. Creates a refund request for batch processing.
2044
        2. Creates a return order for the warehouse executive to return the shipped material.
4484 rajveer 2045
        3. Marks the current order as RTO_REFUNDED, DOA_VALID_REFUNDED or DOA_INVALID_REFUNDED final states.
2628 chandransh 2046
 
2047
    If the order is in SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2048
        1. Creates a refund request for batch processing.
3226 chandransh 2049
        2. Cancels the reservation of the item in the warehouse.
2050
        3. Marks the current order as the REFUNDED final state.
2628 chandransh 2051
 
3226 chandransh 2052
    For all COD orders, if the order is in INIT, SUBMITTED_FOR_PROCESSING or INVENTORY_LOW state, it does the following:
2053
        1. Cancels the reservation of the item in the warehouse.
2054
        2. Marks the current order as CANCELED.
2055
 
2056
    In all cases, it updates the reason for cancellation or refund and the person who performed the action.
2057
 
2058
    Returns True if it is successful, False otherwise.
2628 chandransh 2059
 
2060
    Throws an exception if the order with the given id couldn't be found.
2061
 
2062
    Parameters:
3226 chandransh 2063
     - order_id
2064
     - refunded_by
2065
     - reason
2628 chandransh 2066
    """
3414 chandransh 2067
    logging.info("Refunding order id: " + str(order_id))
2628 chandransh 2068
    order = get_order(order_id)
3186 chandransh 2069
 
3226 chandransh 2070
    if order.cod:
3414 chandransh 2071
        logging.info("Refunding COD order with status " + str(order.status))
4662 rajveer 2072
        status_transition = { OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2073
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2074
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2075
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2076
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2077
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2078
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2079
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2080
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2081
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2082
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2083
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2084
                     OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.COD_VERIFICATION_FAILED,
2085
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2086
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2087
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2088
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2089
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2090
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2091
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2092
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST
3366 chandransh 2093
                     }
2094
        if order.status not in status_transition.keys():
2095
            raise TransactionServiceException(114, "This order can't be refunded")
2096
 
5199 mandeep.dh 2097
        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 2098
            __update_inventory_reservation(order)
2099
            order.statusDescription = "Order Cancelled"
3415 chandransh 2100
        elif order.status == OrderStatus.BILLED:
3413 chandransh 2101
            __create_return_order(order)
2102
            order.statusDescription = "Order Cancelled"
4486 rajveer 2103
        elif order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT]:
5386 phani.kuma 2104
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2105
                __create_return_order(order)
4486 rajveer 2106
            order.statusDescription = "RTO Refunded"
4662 rajveer 2107
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2108
            #__create_return_order(order)
4662 rajveer 2109
            order.statusDescription = "Lost in Transit Refunded"
4479 rajveer 2110
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2111
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2112
                __create_return_order(order)
3226 chandransh 2113
            __create_refund(order)
4495 rajveer 2114
            order.statusDescription = "DOA Refunded"
2115
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2116
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2117
                __create_return_order(order)
4495 rajveer 2118
            __create_refund(order)
2119
            order.statusDescription = "Return Refunded"
4247 rajveer 2120
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5199 mandeep.dh 2121
            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 2122
                __update_inventory_reservation(order)
2123
                order.statusDescription = "Order Cancelled on customer request"
2124
            elif order.previousStatus == OrderStatus.BILLED:
2125
                __create_return_order(order)
2126
                order.statusDescription = "Order Cancelled on customer request"
3226 chandransh 2127
    else:
4662 rajveer 2128
        status_transition = {OrderStatus.LOST_IN_TRANSIT : OrderStatus.LOST_IN_TRANSIT_REFUNDED,
2129
                     OrderStatus.RTO_RECEIVED_PRESTINE : OrderStatus.RTO_REFUNDED,
4486 rajveer 2130
                     OrderStatus.RTO_RECEIVED_DAMAGED : OrderStatus.RTO_DAMAGED_REFUNDED,
2131
                     OrderStatus.RTO_LOST_IN_TRANSIT : OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED,
3366 chandransh 2132
                     OrderStatus.DOA_CERT_INVALID : OrderStatus.DOA_INVALID_REFUNDED,
2133
                     OrderStatus.DOA_CERT_VALID : OrderStatus.DOA_VALID_REFUNDED,
4479 rajveer 2134
                     OrderStatus.DOA_RECEIVED_DAMAGED : OrderStatus.DOA_REFUNDED_RCVD_DAMAGED,
2135
                     OrderStatus.DOA_LOST_IN_TRANSIT : OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT,
4495 rajveer 2136
                     OrderStatus.RET_PRODUCT_UNUSABLE : OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED,
2137
                     OrderStatus.RET_PRODUCT_USABLE : OrderStatus.RET_PRODUCT_USABLE_REFUNDED,
2138
                     OrderStatus.RET_RECEIVED_DAMAGED : OrderStatus.RET_REFUNDED_RCVD_DAMAGED,
2139
                     OrderStatus.RET_LOST_IN_TRANSIT : OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT,
4682 rajveer 2140
                     OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2141
                     OrderStatus.INVENTORY_LOW : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2142
                     OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2143
                     OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2144
                     OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2145
                     OrderStatus.ACCEPTED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
2146
                     OrderStatus.BILLED : OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY,
4247 rajveer 2147
                     OrderStatus.CANCEL_REQUEST_CONFIRMED : OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST,
2148
                     OrderStatus.PAYMENT_FLAGGED : OrderStatus.PAYMENT_FLAGGED_DENIED
3366 chandransh 2149
                     }
2150
        if order.status not in status_transition.keys():
2151
            raise TransactionServiceException(114, "This order can't be refunded")
2152
 
4495 rajveer 2153
        if order.status in [OrderStatus.RTO_RECEIVED_PRESTINE, OrderStatus.RTO_RECEIVED_DAMAGED, OrderStatus.RTO_LOST_IN_TRANSIT] :
5386 phani.kuma 2154
            if order.status != OrderStatus.RTO_LOST_IN_TRANSIT:
2155
                __create_return_order(order)
3226 chandransh 2156
            __create_refund(order)
4495 rajveer 2157
            order.statusDescription = "RTO Refunded"
4662 rajveer 2158
        elif order.status in [OrderStatus.LOST_IN_TRANSIT]:
5386 phani.kuma 2159
            #__create_return_order(order)
4662 rajveer 2160
            __create_refund(order)
2161
            order.statusDescription = "Lost in Transit Refunded"
4495 rajveer 2162
        elif order.status in [OrderStatus.DOA_CERT_INVALID, OrderStatus.DOA_CERT_VALID, OrderStatus.DOA_RECEIVED_DAMAGED, OrderStatus.DOA_LOST_IN_TRANSIT] :
5386 phani.kuma 2163
            if order.status != OrderStatus.DOA_LOST_IN_TRANSIT:
2164
                __create_return_order(order)
4495 rajveer 2165
            __create_refund(order)
2166
            order.statusDescription = "DOA Refunded"
2167
        elif order.status in [OrderStatus.RET_PRODUCT_UNUSABLE, OrderStatus.RET_PRODUCT_USABLE, OrderStatus.RET_RECEIVED_DAMAGED, OrderStatus.RET_LOST_IN_TRANSIT] :
5386 phani.kuma 2168
            if order.status != OrderStatus.RET_LOST_IN_TRANSIT:
2169
                __create_return_order(order)
4495 rajveer 2170
            __create_refund(order)
2171
            order.statusDescription = "Return Refunded"
5199 mandeep.dh 2172
        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 2173
            __update_inventory_reservation(order)
2174
            order.statusDescription = "Order Refunded"
4247 rajveer 2175
        elif order.status == OrderStatus.CANCEL_REQUEST_CONFIRMED:
5272 mandeep.dh 2176
            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 2177
                if order.previousStatus == OrderStatus.ACCEPTED:
2178
                    __create_refund(order)
4247 rajveer 2179
                __update_inventory_reservation(order)
2180
                order.statusDescription = "Order Cancelled on customer request"
2181
            elif order.previousStatus == OrderStatus.BILLED:
2182
                __create_return_order(order)
2183
                __create_refund(order)
2184
                order.statusDescription = "Order Cancelled on customer request"
2185
        elif order.status == OrderStatus.PAYMENT_FLAGGED:
2186
            __update_inventory_reservation(order)
2187
            order.statusDescription = "Order Cancelled due to payment flagged"
3195 chandransh 2188
 
4873 mandeep.dh 2189
    # For orders that are cancelled after being billed, we need to scan in the scanned out
2190
    # inventory item and change availability accordingly
5110 mandeep.dh 2191
    catalogClient = CatalogClient().get_client()
2192
    warehouse = catalogClient.getWarehouse(order.warehouse_id)
2193
    if warehouse.billingType == BillingType.OURS:
4873 mandeep.dh 2194
        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]):
2195
            lineitem = order.lineitems[0]
5177 mandeep.dh 2196
            item = catalogClient.getItem(lineitem.item_id)
5361 mandeep.dh 2197
            warehouseClient = WarehouseClient().get_client()
5177 mandeep.dh 2198
            if ItemType.SERIALIZED == item.type:
2199
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 2200
            else:
2201
                warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4873 mandeep.dh 2202
 
3195 chandransh 2203
    order.status = status_transition[order.status]
2204
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 2205
    order.refunded_by = refunded_by
2206
    order.refund_reason = reason
4873 mandeep.dh 2207
 
2628 chandransh 2208
    session.commit()
2209
    return True
2210
 
3186 chandransh 2211
def __update_inventory_reservation(order):
3191 chandransh 2212
    '''
2213
    Reduce the reservation count for all line items of the given order.
2214
    '''
3186 chandransh 2215
    try:
2216
        catalog_client = CatalogClient().get_client()
2217
        for lineitem in order.lineitems:
5530 mandeep.dh 2218
            catalog_client.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, lineitem.quantity)
3186 chandransh 2219
    except:
2220
        print "Unable to reduce reservation count"
2221
 
4220 rajveer 2222
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 2223
    current_time = datetime.datetime.now()
2224
    new_order = Order()
2225
    new_order.customer_id = order.customer_id
2226
    new_order.customer_name = order.customer_name
2227
    new_order.customer_city = order.customer_city
2228
    new_order.customer_state = order.customer_state
2229
    new_order.customer_mobilenumber = order.customer_mobilenumber
2230
    new_order.customer_pincode = order.customer_pincode
2231
    new_order.customer_address1 = order.customer_address1
2232
    new_order.customer_address2 = order.customer_address2
2233
    new_order.customer_email = order.customer_email
2234
    new_order.total_amount = order.total_amount
2235
    new_order.total_weight = order.total_weight
2236
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2237
    new_order.statusDescription = 'Submitted for Processing'
2238
    new_order.created_timestamp = current_time
5062 varun.gupt 2239
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 2240
 
2241
    new_order.transaction = order.transaction
4220 rajveer 2242
    new_order.cod = is_cod
5527 anupam.sin 2243
    new_order.orderType = order.orderType
2628 chandransh 2244
 
2245
    for line_item in order.lineitems:
2246
        litem = LineItem()
2247
        litem.item_id = line_item.item_id
2248
        litem.productGroup = line_item.productGroup
2249
        litem.brand = line_item.brand
2250
        if line_item.model_number:
2251
            litem.model_number = line_item.model_number
2252
        if line_item.model_name:    
2253
            litem.model_name = line_item.model_name
2254
        if line_item.color:
2255
            litem.color = line_item.color
2256
        if line_item.extra_info:
2257
            litem.extra_info = line_item.extra_info
2258
        litem.quantity = line_item.quantity
2259
        litem.unit_price = line_item.unit_price
2260
        litem.unit_weight = line_item.unit_weight
2261
        litem.total_price = line_item.total_price
2262
        litem.total_weight = line_item.total_weight
2263
        litem.transfer_price = line_item.transfer_price
4840 mandeep.dh 2264
        litem.dealText = line_item.dealText
2628 chandransh 2265
        litem.order = new_order
2266
 
2267
    logistics_client = LogisticsClient().get_client()
2268
    item_id = new_order.lineitems[0].item_id
5785 mandeep.dh 2269
    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 2270
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2271
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 2272
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 2273
    new_order.logistics_provider_id = logistics_info.providerId
2274
    new_order.airwaybill_no = logistics_info.airway_billno
2275
    new_order.tracking_id = new_order.airwaybill_no
2276
    new_order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
3986 chandransh 2277
    new_order.promised_delivery_time = new_order.expected_delivery_time
4299 rajveer 2278
 
2628 chandransh 2279
    if should_copy_billing_info:
5388 phani.kuma 2280
        new_order.vendorId = order.vendorId
2628 chandransh 2281
        new_order.invoice_number = order.invoice_number
2282
        new_order.billed_by = order.billed_by
2283
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 2284
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
5620 mandeep.dh 2285
        new_order.jacket_number = order.jacket_number
2286
        new_order.lineitems[0].serial_number = order.lineitems[0].serial_number
2287
        new_order.lineitems[0].item_number   = order.lineitems[0].item_number
2628 chandransh 2288
        new_order.accepted_timestamp = current_time
2289
        new_order.billing_timestamp = current_time    
2290
        new_order.status = OrderStatus.BILLED
2291
        new_order.statusDescription = 'Order Billed'
2292
    else:       
3133 rajveer 2293
        catalog_client = CatalogClient().get_client()
5110 mandeep.dh 2294
        catalog_client.reserveItemInWarehouse(item_id, logistics_info.fulfilmentWarehouseId, new_order.lineitems[0].quantity)
2628 chandransh 2295
 
2296
    return new_order
2297
 
2298
def __create_return_order(order):
2687 chandransh 2299
    ret_order = ReturnOrder(order)
2628 chandransh 2300
    return ret_order
2301
 
2302
def __create_refund(order):
4078 chandransh 2303
    payment_client = PaymentClient().get_client()
2304
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 2305
    return
2628 chandransh 2306
 
2536 chandransh 2307
def __get_order_address(order):
2308
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
2309
    if order.customer_address2:
2310
        address = address + order.customer_address2 + "\n"
2311
    address = address + order.customer_city + "\n"
2312
    address = address + order.customer_state + "\n"
2313
    address = address + "PIN " + order.customer_pincode + "\n"
2314
    address = address + "Phone: " + order.customer_mobilenumber
2315
    return address
2316
 
5767 rajveer 2317
def __get_store_address(store):
2318
    address = store.name + "\n" + store.line1 + "\n"
2319
    if store.line2:
2320
        address = address + store.line2 + "\n"
2321
    address = address + store.city + "\n"
2322
    address = address + store.state + "\n"
5802 rajveer 2323
    address = address + "PIN - " + store.pin + "\n"
5793 rajveer 2324
    if store.phone:
5802 rajveer 2325
        address = address + "Phone - " + store.phone + "\n"
5855 rajveer 2326
    address = address +  "Store timings - 11AM to 8PM (7 days)\n"
5767 rajveer 2327
    return address
2328
 
5793 rajveer 2329
def __get_store_address_html(store):
2330
    address = store.name + "<br>" + store.line1 + "<br>"
2331
    if store.line2:
2332
        address = address + store.line2 + "<br>"
2333
    address = address + store.city + "<br>"
2334
    address = address + store.state + "<br>"
5802 rajveer 2335
    address = address + "PIN - " + store.pin + "<br>"
5793 rajveer 2336
    if store.phone:
5802 rajveer 2337
        address = address + "Phone - " + store.phone + "<br>"
5855 rajveer 2338
    address = address +  "Store timings - 7 days: 11AM to 8PM  (7 days)<br>"
5793 rajveer 2339
    return address
2340
 
4815 phani.kuma 2341
def __generate_return_advice(order, warehouse, provider, filename):
2342
    if warehouse.id == 7:
2343
        executive = 'Amit Kumar'
2344
    else:
4966 phani.kuma 2345
        executive = 'Dinesh Kumar'
2536 chandransh 2346
    pdf = Canvas(filename)
2347
    pdf.setFont('Times-Bold',16)
2348
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
2349
    address_text.textLine("To")
4815 phani.kuma 2350
    address_text.textLine(executive)
2536 chandransh 2351
    for line in warehouse.location.split("\n"):
2352
        address_text.textLine(line)
2353
    address_text.textLine("PIN " + warehouse.pincode)
2354
    pdf.drawText(address_text)
2355
 
2356
    pdf.setFont('Times-Roman',12)
2357
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 2358
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 2359
    lineitem = order.lineitems[0] 
4234 rajveer 2360
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 2361
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
2362
    order_text.textLine("Order ID : " + str(order.id))
2363
    pdf.drawText(order_text)
2364
    pdf.showPage()
2365
    pdf.save()
2366
    return filename
2367
 
5806 rajveer 2368
def __push_collection_to_hotspot(order, type):
2369
    try:
2370
        logistics_client = LogisticsClient().get_client()
2371
        store = logistics_client.getPickupStore(order.pickupStoreId)
2372
        store_string = "<store>" + store.hotspotId + "</store>"
2373
        order_string = "<orderno>" + str(order.id) + "</orderno>"
2374
        collection_type = "<Type>" + type + "</Type>"
5833 rajveer 2375
        payment_mode = get_order_attribute_value(order.id, "PAYMENT_MODE")
5806 rajveer 2376
        if type == "SALE":
2377
            amount = int(order.total_amount)
2378
            ts = order.delivery_timestamp
2379
        if type == "SALE RETURN":
2380
            amount = -int(order.total_amount)
2381
            ts = order.refund_timestamp
2382
        if payment_mode == "Cash":
2383
            cash_string = "<cash>" + str(amount) + "</cash>"
2384
            card_string = "<hdfc>0</hdfc>"
2385
        if payment_mode == "Card":
2386
            cash_string = "<cash>0</cash>"
2387
            card_string = "<hdfc>" + str(amount) + "</hdfc>"
2388
        date_string = "<date>" + ts.strftime("%Y%m%d") + "</date>"
2389
        time_string = "<time>" + ts.strftime("%H%M%S") + "</time>"
2390
 
2391
        conn = httplib.HTTPConnection("182.71.104.182")
2392
        XML="""
2393
        <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/">
2394
          <soap:Body>
2395
            <SaholicDataTransfer xmlns="http://tempuri.org/">
2396
        """
2397
 
2398
        XML = XML + store_string + order_string + collection_type + cash_string + card_string + date_string + time_string 
2399
 
2400
        footer = """
2401
            </SaholicDataTransfer>
2402
          </soap:Body>
2403
        </soap:Envelope>
2404
        """
2405
        XML = XML + footer
2406
 
2407
        params = urllib.urlencode({'op': 'SaholicDataTransfer'})
2408
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
2409
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
2410
        conn.send(XML)
2411
        response = conn.getresponse()
2412
        print response.status, response.reason
2413
        resp = response.read()
2414
        conn.close()
2415
        print resp
2416
        if "Saved Successfully" in resp:
2417
            return True
2418
        elif "Error in Saving Data" in resp:
2419
            return False
2420
        else: 
2421
            return False
2422
    except Exception as e:
2423
        print e
2424
        return False
2425
 
2697 chandransh 2426
def get_return_orders(warehouse_id, from_date, to_date):
2427
    query = ReturnOrder.query.filter_by(processedStatus = False)
2428
    if warehouse_id != -1:
2429
        query = query.filter_by(warehouseId = warehouse_id)
2430
    if from_date:
4118 chandransh 2431
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 2432
    if to_date:
4118 chandransh 2433
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 2434
    return [return_order.to_thrift_object() for return_order in query.all()]
2435
 
5481 phani.kuma 2436
def get_all_return_orders(onlyNotProcessed, from_date, to_date):
2437
    query = ReturnOrder.query
2438
    if onlyNotProcessed:
2439
        query = query.filter_by(processedStatus = False)
2440
    if from_date:
2441
        query = query.filter(ReturnOrder.createdAt >= from_date)
2442
    if to_date:
2443
        query = query.filter(ReturnOrder.createdAt <= to_date)
2444
    return [return_order.to_thrift_object() for return_order in query.all()]
2445
 
2700 chandransh 2446
def get_return_order(id):
2447
    ret_order = ReturnOrder.get_by(orderId = id)
2448
    if ret_order is None:
2449
        raise TransactionServiceException(116, "No return order found for the given order id")
2450
    return ret_order.to_thrift_object()
2451
 
2697 chandransh 2452
def process_return(ret_order_id):
2453
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
2454
    if ret_order is None:
2455
        raise TransactionServiceException(116, "No return order found for the given order id")
2456
    ret_order.processedStatus = True
2701 chandransh 2457
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 2458
    session.commit()
2459
 
4757 mandeep.dh 2460
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
2461
    """
2462
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
2463
    the quantities for which the PO is raised.
2464
 
2465
    Parameters:
2466
     - itemIdQuantityMap
2467
     - purchaseOrderId
2468
     - warehouseId
2469
    """
3451 chandransh 2470
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 2471
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 2472
    query = query.filter_by(purchase_order_id=None)
2473
    query = query.order_by(Order.created_timestamp)
2474
    pending_orders = query.all()
4586 mandeep.dh 2475
 
2476
    for order in pending_orders:
4757 mandeep.dh 2477
        lineitem = order.lineitems[0]
2478
        if itemIdQuantityMap.has_key(lineitem.item_id):
2479
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
2480
                order.status = OrderStatus.LOW_INV_PO_RAISED
2481
                order.statusDescription = 'In Process'
2482
                order.purchase_order_id = purchaseOrderId
2483
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 2484
 
2819 chandransh 2485
    session.commit()
2486
 
3451 chandransh 2487
def update_weight(order_id, weight):
3469 chandransh 2488
    '''
2489
    Update the weight of order
2490
    '''
3451 chandransh 2491
    order = get_order(order_id)
2492
    order.total_weight = weight
3469 chandransh 2493
    lineitem = order.lineitems[0]
2494
    lineitem.total_weight = weight
2495
    lineitem.unit_weight = weight
3451 chandransh 2496
 
3469 chandransh 2497
    session.commit()
2498
    return order
2499
 
2500
def change_product(order_id, item_id):
2501
    '''
2502
    Ship a product of a different color to the customer.
2503
    '''
2504
    order = get_order(order_id)
4662 rajveer 2505
    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 2506
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
2507
 
2508
    lineitem = order.lineitems[0]
3451 chandransh 2509
 
3469 chandransh 2510
    catalog_client = CatalogClient().get_client()
2511
 
2512
    old_item = catalog_client.getItem(lineitem.item_id)
2513
    item = catalog_client.getItem(item_id)
2514
    if old_item.catalogItemId != item.catalogItemId:
2515
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
2516
 
5110 mandeep.dh 2517
    catalog_client.reserveItemInWarehouse(item_id, order.fulfilmentWarehouseId, lineitem.quantity)
2518
    __update_inventory_reservation(order)
3469 chandransh 2519
    #TODO: Check that this new item has the same price
2520
 
2521
    lineitem.item_id = item_id
2522
    lineitem.color = item.color
2523
 
3451 chandransh 2524
    session.commit()
3469 chandransh 2525
 
2526
    order = get_order(order_id)
3451 chandransh 2527
    return order
3469 chandransh 2528
 
2529
def change_warehouse(order_id, warehouse_id):
2530
    '''
2531
    Update the warehouse which will be used to fulfil this order.
2532
    '''
2533
    order = get_order(order_id)
4662 rajveer 2534
    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 2535
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
2536
 
2537
    if warehouse_id == order.warehouse_id:
2538
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
2539
 
2540
    lineitem = order.lineitems[0]
2541
    catalog_client = CatalogClient().get_client()
2542
    try:
2543
        warehouse = catalog_client.getWarehouse(warehouse_id)
2544
    except:
2545
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 2546
 
5147 mandeep.dh 2547
    if warehouse.billingWarehouseId is None:
2548
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 2549
 
5620 mandeep.dh 2550
    # If One gives a billing warehouse for warehouse shift, we should assign order to the GOOD warehouse
2551
    # present within it with maximum availability
2552
    if warehouse.id == warehouse.billingWarehouseId:
5147 mandeep.dh 2553
        warehouses = catalog_client.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
2554
        if warehouses:
2555
            itemInventory = catalog_client.getItemInventoryByItemId(lineitem.item_id)
2556
            warehouse = warehouses[0]
2557
            maxAvailability = 0
2558
            for goodWarehouse in warehouses:
2559
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
2560
                    warehouse = goodWarehouse
2561
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
2562
 
2563
            # Use preferred vendor's warehouse if not available anywhere
2564
            if not maxAvailability:
2565
                item = catalog_client.getItem(lineitem.item_id)
2566
                if item.preferredVendor:
2567
                    for goodWarehouse in warehouses:
2568
                        if goodWarehouse.vendor.id == item.preferredVendor:
2569
                            warehouse = goodWarehouse
2570
        else:
2571
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
2572
 
5199 mandeep.dh 2573
    catalog_client.reserveItemInWarehouse(lineitem.item_id, warehouse.id, lineitem.quantity)
5110 mandeep.dh 2574
    __update_inventory_reservation(order)
2575
 
2576
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 2577
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 2578
    session.commit()
2579
    return order
3553 chandransh 2580
 
4647 rajveer 2581
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 2582
    '''
3994 chandransh 2583
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 2584
    '''
2585
    order = get_order(order_id)
2586
    try:
3581 chandransh 2587
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 2588
        order.delayReasonText = delayReasonText
4009 chandransh 2589
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
2590
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 2591
 
4842 rajveer 2592
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
2593
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 2594
 
3553 chandransh 2595
        session.commit()
4008 mandeep.dh 2596
 
2597
        try:
2598
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
2599
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
2600
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
2601
            session.commit()
2602
        except Exception as e:
4065 mandeep.dh 2603
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 2604
 
3553 chandransh 2605
        return True
2606
    except:
3994 chandransh 2607
        print sys.exc_info()[0]
3553 chandransh 2608
        return False
3956 chandransh 2609
 
2610
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
2611
    unprocessed_awbs = {}
2612
    for awb, amount in collected_amount_map.iteritems():
2613
        try:
2614
            order = Order.query.filter_by(airwaybill_no=awb).one()
2615
        except NoResultFound:
2616
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
2617
            continue
2618
        except MultipleResultsFound:
2619
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
2620
            continue
2621
 
2622
        if order.cod_reconciliation_timestamp:
2623
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
2624
            continue
2625
 
2626
        if order.status < OrderStatus.DELIVERY_SUCCESS:
2627
            #Order has not been delivered yet. No way we can receive the payment.
2628
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
2629
            continue
2630
 
4252 rajveer 2631
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
2632
        if abs(amount - order.total_amount) > 0.5:
3956 chandransh 2633
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
2634
            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)
2635
            continue
2636
 
2637
        try:
2638
            payment_client = PaymentClient().get_client()
2639
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
2640
        except Exception:
2641
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
2642
            continue
2643
 
2644
        #Payment has been recorded now. We can update the order peacefully.
2645
        order.cod_reconciliation_timestamp = datetime.datetime.now()
2646
        session.commit()
3469 chandransh 2647
 
3956 chandransh 2648
    return unprocessed_awbs
4008 mandeep.dh 2649
 
2650
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 2651
    """
2652
    Returns the list of transaction ids that require some extra processing and
2653
    which belong to a particular category. This is currently used by CRM
2654
    application. If no such transaction ids are present, it returns an empty list.
2655
    """
2656
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 2657
 
4065 mandeep.dh 2658
    if category is not None:
2659
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 2660
 
4065 mandeep.dh 2661
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 2662
 
2663
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 2664
    """
2665
    Marks a particular transaction as processed for a particular cateogory.
2666
    It essentially deletes the transaction id record for a particular
2667
    processing type category (if present) from DB.
2668
    This is currently used by CRM application.
2669
    """
4008 mandeep.dh 2670
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
2671
    session.commit()
2672
 
4018 chandransh 2673
def get_item_wise_risky_orders_count():
2674
    """
2675
    Returns a map containing the number of risky orders keyed by item id. A risky order
2676
    is defined as one whose shipping date is about to expire.
2677
    """
2678
    item_wise_risky_orders_count = {}
4019 chandransh 2679
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 2680
    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()
2681
    for order in orders:
2682
        for lineitem in order.lineitems:
2683
            quantity = lineitem.quantity
2684
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
2685
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
2686
 
2687
            item_wise_risky_orders_count[lineitem.item_id] = quantity
2688
    return item_wise_risky_orders_count
2689
 
4324 mandeep.dh 2690
def update_shipment_address(order_id, address_id):
2691
    """
2692
    Updates shipment address of an order. Delivery and shipping date estimates
2693
    etc. are also updated here.
2694
 
2695
    Throws TransactionServiceException in case address change is not
2696
    possible due to certain reasons such as new pincode in address is
2697
    not serviceable etc.
2698
 
2699
    Parameters:
2700
     - orderId
2701
     - addressId
2702
    """
2703
    user_client = UserClient().get_client()
2704
    address     = user_client.getAddressById(address_id)
2705
    order       = get_order(order_id)
2706
 
4630 mandeep.dh 2707
    type = DeliveryType.PREPAID
2708
    if order.cod:
2709
        type = DeliveryType.COD
2710
 
4324 mandeep.dh 2711
    logistics_client = LogisticsClient().get_client()
5793 rajveer 2712
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type, PickUpType.COURIER)
4324 mandeep.dh 2713
 
2714
    # Check for new estimate. Raise exception if new address is not serviceable
2715
    if logistics_info.deliveryTime == -1:
2716
        raise TransactionServiceException(1, 'Location not serviceable')
2717
 
2718
    # COD services are not available everywhere
2719
    if order.cod:
4868 rajveer 2720
        if not logistics_info.codAllowed:
4324 mandeep.dh 2721
            raise TransactionServiceException(2, 'COD service not available')
2722
 
5593 mandeep.dh 2723
    if logistics_info.providerId != order.logistics_provider_id:
5793 rajveer 2724
        logistics_info = logistics_client.getLogisticsInfo(address.pin, order.lineitems[0].item_id, type)
5593 mandeep.dh 2725
        order.tracking_id = logistics_info.airway_billno
2726
        order.airwaybill_no = logistics_info.airway_billno
2727
        order.logistics_provider_id = logistics_info.providerId
2728
 
4324 mandeep.dh 2729
    current_time = datetime.datetime.now()
2730
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2731
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2732
 
2733
    order.customer_name         = address.name
2734
    order.customer_pincode      = address.pin
2735
    order.customer_address1     = address.line1
2736
    order.customer_address2     = address.line2
2737
    order.customer_city         = address.city
2738
    order.customer_state        = address.state
2739
    order.customer_mobilenumber = address.phone
2740
 
2741
    if order.cod:
2742
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2743
    else:
2744
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2745
 
2746
    order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
2747
    order.promised_shipping_time = order.expected_shipping_time
2748
    order.promised_delivery_time = order.expected_delivery_time 
2749
 
2750
    session.commit()
2751
 
4247 rajveer 2752
def mark_order_cancellation_request_received(orderId):
2753
    """
2754
    Mark order as cancellation request received. If customer sends request of cancellation of
2755
    a particular order, this method will be called. It will just change status of the order
2756
    depending on its current status. It also records the previous status, so that we can move
2757
    back to that status if cancellation request is denied.
2758
 
2759
    Parameters:
2760
     - orderId
2761
    """
4662 rajveer 2762
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2763
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
2764
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 2765
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2766
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
2767
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 2768
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2769
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
2770
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
2771
             }
4662 rajveer 2772
 
2773
    order = get_order(orderId)
4247 rajveer 2774
    if order.status not in status_transition.keys():
2775
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
2776
 
4662 rajveer 2777
 
4247 rajveer 2778
    order.previousStatus = order.status
2779
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
2780
    order.statusDescription = "Cancellation request received from user"
2781
    session.commit()
2782
 
4662 rajveer 2783
def mark_order_as_lost_in_transit(orderId):
2784
    """
2785
    Parameters:
2786
     - orderId
2787
    """
2788
    order = get_order(orderId)
4910 phani.kuma 2789
    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 2790
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
2791
    order.status = OrderStatus.LOST_IN_TRANSIT
2792
    order.statusDescription = "Lost in Transit"
2793
    session.commit()
2794
 
4258 rajveer 2795
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 2796
    """
4258 rajveer 2797
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
2798
    Changed transaction and all orders status to payment accepted.
4247 rajveer 2799
 
2800
    Parameters:
4258 rajveer 2801
     - transactionId
4247 rajveer 2802
    """
4258 rajveer 2803
    transaction = get_transaction(transactionId)
2804
    transaction.status = TransactionStatus.AUTHORIZED
2805
    for order in transaction.orders:
2806
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2807
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 2808
    session.commit()
2809
 
4259 anupam.sin 2810
def refund_transaction(transactionId, refundedBy, reason):
2811
    """
2812
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
2813
    need to be cancelled
2814
 
2815
    Parameters:
2816
     - transactionId
2817
    """
2818
    transaction = get_transaction(transactionId)
2819
    transaction.status = TransactionStatus.FAILED
2820
    for order in transaction.orders:
2821
        refund_order(order.id, refundedBy, reason)
2822
    session.commit()
2823
 
4247 rajveer 2824
def mark_order_cancellation_request_denied(orderId):
2825
    """
4283 anupam.sin 2826
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 2827
 
2828
    Parameters:
2829
     - orderId
2830
    """
2831
    order = get_order(orderId)
2832
    order.status = order.previousStatus
2833
    order.previousStatus = None
2834
    order.statusDescription = "Cancellation request denied"
2835
    session.commit()
2836
 
2837
def mark_order_cancellation_request_confirmed(orderId):
2838
    """
2839
    If we decide to to cancel order, CRM will call this method to move the status of order to
2840
    cancellation request confirmed. After this OM will be able to cancel the order.
2841
 
2842
    Parameters:
2843
     - orderId
2844
    """
2845
    order = get_order(orderId)
2846
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
2847
    order.statusDescription = "Cancellation request confirmed"
2848
    session.commit()
2849
 
4285 rajveer 2850
def accept_orders_for_item_id(itemId, inventory):
2851
    """
2852
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
2853
    given order is not a COD order, it also captures the payment if the same has not been captured.
2854
 
2855
    Parameters:
2856
     - itemId
2857
     - inventory
2858
    """
4938 rajveer 2859
    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 2860
    for order in orders:
4301 rajveer 2861
        if inventory > 0:
2862
            lineitem = order.lineitems[0]
2863
            if itemId == lineitem.item_id:
2864
                try:
2865
                    accept_order(order.id)
2866
                    inventory = inventory - lineitem.quantity
2867
                except:
2868
                    logging.info("Unable to accept the order")
2869
        else:
2870
            order_outofstock(order.id)
4285 rajveer 2871
    return
2872
 
4607 rajveer 2873
def get_slipped_sipping_date_orders():
4662 rajveer 2874
    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 2875
 
2876
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
2877
    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 2878
 
4369 rajveer 2879
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
2880
    if isReminder:
2881
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2882
    else:
2883
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2884
 
2885
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2886
    for order in orders:
2887
        lineitem = order.lineitems[0]
2888
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2889
            if estimate > 0:
2890
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2891
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 2892
            order.statusDescription = "PO Raised"
4303 rajveer 2893
            quantity = quantity - lineitem.quantity
2894
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
2895
            session.commit()
2896
 
4369 rajveer 2897
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
2898
    if isReminder:
2899
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2900
    else:
2901
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2902
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2903
    for order in orders:
2904
        lineitem = order.lineitems[0]
2905
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2906
            if estimate > 0:
2907
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
2908
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 2909
            order.statusDescription = "Reversal Initiated"
4303 rajveer 2910
            quantity = quantity - lineitem.quantity
2911
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
2912
            session.commit()
2913
 
4369 rajveer 2914
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
2915
    if isReminder:
2916
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
2917
    else:
2918
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
2919
 
2920
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 2921
    for order in orders:
2922
        lineitem = order.lineitems[0]
2923
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
2924
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 2925
            order.statusDescription = "Not Available"
4303 rajveer 2926
            quantity = quantity - lineitem.quantity
2927
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
2928
            session.commit()
2929
 
2930
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 2931
    orderInv = OrderInventory.get_by(order_id=order.id)
2932
    if not orderInv:
2933
        orderInv = OrderInventory()
2934
        orderInv.order = order
4303 rajveer 2935
    orderInv.hotspotAction = hotspotAction  
2936
    orderInv.estimate = estimate
2937
    orderInv.itemId = itemId
2938
    orderInv.timestamp = datetime.datetime.now()
2939
    orderInv.quantity = quantity
2940
 
4556 mandeep.dh 2941
'''    
4369 rajveer 2942
def mark_orders_as_timeout(vendorId):
2943
    ret_timeouts = {}
2944
    orderInvs = OrderInventory.query.all()
2945
    for orderInv in orderInvs:
2946
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
2947
            if not ret_timeouts.has_key(orderInv.itemId):
2948
                timeout = TimeoutSummary()
2949
                ret_timeouts[orderInv.itemId] = timeout
2950
            else:
2951
                timeout = ret_timeouts.get(orderInv.itemId)
2952
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2953
                if timeout.poRaised:
2954
                    timeout.poRaised += 1
2955
                else:
2956
                    timeout.poRaised = 1
2957
 
2958
                if timeout.poEstimate:
2959
                    timeout.poEstimate += orderInv.estimate
2960
                else:
2961
                    timeout.poEstimate = orderInv.estimate
2962
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
2963
                orderInv.order.statusDescription = "PO Raised Timeout"
2964
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
2965
                if timeout.reversalInitiated:
2966
                    timeout.reversalInitiated += 1
2967
                else:
2968
                    timeout.reversalInitiated = 1
2969
 
2970
                if timeout.reversalEstimate:
2971
                    timeout.reversalEstimate += orderInv.estimate
2972
                else:
2973
                    timeout.reversalEstimate = orderInv.estimate
2974
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
2975
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
2976
            else:
2977
                orderInv.delete()
2978
    session.commit()
2979
    return ret_timeouts
4556 mandeep.dh 2980
'''
2981
 
2982
 
2983
def mark_orders_as_timeout(vendorId):
2984
    ret_timeouts = {}
2985
    orderInvs = OrderInventory.query.all()
2986
    for orderInv in orderInvs:
2987
        if not ret_timeouts.has_key(orderInv.itemId):
2988
            timeout = TimeoutSummary()
2989
            ret_timeouts[orderInv.itemId] = timeout
2990
        else:
2991
            timeout = ret_timeouts.get(orderInv.itemId)
2992
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
2993
            if timeout.poRaised:
2994
                timeout.poRaised += 1
2995
            else:
2996
                timeout.poRaised = 1
2997
 
2998
            if timeout.poEstimate:
2999
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
3000
            else:
3001
                timeout.poEstimate = orderInv.estimate
3002
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3003
            if timeout.reversalInitiated:
3004
                timeout.reversalInitiated += 1
3005
            else:
3006
                timeout.reversalInitiated = 1
3007
 
3008
            if timeout.reversalEstimate:
3009
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
3010
            else:
3011
                timeout.reversalEstimate = orderInv.estimate
3012
        orderInv.order.status = OrderStatus.INVENTORY_LOW
3013
        orderInv.order.statusDescription = "Low Inventory"
3014
        orderInv.delete()
3015
    session.commit()
3016
    return ret_timeouts
3017
 
4386 anupam.sin 3018
def get_order_for_awb(awb):
3019
    order = Order.get_by(airwaybill_no=awb)
3020
    if not order:
3021
        raise TransactionServiceException(108, "no such order")
3022
 
3023
    return order
4369 rajveer 3024
 
4910 phani.kuma 3025
def get_orders_for_provider_for_status(provider_id, order_status_list):
3026
    if not provider_id or not order_status_list:
4506 phani.kuma 3027
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 3028
    doa_provider = False
3029
    for order_status in order_status_list:
3030
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
3031
            doa_provider = True
3032
    if doa_provider:
3033
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 3034
    else:
4910 phani.kuma 3035
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 3036
    return query.all()
4386 anupam.sin 3037
 
4600 varun.gupt 3038
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 3039
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
3040
 
3041
    if vendor_id:
3042
        query = query.filter_by(vendorId = vendor_id)
3043
 
4600 varun.gupt 3044
    if billing_date_from:
3045
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 3046
 
4600 varun.gupt 3047
    if billing_date_to:
3048
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 3049
 
4600 varun.gupt 3050
    return query.all()
3051
 
5481 phani.kuma 3052
def get_billed_orders(vendor_id, onlyVendorNotPaid, billing_date_from, billing_date_to):
5386 phani.kuma 3053
    query = Order.query.filter(Order.billing_timestamp != None)
5481 phani.kuma 3054
 
3055
    if onlyVendorNotPaid:
5488 phani.kuma 3056
        query = query.filter_by(vendor_paid = False)
5481 phani.kuma 3057
 
5386 phani.kuma 3058
    if vendor_id != -1:
3059
        query = query.filter_by(vendorId = vendor_id)
3060
 
5481 phani.kuma 3061
    if billing_date_from:
3062
        query = query.filter(Order.billing_timestamp >= billing_date_from)
3063
 
3064
    if billing_date_to:
3065
        query = query.filter(Order.billing_timestamp <= billing_date_to)
3066
 
4885 varun.gupt 3067
    return query.all()
4875 varun.gupt 3068
 
4600 varun.gupt 3069
def save_bluedart_settlements(map_awb_and_amount):
3070
    payment_client = PaymentClient().get_client()
3071
 
3072
    for awb, amount in map_awb_and_amount.iteritems():
3073
        order = Order.get_by(airwaybill_no = awb)
3074
 
3075
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
3076
        settlement = PaymentSettlement()
3077
        settlement.paymentId = payment.paymentId
3078
        settlement.paymentGatewayId = payment.gatewayId
3079
        settlement.netCollection = amount
3080
        session.commit()
3081
 
4905 varun.gupt 3082
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 3083
    originalOrderId = None
3084
    if paymentGatewayId == 4:
3085
        cod_order = Order.get_by(id = referenceId)
3086
        if cod_order.originalOrderId:
3087
            originalOrderId = cod_order.originalOrderId
3088
        else:
3089
            originalOrderId = referenceId
4600 varun.gupt 3090
    settlement = PaymentSettlement()
3091
    settlement.settlementDate = settlementDate
3092
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 3093
    if originalOrderId is not None:
3094
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 3095
    settlement.referenceId = referenceId
4600 varun.gupt 3096
    settlement.serviceTax = serviceTax
3097
    settlement.otherCharges = otherCharges
3098
    settlement.netCollection = netCollection
3099
    session.commit()
3100
 
5386 phani.kuma 3101
def get_settlement_for_Prepaid(reference_id, is_refund = False):
3102
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 3103
 
5189 varun.gupt 3104
    if is_refund:
3105
        query = query.filter(PaymentSettlement.netCollection < 0)
3106
    else:
3107
        query = query.filter(PaymentSettlement.netCollection > 0)
3108
 
5386 phani.kuma 3109
    return query.first()
3110
 
3111
def get_settlement_for_Cod(orderId, is_refund = False):
3112
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 3113
 
5386 phani.kuma 3114
    if is_refund:
3115
        query = query.filter(PaymentSettlement.netCollection < 0)
3116
    else:
3117
        query = query.filter(PaymentSettlement.netCollection > 0)
3118
 
5189 varun.gupt 3119
    return query.first()
4600 varun.gupt 3120
 
3121
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
5551 phani.kuma 3122
    summary = EBSSettlementSummary.query.filter_by(settlementId = settlement_id).first()
5481 phani.kuma 3123
    if summary is None:
3124
        summary = EBSSettlementSummary()
3125
        summary.settlementId = settlement_id
3126
        summary.settlementDate = settlement_date
3127
        summary.transactionDateFrom = transaction_date_from
3128
        summary.transactionDateTo = transaction_date_to
3129
        summary.amount = amount
3130
        summary.detailsUploaded = False
3131
        session.commit()
4600 varun.gupt 3132
 
3133
def get_ebs_settlement_summaries():
3134
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
3135
    summary_map = {}
3136
 
3137
    for summary in summaries:
3138
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
3139
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
3140
 
3141
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
3142
 
3143
    return summary_map
3144
 
3145
def get_ebs_settlement_date(settlement_id):
3146
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3147
 
3148
    if summary:
3149
        return summary.settlementDate
3150
 
3151
def mark_ebs_settlement_uploaded(settlement_id):
3152
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3153
 
3154
    if summary:
3155
        summary.detailsUploaded = True
3156
        session.commit()
4715 varun.gupt 3157
 
3158
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
3159
    query = PaymentSettlement.query
4600 varun.gupt 3160
 
4715 varun.gupt 3161
    if settlement_date_from:
3162
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
3163
 
3164
    if settlement_date_to:
3165
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
3166
 
4749 varun.gupt 3167
    if is_refund is True:
3168
        query = query.filter(PaymentSettlement.netCollection < 0.0)
3169
    else:
3170
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 3171
 
4749 varun.gupt 3172
    return query.all()
4715 varun.gupt 3173
 
3174
def get_reshipped_order_ids(order_ids):
3175
    reshipped_order_ids = []
3176
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
3177
 
4749 varun.gupt 3178
def get_shipping_confirmation_email_body(order):
3179
 
3180
    html = """
3181
<html>
3182
<body>
3183
<div>
3184
    <p>Dear Customer,</p>
3185
    <p>
4885 varun.gupt 3186
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 3187
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
4749 varun.gupt 3188
    </p>
3189
    <p>
3190
        Expected delivery date for your order is $expected_delivery_date. 
3191
        The product can be delivered to you between business hours of 10am to 6pm. 
3192
        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.
3193
    </p>
3194
    <p>
5573 amit.gupta 3195
        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 3196
    </p>
5139 varun.gupt 3197
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 3198
    <p>
3199
        Warm Regards,<br />
3200
        Saholic Team
3201
    </p>
4750 varun.gupt 3202
</div>
4749 varun.gupt 3203
</body>
3204
</html>
3205
    """
5573 amit.gupta 3206
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}}
5139 varun.gupt 3207
    provider_name = logistics_providers[order.logistics_provider_id]['name']
3208
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
3209
 
5868 rajveer 3210
    lclient = LogisticsClient().get_client()
3211
    logistics_info = lclient.getLogisticsEstimation(order.lineitems[0].item_id, order.customer_pincode, DeliveryType.PREPAID)
4749 varun.gupt 3212
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 3213
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
4749 varun.gupt 3214
    product = "%s %s %s" % (order.lineitems[0].brand, order.lineitems[0].model_name, order.lineitems[0].model_number)
5868 rajveer 3215
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (logistics_info.deliveryTime - logistics_info.shippingTime)))
4885 varun.gupt 3216
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
5139 varun.gupt 3217
    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 3218
    return Template(html).substitute(info)
4749 varun.gupt 3219
 
5832 rajveer 3220
def enqueue_shipping_confirmation_email(order):
4915 varun.gupt 3221
    # Calling helper service on production
3222
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5832 rajveer 3223
    try:
3224
        emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
3225
        emailBody = get_shipping_confirmation_email_body(order)
5866 rajveer 3226
        helperClient.saveUserEmailForSending([order.customer_email], None, emailSubject, emailBody, str(order.id), 'ShippingConfirmation', [], [])
5832 rajveer 3227
    except Exception as e:
3228
        print e
5139 varun.gupt 3229
 
4915 varun.gupt 3230
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 3231
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
3232
    query = query.filter(Order.created_timestamp >= start_date)
3233
    query = query.filter(Order.created_timestamp <= end_date)
3234
    return query.all()
4915 varun.gupt 3235
 
5067 varun.gupt 3236
def get_order_ids_for_status(status, start_datetime, end_datetime):
3237
    query = Order.query.filter(Order.status == status)
3238
    query = query.filter(Order.created_timestamp >= start_datetime)
3239
    query = query.filter(Order.created_timestamp <= end_datetime)
3240
    return query.all()
3241
 
5099 varun.gupt 3242
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 3243
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 3244
 
5139 varun.gupt 3245
    if paid_order.originalOrderId is None:
3246
        paid_order.vendor_paid = True
5099 varun.gupt 3247
        session.commit()
5139 varun.gupt 3248
 
3249
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
3250
            order.vendor_paid = True
3251
            session.commit()
3252
    else:
5208 varun.gupt 3253
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 3254
 
5208 varun.gupt 3255
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 3256
            order.vendor_paid = True
3257
            session.commit()
3258
 
3259
        original_order = Order.get_by(id = original_order_id)
3260
        if original_order:  original_order.vendor_paid = True
3261
        session.commit()
5348 anupam.sin 3262
 
3263
def update_COD_agent(agentEmailId, orderId):
3264
    order = Order.get_by(id=orderId)
3265
    if not order:
3266
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
3267
    agent = CodVerificationAgent()
3268
    agent.orderId = orderId
3269
    agent.verificationAgent = agentEmailId
3270
    session.commit()
3271
 
5099 varun.gupt 3272
 
5386 phani.kuma 3273
def update_order_only_as_paid_to_vendor(order_id):
3274
    paid_order = Order.get_by(id = order_id)
3275
    if paid_order is None:
3276
        raise TransactionServiceException(116, "No order found for the given order id")
3277
    paid_order.vendor_paid = True
3278
    session.commit()
3279
 
5208 varun.gupt 3280
def get_refunded_orders_marked_paid():
3281
    orderStatusGroup = OrderStatusGroups()
3282
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
3283
 
5447 anupam.sin 3284
def get_all_verification_agents(minOrderId, maxOrderId):
3285
    return CodVerificationAgent.query.filter(CodVerificationAgent.orderId >= minOrderId).filter(CodVerificationAgent.orderId <= maxOrderId).all()
3286
 
5527 anupam.sin 3287
def get_all_attributes_for_order_id(orderId):
3288
    return Attribute.query.filter(Attribute.orderId == orderId).all()
3289
 
3290
def set_order_attribute_for_transaction(transactionId, t_attribute):
3291
    for order in Order.query.filter_by(transaction_id = transactionId).all():
3292
        attribute = Attribute()
3293
        attribute.orderId = order.id
3294
        attribute.name = t_attribute.name
3295
        attribute.value = t_attribute.value
3296
        session.commit()
5593 mandeep.dh 3297
 
5558 mandeep.dh 3298
def accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
3299
    catalogClient = CatalogClient().get_client()
3300
    inventory = catalogClient.getItemInventoryByItemId(itemId)
5684 mandeep.dh 3301
    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 3302
    for order in orders:
5593 mandeep.dh 3303
        lineitem = order.lineitems[0]
5558 mandeep.dh 3304
        if lineitem.item_id == itemId and lineitem.quantity <= quantity:
3305
            warehouse = catalogClient.getWarehouse(order.fulfilmentWarehouseId)
5684 mandeep.dh 3306
            if not warehouse.billingWarehouseId and warehouse.warehouseType == WarehouseType.THIRD_PARTY:
3307
                if (inventory.availability[fulfilmentWarehouseId] >= inventory.reserved[fulfilmentWarehouseId] + lineitem.quantity) and inventory.availability[order.fulfilmentWarehouseId] < inventory.reserved[order.fulfilmentWarehouseId]:
3308
                    catalogClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, quantity)
3309
                    catalogClient.reserveItemInWarehouse(itemId, fulfilmentWarehouseId, quantity)
3310
                    order.fulfilmentWarehouseId = fulfilmentWarehouseId
5558 mandeep.dh 3311
                    quantity -= lineitem.quantity
5684 mandeep.dh 3312
                    session.commit()
5593 mandeep.dh 3313
                    if not quantity:
3314
                        break
5558 mandeep.dh 3315
 
766 rajveer 3316
def close_session():
3317
    if session.is_active:
3318
        print "session is active. closing it."
2783 chandransh 3319
        session.close()
3376 rajveer 3320
 
3321
def is_alive():
3322
    try:
3323
        session.query(Transaction.id).limit(1).one()
3324
        return True
3325
    except:
4343 varun.gupt 3326
        return False