Subversion Repositories SmartDukaan

Rev

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