Subversion Repositories SmartDukaan

Rev

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