Subversion Repositories SmartDukaan

Rev

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