Subversion Repositories SmartDukaan

Rev

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