Subversion Repositories SmartDukaan

Rev

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