Subversion Repositories SmartDukaan

Rev

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