Subversion Repositories SmartDukaan

Rev

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