Subversion Repositories SmartDukaan

Rev

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