Subversion Repositories SmartDukaan

Rev

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