Subversion Repositories SmartDukaan

Rev

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