Subversion Repositories SmartDukaan

Rev

Rev 6751 | Rev 6757 | 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
        if ItemType.SERIALIZED == item.type and not (serialNumbers and serialNumbers[0]):
1180
            raise TransactionServiceException(110, "No Serial Number supplied")
1181
        if serialNumbers:
1182
            lineitem.serial_number = serialNumbers[0]
1183
 
1184
        if billingType == BillingType.EXTERNAL or billingType == BillingType.OURS_EXTERNAL:
5411 rajveer 1185
            if itemNumbers:
1186
                lineitem.item_number = itemNumbers[0]    
1187
            if ItemType.SERIALIZED == item.type and not (serialNumbers and serialNumbers[0]):
1188
                raise TransactionServiceException(110, "No Serial Number supplied")
1189
            if serialNumbers:
1190
                lineitem.serial_number = serialNumbers[0]
6751 amar.kumar 1191
 
4763 rajveer 1192
            if billedOrdersColorMap.has_key(orderId):
1193
                etpColor = billedOrdersColorMap.get(orderId)
1194
                ourColor = order.lineitems[0].color
4781 rajveer 1195
                if ourColor and etpColor != ourColor and not authorize:
4763 rajveer 1196
                    raise TransactionServiceException(777, "ETP color: " + etpColor + " and Order color: " + ourColor)
1197
                else:
1198
                    billedOrdersColorMap.pop(orderId)
6751 amar.kumar 1199
 
1200
        if billingType == BillingType.EXTERNAL:            
1201
            order.invoice_number = invoice_number
1202
 
1203
        if billingType == BillingType.OURS or billingType == BillingType.OURS_EXTERNAL:
1204
            order.invoice_number = get_next_invoice_number(order.orderType)
4283 anupam.sin 1205
 
2842 chandransh 1206
        order.status = OrderStatus.BILLED
1207
        order.statusDescription = "Order Billed"
1208
        order.billing_timestamp = datetime.datetime.now()
4285 rajveer 1209
        order.billed_by = billedBy
4435 mandeep.dh 1210
 
5436 mandeep.dh 1211
        # Letting the billing process fail in cases where we are unable to 
4435 mandeep.dh 1212
        # fill in transfer price
1213
        try:
5944 mandeep.dh 1214
            inventory_client = InventoryClient().get_client()
1215
            warehouse = inventory_client.getWarehouse(fulfilmentWarehouseId)
1216
            item_pricing = inventory_client.getItemPricing(item_id, warehouse.vendor.id)
5110 mandeep.dh 1217
            lineitem.transfer_price = item_pricing.transferPrice
6751 amar.kumar 1218
            lineitem.nlc = item_pricing.nlc
6075 amit.gupta 1219
            lineitem.vatRate = catalog_client.getVatPercentageForItem(lineitem.item_id, lineitem.unit_price)
5110 mandeep.dh 1220
            order.vendorId = warehouse.vendor.id
4435 mandeep.dh 1221
        except InventoryServiceException as e:
1222
            print sys.exc_info()[0]
1223
            print e.message
5110 mandeep.dh 1224
            raise TransactionServiceException(110, 'Transfer price missing for itemId: ' + str(item_id) + ' and vendor: ' + str(warehouse.vendor.id))
4435 mandeep.dh 1225
 
5110 mandeep.dh 1226
        # For OUR warehouse, we need to scan out items for every billed order
1227
        if billingType == BillingType.OURS:
5530 mandeep.dh 1228
            for index, serialNumber in enumerate(serialNumbers):
5411 rajveer 1229
                try:
1230
                    warehouse_client = WarehouseClient().get_client()
5436 mandeep.dh 1231
                    # Fetching GOOD w/h corresponding to the virtual one here
5835 mandeep.dh 1232
                    if not warehouse.billingWarehouseId:
5950 mandeep.dh 1233
                        warehouse = inventory_client.getWarehouses(None, InventoryType.GOOD, warehouse.vendor.id, order.warehouse_id, 0)[0]
5436 mandeep.dh 1234
 
5411 rajveer 1235
                    if ItemType.SERIALIZED == item.type:
1236
                        inventoryItem = warehouse_client.getInventoryItem(serialNumber)
1237
                    else:
5661 mandeep.dh 1238
                        inventoryItem = warehouse_client.getNonSeralizedInventoryItem(itemNumbers[index], item_id, warehouse.id)
5411 rajveer 1239
 
1240
                    if (inventoryItem.itemId != item_id):
1241
                        catalog_client = CatalogClient().get_client()
1242
                        item = catalog_client.getItem(inventoryItem.itemId)
1243
                        scanItemString = " ".join([str(item.brand), str(item.modelName), str(item.modelNumber), str(item.color)])
1244
                        lineItemString = " ".join([str(lineitem.brand), str(lineitem.model_name), str(lineitem.model_number), str(lineitem.color)])
1245
                        raise TransactionServiceException(110, 'Trying to scan ' + scanItemString + ' instead of ' + lineItemString)
1246
 
1247
                    if ItemType.SERIALIZED == item.type:
5661 mandeep.dh 1248
                        inventoryItem = warehouse_client.scanSerializedItemForOrder(serialNumber, ScanType.SALE, orderId, warehouse.id, 1, order.warehouse_id)
5411 rajveer 1249
                    else:
5661 mandeep.dh 1250
                        inventoryItem = warehouse_client.scanForOrder(inventoryItem, ScanType.SALE, 1, order.id, warehouse.id, order.warehouse_id)
5411 rajveer 1251
 
1252
                    lineitem.transfer_price = inventoryItem.unitPrice
1253
                    order.vendorId = inventoryItem.supplierId
5636 amar.kumar 1254
                    catalog_client = CatalogClient().get_client()
5411 rajveer 1255
                except WarehouseServiceException as e:
1256
                    print sys.exc_info()[0]
1257
                    print 'Could not scan out orders due to: ' + e.message
1258
                    raise TransactionServiceException(110, e.message)
6753 rajveer 1259
                    '''
1260
                    elif billingType == BillingType.OURS_EXTERNAL:
1261
                        try:
1262
                            serialNumber = serialNumbers[0]
1263
                            warehouse_client = WarehouseClient().get_client()
1264
                            inventoryItem = warehouse_client.scanForOursExternalSale(lineitem.item_number, serialNumber, invoice_number, order.fulfilmentWarehouseId, lineitem.transfer_price)
1265
                            lineitem.transfer_price = inventoryItem.unitPrice
1266
                            order.vendorId = inventoryItem.supplierId
1267
                        except WarehouseServiceException as e:
1268
                            print sys.exc_info()[0]
1269
                            print 'Could not scan out orders due to: ' + e.message
1270
                            raise TransactionServiceException(110, e.message)
1271
                    '''
5123 mandeep.dh 1272
        else:
1273
            if not warehouse.isAvailabilityMonitored:
5944 mandeep.dh 1274
                inventory_client = InventoryClient().get_client()
1275
                inventory_client.addInventory(item.id, warehouse.id, -1 * lineitem.quantity)
4365 mandeep.dh 1276
 
5110 mandeep.dh 1277
        __update_inventory_reservation(order)
5661 mandeep.dh 1278
        order.fulfilmentWarehouseId = warehouse.id
4541 mandeep.dh 1279
        session.commit()
4283 anupam.sin 1280
        return True
1281
    else:
1282
        return False
1149 chandransh 1283
 
6751 amar.kumar 1284
def add_invoice_number(orderId, invoiceNumber, color, serialNumber, itemNumber):
4579 rajveer 1285
    order = Order.get_by(id=orderId)
1286
    if not order:
1287
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
1288
 
1289
    if order.status == OrderStatus.ACCEPTED:
1290
        order.invoice_number = invoiceNumber
4767 rajveer 1291
        if color:
1292
            billedOrdersColorMap[orderId] = color;
6751 amar.kumar 1293
        if serialNumber:
1294
            order.lineitems[0].serial_number = serialNumber 
1295
        if itemNumber:
1296
            order.lineitems[0].item_number = itemNumber
4579 rajveer 1297
    session.commit()
1298
 
1220 chandransh 1299
def batch_orders(warehouseId):
1300
    if not warehouseId:
1301
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 1302
 
1303
    batchno_generator = BatchNoGenerator()
1304
    session.commit()
1220 chandransh 1305
    query = Order.query.filter_by(warehouse_id=warehouseId)
4592 mandeep.dh 1306
    query = query.filter(Order.status == OrderStatus.LOW_INV_PO_RAISED)
1220 chandransh 1307
    query = query.order_by(Order.created_timestamp)
1308
    pending_orders = query.all()
1225 chandransh 1309
 
1220 chandransh 1310
    serial_no = 1
1311
    for order in pending_orders:
1276 chandransh 1312
        order.batchNo = batchno_generator.id
1220 chandransh 1313
        order.serialNo = serial_no
1314
        serial_no += 1
1315
    session.commit() 
1316
    pending_orders = query.all()
1317
    return pending_orders
1318
 
1319
def order_outofstock(orderId):
1911 chandransh 1320
    '''
1321
    Mark order as out of stock
1322
    '''
1220 chandransh 1323
    order = get_order(orderId)
1324
    order.status = OrderStatus.INVENTORY_LOW
1325
    order.statusDescription = "Low Inventory"
1326
    order.outofstock_timestamp = datetime.datetime.now()
1327
    session.commit()
1328
    return True
1329
 
4789 rajveer 1330
def mark_orders_as_shipped_from_warehouse(warehouseId, providerId, cod, orderIds):
4410 rajveer 1331
    try:
1332
        current_timestamp = datetime.datetime.now()
5822 rajveer 1333
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(warehouse_id = warehouseId, logistics_provider_id = providerId, status = OrderStatus.BILLED).all()
4410 rajveer 1334
        for order in orders:
5822 rajveer 1335
            order.status = OrderStatus.SHIPPED_FROM_WH
1336
            order.statusDescription = "Order shipped from warehouse"
1337
            order.shipping_timestamp = current_timestamp
1338
            try:
1339
                print "Trying to schedule alert"
1340
                monitoredEntity = MonitoredEntity();
1341
                monitoredEntity.entityType=EntityType.COURIER;
1342
                monitoredEntity.eventType=OrderStatus.SHIPPED_FROM_WH;
1343
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1344
                adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1345
                sec = datetime.datetime.now()
1346
                #Warn alert time is taken as 16 hrs
1347
                warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=16))
1348
                #Critical alert time is taken as 26 hrs                    
1349
                critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=26))
1350
                monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1351
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1352
                monitoredEntity.description="warehouseId = " + str(warehouseId) + " providerId = " + str(providerId) + " orderId = "  + str(order.id);
1353
                alert_client = AlertClient().get_client()
1354
                alert_client.scheduleAlert(monitoredEntity)
1355
            except Exception as e:
1356
                print "Exception in scheduling alert in ShippedFromWarehouse method"
1357
                print e
759 chandransh 1358
        session.commit()
5832 rajveer 1359
 
4749 varun.gupt 1360
 
1361
        try:
5832 rajveer 1362
            for order in orders:
1363
                if order.pickupStoreId:
1364
                    send_mails_to_bdms(order)
1365
                else:
1366
                    enqueue_shipping_confirmation_email(order)
4749 varun.gupt 1367
        except Exception as e:
1368
            print e
5832 rajveer 1369
 
759 chandransh 1370
        return True
1371
    except:
1372
        return False
4410 rajveer 1373
 
5832 rajveer 1374
def send_mails_to_bdms(order):
5816 rajveer 1375
    logistics_client = LogisticsClient().get_client()
5832 rajveer 1376
    store = logistics_client.getPickupStore(order.pickupStoreId)
1377
    provider = logistics_client.getProvider(order.logistics_provider_id)
6029 rajveer 1378
    subject = source_name + " order " + str(order.id) +" shipped to store" 
5832 rajveer 1379
    raw_message = '''
1380
    Dear Sir,
5816 rajveer 1381
 
5832 rajveer 1382
    Order mentioned below is being shipped to your store. Customer will pick it from your store. 
1383
 
1384
    Store Id: %(store_id)s
1385
    Order Id: %(order_id)s 
1386
    Product: %(product)s
1387
    Delivery By: %(provider)s
5844 mandeep.dh 1388
    Payment Mode: %(payMode)s
1389
 
1390
    %(note)s
1391
 
5832 rajveer 1392
    Thanks and Regards
1393
    Sandeep Sachdeva
1394
    '''
1395
 
5844 mandeep.dh 1396
    payMode = 'Prepaid'
1397
    note = ''
1398
    if order.cod:
1399
        payMode = 'COD'
6318 rajveer 1400
        note = 'Note: Please collect Rs. ' + str(order.total_amount-order.gvAmount) + ' from customer'
5844 mandeep.dh 1401
 
5832 rajveer 1402
    message = dedent(raw_message) % { 'order_id' : str(order.id),
1403
                                     'store_id' : str(store.hotspotId),
1404
                                  'provider' : provider.name,
5844 mandeep.dh 1405
                                  'product' : str(order.lineitems[0]),
1406
                                  'payMode' : payMode,
1407
                                  'note'    : note
5832 rajveer 1408
                                  }
6643 rajveer 1409
    to_addresses = [store.email, store.bdmEmail, 'sandeep.sachdeva@shop2020.in', 'amit.sirohi@shop2020.in', 'manoj.kumar@shop2020.in']
5894 rajveer 1410
    cc = ['khushal.bhatia@spiceretail.co.in']
1411
    bcc = ['rajneesh.arora@spiceretail.co.in']
5966 rajveer 1412
    mail(mail_user, mail_password, to_addresses, subject, message, [], cc, bcc)
5816 rajveer 1413
 
5713 rajveer 1414
def mark_orders_as_returned_from_store(providerId, orderIds, awbs):
5676 rajveer 1415
    try:
1416
        current_timestamp = datetime.datetime.now()
5824 rajveer 1417
        orders = Order.query.filter(Order.id.in_(orderIds)).filter_by(logistics_provider_id = providerId, status = OrderStatus.RET_PICKUP_REQUEST_RAISED).all()
5676 rajveer 1418
        for order in orders:
5824 rajveer 1419
            order.status = OrderStatus.RET_RETURN_IN_TRANSIT
1420
            order.statusDescription = "Order returned from store"
1421
            order.doa_pickup_timestamp = current_timestamp
1422
            #order.airwaybill_no = awbs[orderIds.index(order.id)]
1423
            order.tracking_id = awbs[orderIds.index(order.id)]
5676 rajveer 1424
        session.commit()
1425
 
1426
        return True
1427
    except:
1428
        return False    
1429
 
1430
def set_order_attributes(orderId, attributes):
5871 rajveer 1431
    for attribute in attributes :
1432
        existingAttribute = Attribute.query.filter(Attribute.orderId == orderId).filter(Attribute.name == attribute.name).first()
1433
        if existingAttribute:
1434
            existingAttribute.value = attribute.value
1435
        else :                
1436
            attr = Attribute()
1437
            attr.orderId = orderId
1438
            attr.name = attribute.name
1439
            attr.value = attribute.value
5791 anupam.sin 1440
    session.commit()
5724 rajveer 1441
 
1113 chandransh 1442
def mark_orders_as_picked_up(provider_id, pickup_details):
1443
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 1444
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
2684 chandransh 1445
        if order == None or order.status != OrderStatus.SHIPPED_FROM_WH:
2220 chandransh 1446
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1447
            continue
1113 chandransh 1448
        order.status = OrderStatus.SHIPPED_TO_LOGST
1449
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 1450
        order.pickup_timestamp = pickup_timestamp
5636 amar.kumar 1451
 
1452
        try:
1453
            monitoredEntity = MonitoredEntity();
1454
            monitoredEntity.entityType=EntityType.COURIER;
1455
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_LOGST
1456
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1457
            adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1458
            sec = datetime.datetime.now()
1459
            #Warn alert time is taken as 16 hrs
5821 amit.gupta 1460
            warn_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=15))
5744 amar.kumar 1461
            #Critical alert time is taken as 26 hrs                    
5821 amit.gupta 1462
            critical_time = (sec + timedelta(days=(adjustedDeliveryDays-1)) + timedelta(hours=20))
5744 amar.kumar 1463
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1464
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5819 amit.gupta 1465
            monitoredEntity.description="providerId = " + str(provider_id)
5636 amar.kumar 1466
            alert_client = AlertClient().get_client()
1467
            alert_client.updateMonitoredObject(monitoredEntity)
1468
        except Exception as e:
5801 amar.kumar 1469
            print "Exception in updating alert in MarkOrdersAsPickedUp method"
5636 amar.kumar 1470
            print e
1113 chandransh 1471
    session.commit()
1217 chandransh 1472
 
4910 phani.kuma 1473
def get_orders_not_picked_up(provider_id):
1132 chandransh 1474
    current_time = datetime.datetime.now()
1475
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4741 phani.kuma 1476
    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 1477
    return orders_not_picked_up
1478
 
1132 chandransh 1479
def mark_orders_as_delivered(provider_id, delivered_orders):
1480
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 1481
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4910 phani.kuma 1482
        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 1483
            continue
6561 amit.gupta 1484
        timestamp, receiver = detail.split('|')
1485
        order.delivery_timestamp = datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")
1486
        if order.first_dlvyatmp_timestamp is None:
1487
            order.first_dlvyatmp_timestamp = order.delivery_timestamp
1488
        order.receiver = receiver
5555 rajveer 1489
        if order.pickupStoreId:
1490
            order.status = OrderStatus.DELIVERED_AT_STORE
1491
            order.statusDescription = "Order delivered At Store"
5762 amar.kumar 1492
            try:
1493
                monitoredEntity = MonitoredEntity();
1494
                monitoredEntity.entityType=EntityType.COURIER;
1495
                monitoredEntity.eventType=OrderStatus.RECEIVED_AT_STORE;
1496
                monitoredEntity.entityIdentifier="orderId = " + str(order.id);
1497
                #adjustedDeliveryDays = adjust_delivery_time(datetime.datetime.now(), 1);
1498
                sec = datetime.datetime.now()
1499
                #Critical alert time is taken as 26 hrs                    
1500
                critical_time = (sec + timedelta(hours=4))
1501
                monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
1502
                monitoredEntity.description="deliveryTimeAtStore = " + str(order.delivery_timestamp) + " orderId = "  + str(order.id);
1503
                alert_client = AlertClient().get_client()
1504
                alert_client.updateMonitoredObject(monitoredEntity)
1505
            except Exception as e:
1506
                print e
5555 rajveer 1507
        else:
1508
            order.status = OrderStatus.DELIVERY_SUCCESS
1509
            order.statusDescription = "Order delivered"
5762 amar.kumar 1510
            update_trust_level(order)
6745 anupam.sin 1511
            if enqueue_delivery_success_mail(order) :
1512
                session.commit()
1513
            else :
1514
                session.rollback()
5762 amar.kumar 1515
            try:
1516
                alert_client = AlertClient().get_client()
1517
                alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1518
            except Exception as e:
5801 amar.kumar 1519
                print "Exception in scheduling alert in ShippedFromWarehouse method"
5762 amar.kumar 1520
                print e
5636 amar.kumar 1521
 
6745 anupam.sin 1522
 
1132 chandransh 1523
 
4712 rajveer 1524
def mark_order_as_delivered(orderId, deliveryTimestamp, receiver):
1525
    order = Order.get_by(id=orderId)
5555 rajveer 1526
    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 1527
        raise TransactionServiceException(101, "Either wrond order id or invalid state " + str(orderId))
5402 rajveer 1528
 
1529
    # Provider is 4 is for self pickup and hardcoded. We should figure out a way to not to hard code.   
1530
    if order.status == OrderStatus.BILLED and order.logistics_provider_id != 4:
5807 rajveer 1531
        raise TransactionServiceException(101, "Order is not marked for self pickup: " + str(orderId))
5402 rajveer 1532
 
5555 rajveer 1533
    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 1534
        order.delivery_timestamp = deliveryTimestamp
6631 amit.gupta 1535
        if order.first_dlvyatmp_timestamp is None:
6632 amit.gupta 1536
            order.first_dlvyatmp_timestamp = deliveryTimestamp
4712 rajveer 1537
        order.receiver = receiver
1538
    order.status = OrderStatus.DELIVERY_SUCCESS
1539
    order.statusDescription = "Order delivered"
1540
    update_trust_level(order)
1541
    session.commit()
5713 rajveer 1542
 
5812 rajveer 1543
    if order.pickupStoreId and order.cod:
5806 rajveer 1544
        __push_collection_to_hotspot(order, "SALE")
1545
 
5966 rajveer 1546
    enqueue_delivery_success_mail(order)
5713 rajveer 1547
#    if order.pickupStoreId:
1548
#        payment_client = PaymentClient().get_client()
1549
#        payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
1550
#        payment_client = PaymentClient().get_client()
1551
#        payment_client.partiallyCapturePayment(order.transaction.id, order.total_amount, xferBy, xferTxnId, now())
1552
#        order.cod_reconciliation_timestamp = datetime.datetime.now()
1553
#        session.commit()
1554
 
5636 amar.kumar 1555
    try:
1556
        alert_client = AlertClient().get_client()
5744 amar.kumar 1557
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1558
    except Exception as e:
5801 amar.kumar 1559
        print "Exception in ending alert in MarkOrderAsDelivered method"
5636 amar.kumar 1560
        print e
1561
 
4712 rajveer 1562
 
5555 rajveer 1563
def mark_order_as_received_at_store(orderId, deliveryTimestamp):
1564
    order = Order.get_by(id=orderId)
1565
    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]:
1566
        order.status = OrderStatus.RECEIVED_AT_STORE
1567
        order.statusDescription = "Order received at store"
1568
        order.delivery_timestamp = deliveryTimestamp
1569
    session.commit()
5713 rajveer 1570
    try:
5762 amar.kumar 1571
        alert_client = AlertClient().get_client()
1572
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
1573
    except Exception as e:
1574
        print e
1575
 
1576
    try:
5713 rajveer 1577
        enqueue_received_at_store_email(order)
1578
    except Exception as e:
1579
        print e
1580
 
1581
 
5555 rajveer 1582
 
4910 phani.kuma 1583
def mark_orders_as_rto(provider_id, returned_orders):
1135 chandransh 1584
    for awb, detail in returned_orders.iteritems():
1585
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
5713 rajveer 1586
        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 1587
            continue
1588
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
4484 rajveer 1589
        order.status = OrderStatus.RTO_IN_TRANSIT
1135 chandransh 1590
        order.delivery_timestamp, reason = detail.split('|')
1591
        order.statusDescription = "Order Returned to Origin:" + reason
3578 mandeep.dh 1592
        update_trust_level(order)
1911 chandransh 1593
    session.commit()
5636 amar.kumar 1594
    try:
1595
        alert_client = AlertClient().get_client()
5801 amar.kumar 1596
        alert_client.endMonitoringEntity(EntityType.COURIER, "orderId = " + str(order.id))
5636 amar.kumar 1597
    except Exception as e:
5801 amar.kumar 1598
        print "Exception in ending alert in MarkOrderAsRTO method"
5636 amar.kumar 1599
        print e
1135 chandransh 1600
 
4910 phani.kuma 1601
def get_rto_orders(provider_id):
1602
    current_time = datetime.datetime.now()
1603
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1604
    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()
1605
    return rto_orders
1606
 
5555 rajveer 1607
def get_receive_pending_orders(storeId):
1608
    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()
1609
 
1610
def get_received_at_store_orders(storeId):
5676 rajveer 1611
    return Order.query.filter_by(pickupStoreId = storeId).filter(Order.status.in_((OrderStatus.RECEIVED_AT_STORE, OrderStatus.RET_PICKUP_REQUEST_RAISED))).all()
5555 rajveer 1612
 
5713 rajveer 1613
def get_orders_collection_at_store(storeId, fromDate, toDate, onlyCod):
1614
    query = Order.query.filter(Order.status == OrderStatus.DELIVERY_SUCCESS)
1615
    if storeId:
1616
        query = query.filter_by(pickupStoreId = storeId)
5720 rajveer 1617
    else:
1618
        query = query.filter(Order.pickupStoreId != 0)
5713 rajveer 1619
    if onlyCod:
1620
        query = query.filter_by(cod = onlyCod)
1621
    if fromDate:
1622
        query = query.filter(Order.delivery_timestamp >= fromDate)
1623
    if toDate:
1624
        query = query.filter(Order.delivery_timestamp <= toDate)
1625
    return query.all()
1626
 
1246 chandransh 1627
def update_non_delivery_reason(provider_id, undelivered_orders):
1628
    for awb, reason in undelivered_orders.iteritems():
1629
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
4920 phani.kuma 1630
        if order == None or order.status == OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE:
2684 chandransh 1631
            continue
1632
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1246 chandransh 1633
        order.statusDescription = reason
1634
    session.commit()
4910 phani.kuma 1635
 
1636
def get_non_delivered_orders_by_courier(provider_id):
4581 phani.kuma 1637
    current_time = datetime.datetime.now()
1638
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1639
    upto_datetime = today_datetime - datetime.timedelta(4)
4910 phani.kuma 1640
    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 1641
    return orders_not_delivered
1246 chandransh 1642
 
4910 phani.kuma 1643
def mark_orders_as_local_connected(provider_id, local_connected_orders):
1644
    for awb, timestamp in local_connected_orders.iteritems():
1645
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1646
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST]:
1647
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
1648
            continue
1649
        order.status = OrderStatus.SHIPPED_TO_DESTINATION_CITY
1650
        order.statusDescription = "Left Out of Origin City"
5636 amar.kumar 1651
        current_time = datetime.datetime.now()
1652
        order.local_connected_timestamp = datetime.datetime(current_time.year, current_time.month, current_time.day)
1653
        try:
1654
            monitoredEntity = MonitoredEntity();
1655
            monitoredEntity.entityType=EntityType.COURIER;
1656
            monitoredEntity.eventType=OrderStatus.SHIPPED_TO_DESTINATION_CITY
1657
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1658
            #Warn alert time is taken as 23 hrs less than promised delivery time
5821 amit.gupta 1659
            warn_time = (order.expected_delivery_time-timedelta(hours = 15))
5744 amar.kumar 1660
            #Critical alert time is taken as 13 hrs less than promised delivery time                    
5821 amit.gupta 1661
            critical_time = (order.expected_delivery_time-timedelta(hours = 10))
5801 amar.kumar 1662
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1663
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1664
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1665
            alert_client = AlertClient().get_client()
1666
            alert_client.updateMonitoredObject(monitoredEntity)
1667
        except Exception as e:
5801 amar.kumar 1668
            print "Exception in updating alert in MarkOrderAsLocalConnected method"
5636 amar.kumar 1669
            print e
1670
        session.commit()
4910 phani.kuma 1671
 
1672
def get_orders_not_local_connected(provider_id):
1673
    current_time = datetime.datetime.now()
1674
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1675
    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()
1676
    return orders_pending_local_connection
1677
 
1678
def mark_orders_as_destinationCityReached(provider_id, destination_city_reached_orders):
1679
    for awb, timestamp in destination_city_reached_orders.iteritems():
1680
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1681
        if order == None or order.status not in [OrderStatus.SHIPPED_FROM_WH, OrderStatus.SHIPPED_TO_LOGST, OrderStatus.SHIPPED_TO_DESTINATION_CITY]:
1682
            continue
1683
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1684
        order.status = OrderStatus.REACHED_DESTINATION_CITY
1685
        order.statusDescription = "Reached Destination City"
1686
        order.reached_destination_timestamp = timestamp
5636 amar.kumar 1687
        try:
1688
            monitoredEntity = MonitoredEntity();
1689
            monitoredEntity.entityType=EntityType.COURIER;
1690
            monitoredEntity.eventType=OrderStatus.REACHED_DESTINATION_CITY
1691
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5764 amar.kumar 1692
            warn_time = (order.expected_delivery_time)
5801 amar.kumar 1693
            critical_time = (order.expected_delivery_time + timedelta(hours=12))
1694
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1695
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1696
            monitoredEntity.description="providerId = " + str(provider_id) + " destination city " + order.customer_city 
1697
            alert_client = AlertClient().get_client()
1698
            alert_client.updateMonitoredObject(monitoredEntity)
1699
        except Exception as e:
5801 amar.kumar 1700
            print "Exception in updating alert in MarkOrderAsDestCityReached method"
5636 amar.kumar 1701
            print e
4910 phani.kuma 1702
    session.commit()
1703
 
1704
def mark_orders_as_firstDeliveryAttempted(provider_id, first_atdl_orders):
1705
    for awb, detail in first_atdl_orders.iteritems():
1706
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1707
        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]:
1708
            continue
1709
            #raise TransactionServiceException(103, "No order found for the awb:" + awb)
1710
        order.status = OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1711
        order.first_dlvyatmp_timestamp, reason = detail.split('|')
1712
        order.statusDescription = reason
5636 amar.kumar 1713
        try:
1714
            monitoredEntity = MonitoredEntity();
1715
            monitoredEntity.entityType=EntityType.COURIER;
1716
            monitoredEntity.eventType=OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE
1717
            monitoredEntity.entityIdentifier="orderId = " + str(order.id);
5744 amar.kumar 1718
            adjustedDeliveryDaysfor1day = adjust_delivery_time(datetime.datetime.now(), 1);
1719
            adjustedDeliveryDaysfor2days = adjust_delivery_time(datetime.datetime.now(), 2);
1720
            sec = datetime.datetime.now()
1721
            #Warn alert time is taken as 16 hrs
1722
            warn_time = (sec + timedelta(days=(adjustedDeliveryDaysfor1day-1)) + timedelta(hours=24))
1723
            #Critical alert time is taken as 26 hrs                    
1724
            critical_time = (sec + timedelta(days=(adjustedDeliveryDaysfor2days-1)) + timedelta(hours=36))
1725
            monitoredEntity.warnExpiryTime = int(warn_time.strftime("%s"))*1000
1726
            monitoredEntity.criticalExpiryTime = int(critical_time.strftime("%s"))*1000
5636 amar.kumar 1727
            monitoredEntity.description="providerId = " + str(provider_id) + " first attempt timestamp" + order.first_dlvyatmp_timestamp
1728
            alert_client = AlertClient().get_client()
1729
            alert_client.updateMonitoredObject(monitoredEntity)
1730
        except Exception as e:
5801 amar.kumar 1731
            print "Exception in updating alert in MarkOrdersAsFirstDeliveryAttempted method"
5636 amar.kumar 1732
            print e
4910 phani.kuma 1733
    session.commit()
1734
 
4783 phani.kuma 1735
def get_orders_not_met_expected_delivery_date():
1736
    current_time = datetime.datetime.now()
1737
    today_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4910 phani.kuma 1738
    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 1739
    return orders_not_delivered
1740
 
4444 rajveer 1741
def get_alerts(type, warehouseId, status, timestamp):
1742
    query = Alert.query.filter(Alert.warehouseId == warehouseId)
1743
    if type != -1 :
1744
        query = query.filter(Alert.type == type)
1745
    if status != -1 :
1746
        query = query.filter(Alert.status == status)
4394 rajveer 1747
    if timestamp:
1748
        query = query.filter(Alert.timestamp >= to_py_date(timestamp))
4412 rajveer 1749
    query = query.order_by(desc(Alert.timestamp))
483 rajveer 1750
    return query.all()
1751
 
4447 rajveer 1752
def add_alert(type, warehouseId, description):
4394 rajveer 1753
    alert = Alert()
1754
    alert.type = type
1755
    alert.status = 1
1756
    alert.description = description
1757
    alert.timestamp = datetime.datetime.now()
4447 rajveer 1758
    alert.warehouseId = warehouseId
4444 rajveer 1759
    session.commit()
766 rajveer 1760
 
4444 rajveer 1761
def mark_alerts_as_seen(warehouseId):
1762
    query = Alert.query.filter(Alert.warehouseId == warehouseId).filter(Alert.status == 1)
1763
    alerts = query.all()
1764
    for alert in alerts:
1765
        alert.status = 0    
1766
    session.commit()
1767
 
1596 ankur.sing 1768
def get_valid_order_count():
2851 chandransh 1769
    '''
1770
    Returns the number of orders which we processed. The reshipped orders are not
1771
    counted since there'll always be a new compensating order present.
1772
    '''
4682 rajveer 1773
    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 1774
 
1627 ankur.sing 1775
def get_cust_count_with_successful_txn():
2851 chandransh 1776
    '''
1777
    Returns the number of distinct customers who have done successful transactions.
1778
    It uses the sqlalchemy func module to construct an efficient query.
1779
    '''
1780
    return session.query(func.count(distinct(Order.customer_id))).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).scalar()
1627 ankur.sing 1781
 
1730 ankur.sing 1782
def get_valid_orders_amount_range():
2851 chandransh 1783
    '''
1784
    Returns a list containing the minimum and maximum amount across all
1785
    orders placed with us. No need to consider reshippped orders for min/max
1786
    amount of orders.
1787
    '''
1788
    return session.query(func.min(Order.total_amount), func.max(Order.total_amount)).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).one()
1627 ankur.sing 1789
 
5874 rajveer 1790
def get_valid_orders(limit, onlyStore):
2851 chandransh 1791
    '''
1792
    Returns the last limit number of valid orders placed with us. Ignored the
1793
    limit if it's passed as 0. Raises an excpetion if the supplied limit is 
1794
    less than 0. 
1795
    '''
1796
    if limit < 0:
1797
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
4662 rajveer 1798
    query = Order.query.filter(Order.status >= OrderStatus.COD_VERIFICATION_PENDING)
5874 rajveer 1799
    if onlyStore:
1800
        query = query.filter(Order.pickupStoreId != 0)
1886 ankur.sing 1801
    query = query.order_by(desc(Order.created_timestamp))
2851 chandransh 1802
    if limit != 0:
1886 ankur.sing 1803
        query = query.limit(limit)
1804
    return query.all()
1805
 
5527 anupam.sin 1806
def get_next_invoice_number(orderType):
1807
    if OrderType.B2Cbulk == orderType:
1808
        orderType = OrderType.B2C
1809
    entity_id = InvoiceIDGenerator.query.filter(InvoiceIDGenerator.orderType == orderType).with_lockmode("update").one()
2783 chandransh 1810
    invoice_number = entity_id.id + 1
1811
    entity_id.id = invoice_number
1812
    return invoice_number
1813
 
2536 chandransh 1814
def toggle_doa_flag(order_id):
1815
    order = get_order(order_id)
1816
    if(order.doaFlag):
1817
        order.doaFlag = False
1818
    else:
1819
        order.doaFlag = True
1820
    session.commit()
1821
    return order.doaFlag
1822
 
4454 rajveer 1823
def mark_order_doa_request_received(orderId):
1824
    order = get_order(orderId)
1825
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1826
        return False
1827
    order.status = OrderStatus.DOA_REQUEST_RECEIVED
4459 rajveer 1828
    order.statusDescription = "DOA Request Received"
4454 rajveer 1829
    session.commit()
1830
    return True
1831
 
1832
def mark_order_doa_request_authorized(orderId, isAuthorized):
1833
    order = get_order(orderId)
1834
    if order.status != OrderStatus.DOA_REQUEST_RECEIVED:
1835
        return False
1836
    if isAuthorized:
1837
        order.status = OrderStatus.DOA_REQUEST_AUTHORIZED
4459 rajveer 1838
        order.statusDescription = "DOA Request Authorized"
4454 rajveer 1839
    else:
1840
        order.status = OrderStatus.DELIVERY_SUCCESS
4459 rajveer 1841
        order.statusDescription = "Order delivered"
4454 rajveer 1842
    session.commit()
1843
    return True
1844
 
4488 rajveer 1845
def mark_order_return_request_received(orderId):
1846
    order = get_order(orderId)
1847
    if order.status != OrderStatus.DELIVERY_SUCCESS:
1848
        return False
1849
    order.status = OrderStatus.RET_REQUEST_RECEIVED
1850
    order.statusDescription = "Return Request Received"
1851
    session.commit()
1852
    return True
1853
 
1854
def mark_order_return_request_authorized(orderId, isAuthorized):
1855
    order = get_order(orderId)
1856
    if order.status != OrderStatus.RET_REQUEST_RECEIVED:
1857
        return False
1858
    if isAuthorized:
1859
        order.status = OrderStatus.RET_REQUEST_AUTHORIZED
1860
        order.statusDescription = "Return Request Authorized"
1861
    else:
1862
        order.status = OrderStatus.DELIVERY_SUCCESS
1863
        order.statusDescription = "Order delivered"
1864
    session.commit()
1865
    return True
1866
 
4579 rajveer 1867
def request_pickup_number(order_id, providerId):
2536 chandransh 1868
    order = get_order(order_id)
4495 rajveer 1869
    if order.status != OrderStatus.DELIVERY_SUCCESS and order.status != OrderStatus.DOA_REQUEST_AUTHORIZED and order.status != OrderStatus.RET_REQUEST_AUTHORIZED:
2536 chandransh 1870
        return False
1871
 
4227 rajveer 1872
    subject = "Pickup request from " + order.customer_city
2536 chandransh 1873
    try:
5944 mandeep.dh 1874
        inventory_client = InventoryClient().get_client()
1875
        warehouse = inventory_client.getWarehouse(order.warehouse_id)
2536 chandransh 1876
 
1877
        logistics_client = LogisticsClient().get_client()
4579 rajveer 1878
        provider = logistics_client.getProvider(providerId)
3051 chandransh 1879
        to_addr = provider.details[DeliveryType.PREPAID].email
2536 chandransh 1880
        raw_message = '''
1881
        Dear Sir/Madam,
1882
 
2559 chandransh 1883
        Kindly arrange a pickup today from %(customer_city)s. Pickup and delivery addresses are mentioned below.
2536 chandransh 1884
 
6663 rajveer 1885
        Order Id: %(order_id)s
2536 chandransh 1886
        Pickup CODE: %(provider_code)s
1887
        Total Weight: %(order_weight)s kg
1888
 
2559 chandransh 1889
        Pickup Address:
2536 chandransh 1890
 
1891
        %(customer_address)s
1892
 
1893
        Delivery Address:
1894
 
1895
        %(warehouse_executive)s
1896
        %(warehouse_address)s
1897
        PIN %(warehouse_pin)s
1898
 
1899
        Thanks and Regards
4227 rajveer 1900
        Sandeep Sachdeva
2536 chandransh 1901
        '''
4579 rajveer 1902
 
1903
        if warehouse.id == 7:
1904
            executive = 'Amit Kumar'
1905
        else:
4966 phani.kuma 1906
            executive = 'Dinesh Kumar'
4579 rajveer 1907
 
2559 chandransh 1908
        message = dedent(raw_message) % { 'customer_city' : order.customer_city,
3051 chandransh 1909
                                          'provider_code' : provider.details[DeliveryType.PREPAID].accountNo,
6663 rajveer 1910
                                          'order_id' : str(order_id),
2536 chandransh 1911
                                          'order_weight' : str(order.total_weight),
1912
                                          'customer_address' : __get_order_address(order),
4579 rajveer 1913
                                          'warehouse_executive' : executive,
2536 chandransh 1914
                                          'warehouse_address' : warehouse.location,
4966 phani.kuma 1915
                                          'warehouse_pin' : warehouse.pincode}
6645 anupam.sin 1916
        to_addresses = [to_addr,'amit.sirohi@shop2020.in', 'shrawan.choudhary@shop2020.in', 'ritesh.chauhan@shop2020.in']
4966 phani.kuma 1917
 
5966 rajveer 1918
        mail(mail_user, mail_password, to_addresses, subject, message)
4495 rajveer 1919
        if order.status == OrderStatus.RET_REQUEST_AUTHORIZED:
1920
            order.status = OrderStatus.RET_PICKUP_REQUEST_RAISED
1921
            order.statusDescription = "Pick up requested for RETURN"
1922
        else:
1923
            order.status = OrderStatus.DOA_PICKUP_REQUEST_RAISED
1924
            order.statusDescription = "Pick up requested for DOA"
4815 phani.kuma 1925
        order.doa_logistics_provider_id = providerId
2536 chandransh 1926
        session.commit()
1927
        return True
1928
    except Exception as e:
1929
        print sys.exc_info()[0]
1930
        return False
1931
 
4602 rajveer 1932
def authorize_pickup(order_id, pickup_number, providerId):
2536 chandransh 1933
    order = get_order(order_id)
4495 rajveer 1934
    if order.status not in [OrderStatus.DOA_PICKUP_REQUEST_RAISED, OrderStatus.RET_PICKUP_REQUEST_RAISED]:
2536 chandransh 1935
        return False
4815 phani.kuma 1936
    if order.doa_logistics_provider_id is not None:
1937
        providerId = order.doa_logistics_provider_id    #previously we are not storing this so data is taken from omdashboarduser
2536 chandransh 1938
    subject = 'Pickup details'
1939
    filename = "/tmp/" +  str(order.id) +".pdf" 
1940
    try:
5944 mandeep.dh 1941
        inventory_client = InventoryClient().get_client()
1942
        warehouse = inventory_client.getWarehouse(order.warehouse_id)
2536 chandransh 1943
 
1944
        logistics_client = LogisticsClient().get_client()
4602 rajveer 1945
        provider = logistics_client.getProvider(providerId)
2536 chandransh 1946
        provider_name = provider.name
1947
 
1948
        to_addr = order.customer_email
1949
        today = date.today().strftime("%d-%B-%Y (%A)")
1950
 
1951
        raw_message = '''
1952
        Dear Mr. %(customer_name)s,
1953
 
4815 phani.kuma 1954
        In reference to the return of order ID %(order_id)d, ''' + __generate_mail_body_for_authorize_pickup(order)
1955
        raw_message = raw_message + '''
2536 chandransh 1956
        Take a printout of the attachment in this mail which contains the delivery address and paste it on the packed parcel.
1957
        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.
1958
 
1959
        Pickup will happen from the below mentioned address:-
1960
 
1961
        %(customer_address)s
1962
 
1963
        Do let us know in case of any concerns
1964
 
1965
        Thanks & Regards
6029 rajveer 1966
        %(source_name)s Team
2536 chandransh 1967
        '''
1968
        message = dedent(raw_message) % {'customer_name' : order.customer_name,
1969
                                         'order_id' : order_id,
1970
                                         'provider_name' : provider_name,
1971
                                         'date': today,
1972
                                         'pickup_request_no' : pickup_number,
6029 rajveer 1973
                                         'customer_address' : __get_order_address(order),
1974
                                         'source_name' : source_name}
2536 chandransh 1975
        print message
1976
        __generate_return_advice(order, warehouse, provider, filename)
5966 rajveer 1977
        mail(help_user, help_password, [to_addr], subject, message, [get_attachment_part(filename)])
2536 chandransh 1978
        order.pickupRequestNo = pickup_number
4495 rajveer 1979
        if order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
1980
            order.status = OrderStatus.RET_PICKUP_CONFIRMED
1981
            order.statusDescription = "RETURN pick up confirmed"
1982
        else:
1983
            order.status = OrderStatus.DOA_PICKUP_CONFIRMED
1984
            order.statusDescription = "DOA pick up confirmed"
2764 chandransh 1985
        order.doa_auth_timestamp = datetime.datetime.now()
2536 chandransh 1986
        session.commit()
1987
        return True
1988
    except Exception as e:
4234 rajveer 1989
        print sys.exc_info()
4506 phani.kuma 1990
        traceback.print_tb(sys.exc_info()[2])
2536 chandransh 1991
        return False
1992
    finally:
1993
        if os.path.exists(filename):
1994
            os.remove(filename)
1995
 
4815 phani.kuma 1996
def __generate_mail_body_for_authorize_pickup(order):
1997
    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.',
1998
                         '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.',
1999
                         '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.',
2000
                         'Sony Ericsson' : 'we request you to kindly pack the original DOA certificate and the invoice.',
2001
                         '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.',
2002
                         '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.',
2003
                         'Accessories' : 'we request you to kindly pack the box properly with bubble wrap, and send it along with the original product and the invoice.'}
2004
    categories = ["Handsets", "Tablets", "Laptops"]
2005
    lineitem = order.lineitems[0]
2006
    brand = lineitem.brand
2007
    productGroup = lineitem.productGroup
2008
    searchkey = None
2009
    if productGroup not in categories:
2010
        searchkey = 'Accessories'
2011
    elif order.status == OrderStatus.RET_PICKUP_REQUEST_RAISED:
2012
        searchkey = 'Handsets Return'
2013
    elif brand == 'Nokia':
2014
        searchkey = 'Nokia'
2015
    elif brand == 'Micromax':
2016
        searchkey = 'Micromax'
2017
    elif brand == 'Karbonn':
2018
        searchkey = 'Karbonn'
2019
    elif brand == 'Sony Ericsson':
2020
        searchkey = 'Sony Ericsson'
2021
    else:
2022
        searchkey = 'Others Handsets'
2023
    return brand_msgbody_map.get(searchkey)
2024
 
2764 chandransh 2025
def mark_doas_as_picked_up(provider_id, pickup_details):
2026
    for pickupNo, doa_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 2027
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4452 rajveer 2028
        if order == None or order.status != OrderStatus.DOA_PICKUP_CONFIRMED:
2764 chandransh 2029
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
2030
            continue
2031
        order.status = OrderStatus.DOA_RETURN_IN_TRANSIT
2032
        order.statusDescription = "DOA picked up by Courier Company"
2033
        order.doa_pickup_timestamp = doa_pickup_timestamp
2034
    session.commit()
2035
 
4910 phani.kuma 2036
def get_doas_not_picked_up(provider_id):
2764 chandransh 2037
    current_time = datetime.datetime.now()
2038
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 2039
    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 2040
    return orders_not_picked_up
2041
 
4741 phani.kuma 2042
def mark_return_orders_as_picked_up(provider_id, pickup_details):
2043
    for pickupNo, return_order_pickup_timestamp in pickup_details.iteritems():
4815 phani.kuma 2044
        order = Order.query.filter_by(pickupRequestNo=pickupNo, doa_logistics_provider_id = provider_id).first()
4741 phani.kuma 2045
        if order == None or order.status != OrderStatus.RET_PICKUP_CONFIRMED:
2046
            #raise TransactionServiceException(102, "No order found for the awb: " + awb)
2047
            continue
2048
        order.status = OrderStatus.RET_RETURN_IN_TRANSIT
2049
        order.statusDescription = "Return order picked up by Courier Company"
2050
        order.doa_pickup_timestamp = return_order_pickup_timestamp
2051
    session.commit()
2052
 
4910 phani.kuma 2053
def get_return_orders_not_picked_up(provider_id):
4741 phani.kuma 2054
    current_time = datetime.datetime.now()
2055
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
4815 phani.kuma 2056
    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 2057
    return orders_not_picked_up
2058
 
4479 rajveer 2059
def receive_return(order_id, receiveCondition):
2591 chandransh 2060
    order = get_order(order_id)
4365 mandeep.dh 2061
 
4452 rajveer 2062
    if order.status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.DOA_RETURN_IN_TRANSIT]:
4479 rajveer 2063
        if receiveCondition == 0:
2064
            order.status = OrderStatus.DOA_RECEIVED_PRESTINE
2065
            order.statusDescription = "DOA package received"
2066
        elif receiveCondition == 1:
2067
            order.status = OrderStatus.DOA_RECEIVED_DAMAGED
2068
            order.statusDescription = "DOA received damaged"
2069
        elif receiveCondition == 2:
2070
            order.status = OrderStatus.DOA_LOST_IN_TRANSIT
2071
            order.statusDescription = "DOA lost in transit"
2764 chandransh 2072
        order.received_return_timestamp = datetime.datetime.now()
4495 rajveer 2073
    elif order.status in [OrderStatus.RET_PICKUP_CONFIRMED, OrderStatus.RET_RETURN_IN_TRANSIT]:
2074
        if receiveCondition == 0:
2075
            order.status = OrderStatus.RET_RECEIVED_PRESTINE
2076
            order.statusDescription = "RETURN package received"
2077
        elif receiveCondition == 1:
2078
            order.status = OrderStatus.RET_RECEIVED_DAMAGED
2079
            order.statusDescription = "RETURN received damaged"
2080
        elif receiveCondition == 2:
2081
            order.status = OrderStatus.RET_LOST_IN_TRANSIT
2082
            order.statusDescription = "RETURN lost in transit"
2083
        order.received_return_timestamp = datetime.datetime.now()
4484 rajveer 2084
    elif order.status == OrderStatus.RTO_IN_TRANSIT :
4486 rajveer 2085
        if receiveCondition == 0:
2086
            order.status = OrderStatus.RTO_RECEIVED_PRESTINE
4515 mandeep.dh 2087
            order.statusDescription = "Returned to origin"
4486 rajveer 2088
        elif receiveCondition == 1:
2089
            order.status = OrderStatus.RTO_RECEIVED_DAMAGED
2090
            order.statusDescription = "RTO received damaged"
2091
        elif receiveCondition == 2:
2092
            order.status = OrderStatus.RTO_LOST_IN_TRANSIT
2093
            order.statusDescription = "RTO lost in transit"
2764 chandransh 2094
        order.received_return_timestamp = datetime.datetime.now()
2616 chandransh 2095
    else:
2591 chandransh 2096
        return False
5110 mandeep.dh 2097
 
2098
    # For OUR warehouses, we need to scan in items for every return
5944 mandeep.dh 2099
    inventoryClient = InventoryClient().get_client()
2100
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
5110 mandeep.dh 2101
    if warehouse.billingType == BillingType.OURS:
5361 mandeep.dh 2102
        scanMap = {
2103
            OrderStatus.RTO_RECEIVED_PRESTINE : ScanType.SALE_RET,
2104
            OrderStatus.RTO_RECEIVED_DAMAGED  : ScanType.SALE_RET_UNUSABLE,
2105
            OrderStatus.RTO_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT,
2106
            OrderStatus.DOA_RECEIVED_PRESTINE : ScanType.DOA_IN,
2107
            OrderStatus.DOA_RECEIVED_DAMAGED  : ScanType.DOA_IN,
2108
            OrderStatus.DOA_LOST_IN_TRANSIT   : ScanType.LOST_IN_TRANSIT
2109
        }
5110 mandeep.dh 2110
 
5419 mandeep.dh 2111
        if scanMap.has_key(order.status):
2112
            scanType = scanMap[order.status]
5361 mandeep.dh 2113
            lineitem = order.lineitems[0]
5944 mandeep.dh 2114
            catalogClient = CatalogClient().get_client()
5361 mandeep.dh 2115
            item = catalogClient.getItem(lineitem.item_id)
2116
            warehouseClient = WarehouseClient().get_client()
2117
            if item.type == ItemType.SERIALIZED:
5110 mandeep.dh 2118
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 2119
            else:
2120
                warehouseClient.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
5110 mandeep.dh 2121
 
5558 mandeep.dh 2122
    session.commit()
2591 chandransh 2123
    return True
2124
 
2125
def validate_doa(order_id, is_valid):
2126
    order = get_order(order_id)
4452 rajveer 2127
    if order.status != OrderStatus.DOA_RECEIVED_PRESTINE:
2591 chandransh 2128
        return False
2129
    if is_valid:
2609 chandransh 2130
        order.status = OrderStatus.DOA_CERT_VALID
2131
        order.statusDescription = "DOA Certificate Valid"
2591 chandransh 2132
    else:
2133
        order.status = OrderStatus.DOA_CERT_INVALID
2134
        order.statusDescription = "DOA Certificate Invalid"
3578 mandeep.dh 2135
        update_trust_level(order)
2591 chandransh 2136
    session.commit()
2137
    return True
2138
 
4495 rajveer 2139
def validate_return_product(order_id, is_usable):
2140
    order = get_order(order_id)
2141
    if order.status != OrderStatus.RET_RECEIVED_PRESTINE:
2142
        return False
5110 mandeep.dh 2143
 
2144
    scanType = ScanType.SALE_RET_UNUSABLE
4495 rajveer 2145
    if is_usable:
2146
        order.status = OrderStatus.RET_PRODUCT_USABLE
2147
        order.statusDescription = "Return product usable"
5110 mandeep.dh 2148
        scanType = ScanType.SALE_RET
4495 rajveer 2149
    else:
2150
        order.status = OrderStatus.RET_PRODUCT_UNUSABLE
2151
        order.statusDescription = "Return product unusable"
2152
        update_trust_level(order)
2153
    session.commit()
5110 mandeep.dh 2154
 
2155
    # For OUR warehouses, we need to scan in items for every return
5944 mandeep.dh 2156
    inventoryClient = InventoryClient().get_client()
2157
    warehouse = inventoryClient.getWarehouse(order.warehouse_id)
5110 mandeep.dh 2158
    if warehouse.billingType == BillingType.OURS:
2159
        lineitem = order.lineitems[0]
5944 mandeep.dh 2160
        catalogClient = CatalogClient().get_client()
5361 mandeep.dh 2161
        item = catalogClient.getItem(lineitem.item_id)
5110 mandeep.dh 2162
        warehouse_client = WarehouseClient().get_client()
5361 mandeep.dh 2163
        if item.type == ItemType.SERIALIZED:
2164
            warehouse_client.scanSerializedItemForOrder(lineitem.serial_number, scanType, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
2165
        else:
2166
            warehouse_client.scanForOrder(None, scanType, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
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)
5110 mandeep.dh 2428
    if warehouse.billingType == BillingType.OURS:
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()
5177 mandeep.dh 2434
            if ItemType.SERIALIZED == item.type:
2435
                warehouseClient.scanSerializedItemForOrder(lineitem.serial_number, ScanType.SALE_RET, order.id, order.fulfilmentWarehouseId, lineitem.quantity, order.warehouse_id)
5361 mandeep.dh 2436
            else:
2437
                warehouseClient.scanForOrder(None, ScanType.SALE_RET, lineitem.quantity, order.id, order.fulfilmentWarehouseId, order.warehouse_id)
4873 mandeep.dh 2438
 
3195 chandransh 2439
    order.status = status_transition[order.status]
2440
    order.refund_timestamp = datetime.datetime.now()
3226 chandransh 2441
    order.refunded_by = refunded_by
2442
    order.refund_reason = reason
4873 mandeep.dh 2443
 
2628 chandransh 2444
    session.commit()
2445
    return True
2446
 
3186 chandransh 2447
def __update_inventory_reservation(order):
3191 chandransh 2448
    '''
2449
    Reduce the reservation count for all line items of the given order.
2450
    '''
3186 chandransh 2451
    try:
5944 mandeep.dh 2452
        inventoryClient = InventoryClient().get_client()
3186 chandransh 2453
        for lineitem in order.lineitems:
5966 rajveer 2454
            inventoryClient.reduceReservationCount(lineitem.item_id, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3186 chandransh 2455
    except:
2456
        print "Unable to reduce reservation count"
2457
 
4220 rajveer 2458
def __clone_order(order, should_copy_billing_info, is_cod):
2628 chandransh 2459
    current_time = datetime.datetime.now()
2460
    new_order = Order()
2461
    new_order.customer_id = order.customer_id
2462
    new_order.customer_name = order.customer_name
2463
    new_order.customer_city = order.customer_city
2464
    new_order.customer_state = order.customer_state
2465
    new_order.customer_mobilenumber = order.customer_mobilenumber
2466
    new_order.customer_pincode = order.customer_pincode
2467
    new_order.customer_address1 = order.customer_address1
2468
    new_order.customer_address2 = order.customer_address2
2469
    new_order.customer_email = order.customer_email
2470
    new_order.total_amount = order.total_amount
6318 rajveer 2471
    new_order.gvAmount = order.gvAmount
2628 chandransh 2472
    new_order.total_weight = order.total_weight
2473
    new_order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
2474
    new_order.statusDescription = 'Submitted for Processing'
2475
    new_order.created_timestamp = current_time
5062 varun.gupt 2476
    new_order.originalOrderId = order.originalOrderId if order.originalOrderId is not None else order.id 
2628 chandransh 2477
 
2478
    new_order.transaction = order.transaction
4220 rajveer 2479
    new_order.cod = is_cod
5527 anupam.sin 2480
    new_order.orderType = order.orderType
2628 chandransh 2481
 
2482
    for line_item in order.lineitems:
2483
        litem = LineItem()
2484
        litem.item_id = line_item.item_id
2485
        litem.productGroup = line_item.productGroup
2486
        litem.brand = line_item.brand
2487
        if line_item.model_number:
2488
            litem.model_number = line_item.model_number
2489
        if line_item.model_name:    
2490
            litem.model_name = line_item.model_name
2491
        if line_item.color:
2492
            litem.color = line_item.color
2493
        if line_item.extra_info:
2494
            litem.extra_info = line_item.extra_info
2495
        litem.quantity = line_item.quantity
2496
        litem.unit_price = line_item.unit_price
2497
        litem.unit_weight = line_item.unit_weight
2498
        litem.total_price = line_item.total_price
2499
        litem.total_weight = line_item.total_weight
2500
        litem.transfer_price = line_item.transfer_price
6751 amar.kumar 2501
        litem.nlc = line_item.nlc
4840 mandeep.dh 2502
        litem.dealText = line_item.dealText
6423 amit.gupta 2503
        litem.vatRate = line_item.vatRate
2628 chandransh 2504
        litem.order = new_order
2505
 
2506
    logistics_client = LogisticsClient().get_client()
2507
    item_id = new_order.lineitems[0].item_id
5785 mandeep.dh 2508
    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 2509
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
2628 chandransh 2510
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
6726 rajveer 2511
    logistics_info.deliveryDelay = adjust_delivery_time(current_time, (logistics_info.shippingTime + logistics_info.deliveryDelay))
2628 chandransh 2512
    new_order.warehouse_id = logistics_info.warehouseId
5110 mandeep.dh 2513
    new_order.fulfilmentWarehouseId = logistics_info.fulfilmentWarehouseId
2628 chandransh 2514
    new_order.logistics_provider_id = logistics_info.providerId
2515
    new_order.airwaybill_no = logistics_info.airway_billno
2516
    new_order.tracking_id = new_order.airwaybill_no
6726 rajveer 2517
 
2518
    order.courier_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryDelay)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2519
    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 2520
    new_order.promised_delivery_time = new_order.expected_delivery_time
6629 anupam.sin 2521
    new_order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2522
    new_order.promised_shipping_time = new_order.expected_shipping_time
2523
 
2628 chandransh 2524
    if should_copy_billing_info:
5388 phani.kuma 2525
        new_order.vendorId = order.vendorId
2628 chandransh 2526
        new_order.invoice_number = order.invoice_number
2527
        new_order.billed_by = order.billed_by
2528
        new_order.warehouse_id = order.warehouse_id
5110 mandeep.dh 2529
        new_order.fulfilmentWarehouseId = order.fulfilmentWarehouseId
5620 mandeep.dh 2530
        new_order.jacket_number = order.jacket_number
2531
        new_order.lineitems[0].serial_number = order.lineitems[0].serial_number
2532
        new_order.lineitems[0].item_number   = order.lineitems[0].item_number
2628 chandransh 2533
        new_order.accepted_timestamp = current_time
2534
        new_order.billing_timestamp = current_time    
2535
        new_order.status = OrderStatus.BILLED
2536
        new_order.statusDescription = 'Order Billed'
5966 rajveer 2537
    else:
2538
        session.commit()       
5944 mandeep.dh 2539
        inventoryClient = InventoryClient().get_client()
5966 rajveer 2540
        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 2541
 
2542
    return new_order
2543
 
2544
def __create_return_order(order):
2687 chandransh 2545
    ret_order = ReturnOrder(order)
2628 chandransh 2546
    return ret_order
2547
 
2548
def __create_refund(order):
4078 chandransh 2549
    payment_client = PaymentClient().get_client()
2550
    payment_client.createRefund(order.id, order.transaction.id, order.total_amount)
2747 chandransh 2551
    return
2628 chandransh 2552
 
2536 chandransh 2553
def __get_order_address(order):
2554
    address = order.customer_name + "\n" + order.customer_address1 + "\n"
2555
    if order.customer_address2:
2556
        address = address + order.customer_address2 + "\n"
2557
    address = address + order.customer_city + "\n"
2558
    address = address + order.customer_state + "\n"
2559
    address = address + "PIN " + order.customer_pincode + "\n"
2560
    address = address + "Phone: " + order.customer_mobilenumber
2561
    return address
2562
 
5767 rajveer 2563
def __get_store_address(store):
2564
    address = store.name + "\n" + store.line1 + "\n"
2565
    if store.line2:
2566
        address = address + store.line2 + "\n"
2567
    address = address + store.city + "\n"
2568
    address = address + store.state + "\n"
5802 rajveer 2569
    address = address + "PIN - " + store.pin + "\n"
5793 rajveer 2570
    if store.phone:
5802 rajveer 2571
        address = address + "Phone - " + store.phone + "\n"
5855 rajveer 2572
    address = address +  "Store timings - 11AM to 8PM (7 days)\n"
5767 rajveer 2573
    return address
2574
 
5793 rajveer 2575
def __get_store_address_html(store):
2576
    address = store.name + "<br>" + store.line1 + "<br>"
2577
    if store.line2:
2578
        address = address + store.line2 + "<br>"
2579
    address = address + store.city + "<br>"
2580
    address = address + store.state + "<br>"
5802 rajveer 2581
    address = address + "PIN - " + store.pin + "<br>"
5793 rajveer 2582
    if store.phone:
5802 rajveer 2583
        address = address + "Phone - " + store.phone + "<br>"
5855 rajveer 2584
    address = address +  "Store timings - 7 days: 11AM to 8PM  (7 days)<br>"
5793 rajveer 2585
    return address
2586
 
4815 phani.kuma 2587
def __generate_return_advice(order, warehouse, provider, filename):
2588
    if warehouse.id == 7:
2589
        executive = 'Amit Kumar'
2590
    else:
4966 phani.kuma 2591
        executive = 'Dinesh Kumar'
2536 chandransh 2592
    pdf = Canvas(filename)
2593
    pdf.setFont('Times-Bold',16)
2594
    address_text = pdf.beginText(inch, PAGE_HEIGHT - inch)
2595
    address_text.textLine("To")
4815 phani.kuma 2596
    address_text.textLine(executive)
2536 chandransh 2597
    for line in warehouse.location.split("\n"):
2598
        address_text.textLine(line)
2599
    address_text.textLine("PIN " + warehouse.pincode)
2600
    pdf.drawText(address_text)
2601
 
2602
    pdf.setFont('Times-Roman',12)
2603
    order_text = pdf.beginText(inch, PAGE_HEIGHT - 4 * inch)
3051 chandransh 2604
    order_text.textLine("Pickup CODE: " + provider.details[DeliveryType.PREPAID].accountNo)
2536 chandransh 2605
    lineitem = order.lineitems[0] 
4234 rajveer 2606
    order_text.textLine("Content : " + lineitem.brand + " " + str(lineitem.model_number) + " " + str(lineitem.color))
2536 chandransh 2607
    order_text.textLine("Declared Value: Rs. " + str(order.total_amount))
2608
    order_text.textLine("Order ID : " + str(order.id))
2609
    pdf.drawText(order_text)
2610
    pdf.showPage()
2611
    pdf.save()
2612
    return filename
2613
 
5806 rajveer 2614
def __push_collection_to_hotspot(order, type):
2615
    try:
2616
        logistics_client = LogisticsClient().get_client()
2617
        store = logistics_client.getPickupStore(order.pickupStoreId)
2618
        store_string = "<store>" + store.hotspotId + "</store>"
2619
        order_string = "<orderno>" + str(order.id) + "</orderno>"
2620
        collection_type = "<Type>" + type + "</Type>"
5833 rajveer 2621
        payment_mode = get_order_attribute_value(order.id, "PAYMENT_MODE")
5806 rajveer 2622
        if type == "SALE":
6318 rajveer 2623
            amount = int(order.total_amount-order.gvAmount)
5806 rajveer 2624
            ts = order.delivery_timestamp
2625
        if type == "SALE RETURN":
6318 rajveer 2626
            amount = -int(order.total_amount-order.gvAmount)
5806 rajveer 2627
            ts = order.refund_timestamp
2628
        if payment_mode == "Cash":
2629
            cash_string = "<cash>" + str(amount) + "</cash>"
2630
            card_string = "<hdfc>0</hdfc>"
2631
        if payment_mode == "Card":
2632
            cash_string = "<cash>0</cash>"
2633
            card_string = "<hdfc>" + str(amount) + "</hdfc>"
2634
        date_string = "<date>" + ts.strftime("%Y%m%d") + "</date>"
2635
        time_string = "<time>" + ts.strftime("%H%M%S") + "</time>"
2636
 
2637
        conn = httplib.HTTPConnection("182.71.104.182")
2638
        XML="""
2639
        <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/">
2640
          <soap:Body>
2641
            <SaholicDataTransfer xmlns="http://tempuri.org/">
2642
        """
2643
 
2644
        XML = XML + store_string + order_string + collection_type + cash_string + card_string + date_string + time_string 
2645
 
2646
        footer = """
2647
            </SaholicDataTransfer>
2648
          </soap:Body>
2649
        </soap:Envelope>
2650
        """
2651
        XML = XML + footer
2652
 
2653
        params = urllib.urlencode({'op': 'SaholicDataTransfer'})
2654
        headers = { "Content-type": "text/xml", "Content-Length": "%d" % len(XML)}
2655
        conn.request("POST", "/loaddetect/Service.asmx?"+params, "", headers)
2656
        conn.send(XML)
2657
        response = conn.getresponse()
2658
        print response.status, response.reason
2659
        resp = response.read()
2660
        conn.close()
2661
        print resp
2662
        if "Saved Successfully" in resp:
2663
            return True
2664
        elif "Error in Saving Data" in resp:
2665
            return False
2666
        else: 
2667
            return False
2668
    except Exception as e:
2669
        print e
2670
        return False
2671
 
2697 chandransh 2672
def get_return_orders(warehouse_id, from_date, to_date):
2673
    query = ReturnOrder.query.filter_by(processedStatus = False)
2674
    if warehouse_id != -1:
2675
        query = query.filter_by(warehouseId = warehouse_id)
2676
    if from_date:
4118 chandransh 2677
        query = query.filter(ReturnOrder.createdAt >from_date)
2697 chandransh 2678
    if to_date:
4118 chandransh 2679
        query = query.filter(ReturnOrder.createdAt < to_date)
2697 chandransh 2680
    return [return_order.to_thrift_object() for return_order in query.all()]
2681
 
5481 phani.kuma 2682
def get_all_return_orders(onlyNotProcessed, from_date, to_date):
2683
    query = ReturnOrder.query
2684
    if onlyNotProcessed:
2685
        query = query.filter_by(processedStatus = False)
2686
    if from_date:
2687
        query = query.filter(ReturnOrder.createdAt >= from_date)
2688
    if to_date:
2689
        query = query.filter(ReturnOrder.createdAt <= to_date)
2690
    return [return_order.to_thrift_object() for return_order in query.all()]
2691
 
2700 chandransh 2692
def get_return_order(id):
2693
    ret_order = ReturnOrder.get_by(orderId = id)
2694
    if ret_order is None:
2695
        raise TransactionServiceException(116, "No return order found for the given order id")
2696
    return ret_order.to_thrift_object()
2697
 
2697 chandransh 2698
def process_return(ret_order_id):
2699
    ret_order = ReturnOrder.get_by(orderId = ret_order_id)
2700
    if ret_order is None:
2701
        raise TransactionServiceException(116, "No return order found for the given order id")
2702
    ret_order.processedStatus = True
2701 chandransh 2703
    ret_order.processedAt = datetime.datetime.now()
2697 chandransh 2704
    session.commit()
2705
 
4757 mandeep.dh 2706
def update_orders_as_PORaised(itemIdQuantityMap, purchaseOrderId, warehouseId):
2707
    """
2708
    Updates orders as PO raised. Also updates purchase order id in orders. Pass a map of items mapped to
2709
    the quantities for which the PO is raised.
2710
 
2711
    Parameters:
2712
     - itemIdQuantityMap
2713
     - purchaseOrderId
2714
     - warehouseId
2715
    """
3451 chandransh 2716
    query = Order.query.with_lockmode("update").filter_by(warehouse_id=warehouseId)
4757 mandeep.dh 2717
    query = query.filter(or_(Order.status == OrderStatus.SUBMITTED_FOR_PROCESSING, Order.status == OrderStatus.INVENTORY_LOW))
2819 chandransh 2718
    query = query.filter_by(purchase_order_id=None)
2719
    query = query.order_by(Order.created_timestamp)
2720
    pending_orders = query.all()
4586 mandeep.dh 2721
 
2722
    for order in pending_orders:
4757 mandeep.dh 2723
        lineitem = order.lineitems[0]
2724
        if itemIdQuantityMap.has_key(lineitem.item_id):
2725
            if itemIdQuantityMap[lineitem.item_id] >= lineitem.quantity:
2726
                order.status = OrderStatus.LOW_INV_PO_RAISED
2727
                order.statusDescription = 'In Process'
2728
                order.purchase_order_id = purchaseOrderId
2729
                itemIdQuantityMap[lineitem.item_id] -= lineitem.quantity
4434 mandeep.dh 2730
 
2819 chandransh 2731
    session.commit()
2732
 
3451 chandransh 2733
def update_weight(order_id, weight):
3469 chandransh 2734
    '''
2735
    Update the weight of order
2736
    '''
3451 chandransh 2737
    order = get_order(order_id)
2738
    order.total_weight = weight
3469 chandransh 2739
    lineitem = order.lineitems[0]
2740
    lineitem.total_weight = weight
2741
    lineitem.unit_weight = weight
3451 chandransh 2742
 
3469 chandransh 2743
    session.commit()
2744
    return order
2745
 
2746
def change_product(order_id, item_id):
2747
    '''
2748
    Ship a product of a different color to the customer.
2749
    '''
2750
    order = get_order(order_id)
4662 rajveer 2751
    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 2752
        raise TransactionServiceException(120, "This order has already been processed. Please seek help from engineering.")
2753
 
2754
    lineitem = order.lineitems[0]
3451 chandransh 2755
 
3469 chandransh 2756
    catalog_client = CatalogClient().get_client()
2757
 
2758
    old_item = catalog_client.getItem(lineitem.item_id)
2759
    item = catalog_client.getItem(item_id)
2760
    if old_item.catalogItemId != item.catalogItemId:
2761
        raise TransactionServiceException(121, "You can't ship a different item. You can only ship the same item in a different color.")
2762
 
5944 mandeep.dh 2763
    inventoryClient = InventoryClient().get_client()
5966 rajveer 2764
    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 2765
    __update_inventory_reservation(order)
3469 chandransh 2766
    #TODO: Check that this new item has the same price
2767
 
2768
    lineitem.item_id = item_id
2769
    lineitem.color = item.color
2770
 
3451 chandransh 2771
    session.commit()
3469 chandransh 2772
 
2773
    order = get_order(order_id)
3451 chandransh 2774
    return order
3469 chandransh 2775
 
2776
def change_warehouse(order_id, warehouse_id):
2777
    '''
2778
    Update the warehouse which will be used to fulfil this order.
2779
    '''
2780
    order = get_order(order_id)
6019 rajveer 2781
    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 2782
        raise TransactionServiceException(117, "This order has already been processed. Please seek help from engineering.")
2783
 
2784
    if warehouse_id == order.warehouse_id:
2785
        raise TransactionServiceException(118, "You have selected the current warehouse again. Nothing to do")
2786
 
2787
    lineitem = order.lineitems[0]
2788
    catalog_client = CatalogClient().get_client()
5944 mandeep.dh 2789
    inventoryClient = InventoryClient().get_client()
3469 chandransh 2790
    try:
5944 mandeep.dh 2791
        warehouse = inventoryClient.getWarehouse(warehouse_id)
3469 chandransh 2792
    except:
2793
        raise TransactionServiceException(119, "No warehouse with id" + str(warehouse_id))
5110 mandeep.dh 2794
 
5147 mandeep.dh 2795
    if warehouse.billingWarehouseId is None:
2796
        raise TransactionServiceException(119, "Shifting of warehouse allowed to warehouse with billing support only")
5110 mandeep.dh 2797
 
5620 mandeep.dh 2798
    # If One gives a billing warehouse for warehouse shift, we should assign order to the GOOD warehouse
2799
    # present within it with maximum availability
2800
    if warehouse.id == warehouse.billingWarehouseId:
5944 mandeep.dh 2801
        warehouses = inventoryClient.getWarehouses(None, InventoryType.GOOD, 0, 0, warehouse.id)
5147 mandeep.dh 2802
        if warehouses:
5944 mandeep.dh 2803
            itemInventory = inventoryClient.getItemInventoryByItemId(lineitem.item_id)
5147 mandeep.dh 2804
            warehouse = warehouses[0]
2805
            maxAvailability = 0
2806
            for goodWarehouse in warehouses:
2807
                if itemInventory.availability.has_key(goodWarehouse.id) and maxAvailability < itemInventory.availability[goodWarehouse.id]:
2808
                    warehouse = goodWarehouse
2809
                    maxAvailability = itemInventory.availability[goodWarehouse.id]
2810
 
2811
            # Use preferred vendor's warehouse if not available anywhere
2812
            if not maxAvailability:
2813
                item = catalog_client.getItem(lineitem.item_id)
2814
                if item.preferredVendor:
2815
                    for goodWarehouse in warehouses:
2816
                        if goodWarehouse.vendor.id == item.preferredVendor:
2817
                            warehouse = goodWarehouse
2818
        else:
2819
            raise TransactionServiceException(119, "Shifting of warehouse allowed to GOOD inventory type warehouse with billing support")
2820
 
6007 rajveer 2821
    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 2822
    __update_inventory_reservation(order)
2823
 
2824
    order.warehouse_id = warehouse.billingWarehouseId
5147 mandeep.dh 2825
    order.fulfilmentWarehouseId = warehouse.id
3469 chandransh 2826
    session.commit()
2827
    return order
3553 chandransh 2828
 
4647 rajveer 2829
def add_delay_reason(order_id, reason, further_delay, delayReasonText):
3553 chandransh 2830
    '''
3994 chandransh 2831
    Adds a delay reason to the order and updates the expected delivery time.
3553 chandransh 2832
    '''
2833
    order = get_order(order_id)
2834
    try:
3581 chandransh 2835
        order.delay_reason = DelayReason._VALUES_TO_NAMES[reason]
4647 rajveer 2836
        order.delayReasonText = delayReasonText
4009 chandransh 2837
        actual_delivery_delay = adjust_delivery_time(order.expected_delivery_time, further_delay)
2838
        order.expected_delivery_time = order.expected_delivery_time + datetime.timedelta(days=actual_delivery_delay)
4102 chandransh 2839
 
4842 rajveer 2840
        actual_shipping_delay = adjust_delivery_time(order.expected_shipping_time, further_delay)
2841
        order.expected_shipping_time = order.expected_shipping_time + datetime.timedelta(days=actual_shipping_delay)
4102 chandransh 2842
 
6726 rajveer 2843
        order.courier_delivery_time = order.courier_delivery_time + datetime.timedelta(days=adjust_delivery_time(order.courier_delivery_time, further_delay))
2844
 
3553 chandransh 2845
        session.commit()
4008 mandeep.dh 2846
 
2847
        try:
2848
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
2849
            transaction_requiring_extra_processing.category = 'DELAYED_DELIVERY'
2850
            transaction_requiring_extra_processing.transaction_id = order.transaction_id
2851
            session.commit()
2852
        except Exception as e:
4065 mandeep.dh 2853
            print 'Could not persist transaction id: ' + str(order.transaction_id) + ' for further processing due to: ' + str(e)
4008 mandeep.dh 2854
 
3553 chandransh 2855
        return True
2856
    except:
3994 chandransh 2857
        print sys.exc_info()[0]
3553 chandransh 2858
        return False
3956 chandransh 2859
 
2860
def reconcile_cod_collection(collected_amount_map, xferBy, xferTxnId, xferDate):
2861
    unprocessed_awbs = {}
2862
    for awb, amount in collected_amount_map.iteritems():
2863
        try:
2864
            order = Order.query.filter_by(airwaybill_no=awb).one()
2865
        except NoResultFound:
2866
            unprocessed_awbs[awb] = "No order was found for the given AWB: " + awb
2867
            continue
2868
        except MultipleResultsFound:
2869
            unprocessed_awbs[awb] = "Multiple orders were found for the given AWB:" + awb
2870
            continue
2871
 
2872
        if order.cod_reconciliation_timestamp:
2873
            #This order has been processed already! This may be a re-run. Let's allow other orders to be processed.
2874
            continue
2875
 
2876
        if order.status < OrderStatus.DELIVERY_SUCCESS:
2877
            #Order has not been delivered yet. No way we can receive the payment.
2878
            unprocessed_awbs[awb] = "Payment has been received for order: " + str(order.id) + " before delivery reconciliation"
2879
            continue
2880
 
4252 rajveer 2881
        ##As per ticket #743 if amount difference less than 0.5 we should reconcile
6318 rajveer 2882
        if abs(amount - (order.total_amount - order.gvAmount)) > 0.5:
3956 chandransh 2883
            #Received amount is less than or more than the order amount. Mustn't let the user proceed.
6318 rajveer 2884
            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 2885
            continue
2886
 
2887
        try:
2888
            payment_client = PaymentClient().get_client()
2889
            payment_client.partiallyCapturePayment(order.transaction.id, amount, xferBy, xferTxnId, xferDate)
2890
        except Exception:
2891
            unprocessed_awbs[awb] = "We were unable to partially capture payment for order id " + str(order.id) + ", AWB: " + awb
2892
            continue
2893
 
2894
        #Payment has been recorded now. We can update the order peacefully.
2895
        order.cod_reconciliation_timestamp = datetime.datetime.now()
2896
        session.commit()
3469 chandransh 2897
 
3956 chandransh 2898
    return unprocessed_awbs
4008 mandeep.dh 2899
 
2900
def get_transactions_requiring_extra_processing(category):
4065 mandeep.dh 2901
    """
2902
    Returns the list of transaction ids that require some extra processing and
2903
    which belong to a particular category. This is currently used by CRM
2904
    application. If no such transaction ids are present, it returns an empty list.
2905
    """
2906
    query = TransactionRequiringExtraProcessing.query
4008 mandeep.dh 2907
 
4065 mandeep.dh 2908
    if category is not None:
2909
        query = query.filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category))
4008 mandeep.dh 2910
 
4065 mandeep.dh 2911
    return [a.transaction_id for a in query.all()]
4008 mandeep.dh 2912
 
2913
def mark_transaction_as_processed(transactionId, category):
4065 mandeep.dh 2914
    """
2915
    Marks a particular transaction as processed for a particular cateogory.
2916
    It essentially deletes the transaction id record for a particular
2917
    processing type category (if present) from DB.
2918
    This is currently used by CRM application.
2919
    """
4008 mandeep.dh 2920
    TransactionRequiringExtraProcessing.query.filter_by(transaction_id = transactionId).filter_by(category = ExtraTransactionProcessingType._VALUES_TO_NAMES.get(category)).delete()
2921
    session.commit()
2922
 
4018 chandransh 2923
def get_item_wise_risky_orders_count():
2924
    """
2925
    Returns a map containing the number of risky orders keyed by item id. A risky order
2926
    is defined as one whose shipping date is about to expire.
2927
    """
2928
    item_wise_risky_orders_count = {}
4019 chandransh 2929
    shipping_cutoff_time = (datetime.datetime.now() + datetime.timedelta(days = 1)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
4018 chandransh 2930
    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()
2931
    for order in orders:
2932
        for lineitem in order.lineitems:
2933
            quantity = lineitem.quantity
2934
            if item_wise_risky_orders_count.has_key(lineitem.item_id):
2935
                quantity = quantity + item_wise_risky_orders_count[lineitem.item_id]
2936
 
2937
            item_wise_risky_orders_count[lineitem.item_id] = quantity
2938
    return item_wise_risky_orders_count
2939
 
4324 mandeep.dh 2940
def update_shipment_address(order_id, address_id):
2941
    """
2942
    Updates shipment address of an order. Delivery and shipping date estimates
2943
    etc. are also updated here.
2944
 
2945
    Throws TransactionServiceException in case address change is not
2946
    possible due to certain reasons such as new pincode in address is
2947
    not serviceable etc.
2948
 
2949
    Parameters:
2950
     - orderId
2951
     - addressId
2952
    """
2953
    user_client = UserClient().get_client()
2954
    address     = user_client.getAddressById(address_id)
2955
    order       = get_order(order_id)
2956
 
4630 mandeep.dh 2957
    type = DeliveryType.PREPAID
2958
    if order.cod:
2959
        type = DeliveryType.COD
2960
 
4324 mandeep.dh 2961
    logistics_client = LogisticsClient().get_client()
5886 mandeep.dh 2962
    logistics_info = logistics_client.getLogisticsEstimation(order.lineitems[0].item_id, address.pin, type)
4324 mandeep.dh 2963
 
2964
    # Check for new estimate. Raise exception if new address is not serviceable
2965
    if logistics_info.deliveryTime == -1:
2966
        raise TransactionServiceException(1, 'Location not serviceable')
2967
 
2968
    # COD services are not available everywhere
2969
    if order.cod:
4868 rajveer 2970
        if not logistics_info.codAllowed:
4324 mandeep.dh 2971
            raise TransactionServiceException(2, 'COD service not available')
2972
 
5593 mandeep.dh 2973
    if logistics_info.providerId != order.logistics_provider_id:
5887 mandeep.dh 2974
        logistics_info = logistics_client.getLogisticsInfo(address.pin, order.lineitems[0].item_id, type, PickUpType.COURIER)
5593 mandeep.dh 2975
        order.tracking_id = logistics_info.airway_billno
2976
        order.airwaybill_no = logistics_info.airway_billno
2977
        order.logistics_provider_id = logistics_info.providerId
2978
 
6525 rajveer 2979
    order.otg = logistics_info.otgAvailable
4324 mandeep.dh 2980
    current_time = datetime.datetime.now()
2981
    logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
2982
    logistics_info.shippingTime = adjust_delivery_time(current_time, logistics_info.shippingTime)
6726 rajveer 2983
    logistics_info.deliveryDelay = adjust_delivery_time(current_time, (logistics_info.shippingTime+logistics_info.deliveryDelay))
4324 mandeep.dh 2984
 
2985
    order.customer_name         = address.name
2986
    order.customer_pincode      = address.pin
2987
    order.customer_address1     = address.line1
2988
    order.customer_address2     = address.line2
2989
    order.customer_city         = address.city
2990
    order.customer_state        = address.state
2991
    order.customer_mobilenumber = address.phone
2992
 
2993
    if order.cod:
2994
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
6726 rajveer 2995
        order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0)
2996
        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 2997
    else:
2998
        order.expected_shipping_time = (current_time + datetime.timedelta(days=logistics_info.shippingTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
6726 rajveer 2999
        order.expected_delivery_time = (current_time + datetime.timedelta(days=logistics_info.deliveryTime)).replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0)
3000
        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 3001
 
3002
    order.promised_shipping_time = order.expected_shipping_time
3003
    order.promised_delivery_time = order.expected_delivery_time 
3004
 
3005
    session.commit()
3006
 
4247 rajveer 3007
def mark_order_cancellation_request_received(orderId):
3008
    """
3009
    Mark order as cancellation request received. If customer sends request of cancellation of
3010
    a particular order, this method will be called. It will just change status of the order
3011
    depending on its current status. It also records the previous status, so that we can move
3012
    back to that status if cancellation request is denied.
3013
 
3014
    Parameters:
3015
     - orderId
3016
    """
4662 rajveer 3017
    status_transition = {OrderStatus.COD_VERIFICATION_PENDING : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 3018
             OrderStatus.SUBMITTED_FOR_PROCESSING : OrderStatus.CANCEL_REQUEST_RECEIVED,
3019
             OrderStatus.INVENTORY_LOW : OrderStatus.CANCEL_REQUEST_RECEIVED,
4306 rajveer 3020
             OrderStatus.LOW_INV_PO_RAISED : OrderStatus.CANCEL_REQUEST_RECEIVED,
3021
             OrderStatus.LOW_INV_REVERSAL_IN_PROCESS : OrderStatus.CANCEL_REQUEST_RECEIVED,
3022
             OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT : OrderStatus.CANCEL_REQUEST_RECEIVED,
4247 rajveer 3023
             OrderStatus.ACCEPTED : OrderStatus.CANCEL_REQUEST_RECEIVED,
3024
             OrderStatus.BILLED : OrderStatus.CANCEL_REQUEST_RECEIVED,
3025
             OrderStatus.PAYMENT_FLAGGED : OrderStatus.CANCEL_REQUEST_RECEIVED
3026
             }
4662 rajveer 3027
 
3028
    order = get_order(orderId)
4247 rajveer 3029
    if order.status not in status_transition.keys():
3030
        raise TransactionServiceException(114, "This order can't be considered for cancellation")
3031
 
4662 rajveer 3032
 
4247 rajveer 3033
    order.previousStatus = order.status
3034
    order.status = OrderStatus.CANCEL_REQUEST_RECEIVED
3035
    order.statusDescription = "Cancellation request received from user"
3036
    session.commit()
3037
 
4662 rajveer 3038
def mark_order_as_lost_in_transit(orderId):
3039
    """
3040
    Parameters:
3041
     - orderId
3042
    """
3043
    order = get_order(orderId)
4910 phani.kuma 3044
    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 3045
        raise TransactionServiceException(115, "This order can't be marked as lost in transit")
3046
    order.status = OrderStatus.LOST_IN_TRANSIT
3047
    order.statusDescription = "Lost in Transit"
3048
    session.commit()
3049
 
4258 rajveer 3050
def mark_transaction_as_payment_flag_removed(transactionId):
4247 rajveer 3051
    """
4258 rajveer 3052
    If we and/or payment gateway has decided to accept the payment, this method needs to be called.
3053
    Changed transaction and all orders status to payment accepted.
4247 rajveer 3054
 
3055
    Parameters:
4258 rajveer 3056
     - transactionId
4247 rajveer 3057
    """
4258 rajveer 3058
    transaction = get_transaction(transactionId)
3059
    transaction.status = TransactionStatus.AUTHORIZED
3060
    for order in transaction.orders:
3061
        order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
3062
        order.statusDescription = "Submitted to warehouse"
4247 rajveer 3063
    session.commit()
3064
 
4259 anupam.sin 3065
def refund_transaction(transactionId, refundedBy, reason):
3066
    """
3067
    This method is called when a flagged payment is deemed unserviceable and the corresponding orders
3068
    need to be cancelled
3069
 
3070
    Parameters:
3071
     - transactionId
3072
    """
3073
    transaction = get_transaction(transactionId)
3074
    transaction.status = TransactionStatus.FAILED
3075
    for order in transaction.orders:
3076
        refund_order(order.id, refundedBy, reason)
3077
    session.commit()
3078
 
4247 rajveer 3079
def mark_order_cancellation_request_denied(orderId):
3080
    """
4283 anupam.sin 3081
    If we decide to not to cancel order, we will move the order to previous status.
4247 rajveer 3082
 
3083
    Parameters:
3084
     - orderId
3085
    """
3086
    order = get_order(orderId)
3087
    order.status = order.previousStatus
3088
    order.previousStatus = None
3089
    order.statusDescription = "Cancellation request denied"
3090
    session.commit()
3091
 
3092
def mark_order_cancellation_request_confirmed(orderId):
3093
    """
3094
    If we decide to to cancel order, CRM will call this method to move the status of order to
3095
    cancellation request confirmed. After this OM will be able to cancel the order.
3096
 
3097
    Parameters:
3098
     - orderId
3099
    """
3100
    order = get_order(orderId)
3101
    order.status = OrderStatus.CANCEL_REQUEST_CONFIRMED
3102
    order.statusDescription = "Cancellation request confirmed"
3103
    session.commit()
3104
 
4285 rajveer 3105
def accept_orders_for_item_id(itemId, inventory):
3106
    """
3107
    Marks the orders as ACCEPTED for the given itemId and inventory. It also updates the accepted timestamp. If the
3108
    given order is not a COD order, it also captures the payment if the same has not been captured.
3109
 
3110
    Parameters:
3111
     - itemId
3112
     - inventory
3113
    """
4938 rajveer 3114
    orders = Order.query.filter(Order.warehouse_id == 5).filter(Order.status.in_(tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW, OrderStatus.LOW_INV_PO_RAISED, OrderStatus.LOW_INV_REVERSAL_IN_PROCESS]))).order_by(Order.expected_shipping_time).all()
4285 rajveer 3115
    for order in orders:
4301 rajveer 3116
        if inventory > 0:
3117
            lineitem = order.lineitems[0]
3118
            if itemId == lineitem.item_id:
3119
                try:
3120
                    accept_order(order.id)
3121
                    inventory = inventory - lineitem.quantity
3122
                except:
3123
                    logging.info("Unable to accept the order")
3124
        else:
3125
            order_outofstock(order.id)
4285 rajveer 3126
    return
3127
 
4607 rajveer 3128
def get_slipped_sipping_date_orders():
4662 rajveer 3129
    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 3130
 
3131
def get_cancelled_orders(cancelDateFrom, cancelDateTo):
3132
    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 3133
 
4369 rajveer 3134
def mark_orders_as_po_raised(vendorId, itemId, quantity, estimate, isReminder):
3135
    if isReminder:
3136
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3137
    else:
3138
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3139
 
3140
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3141
    for order in orders:
3142
        lineitem = order.lineitems[0]
3143
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3144
            if estimate > 0:
3145
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
3146
            order.status = OrderStatus.LOW_INV_PO_RAISED
4362 rajveer 3147
            order.statusDescription = "PO Raised"
4303 rajveer 3148
            quantity = quantity - lineitem.quantity
3149
            store_inventory_action(order, itemId, HotspotAction.PO_RAISED, estimate, lineitem.quantity)
3150
            session.commit()
3151
 
4369 rajveer 3152
def mark_orders_as_reversal_initiated(vendorId, itemId, quantity, estimate, isReminder):
3153
    if isReminder:
3154
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3155
    else:
3156
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3157
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3158
    for order in orders:
3159
        lineitem = order.lineitems[0]
3160
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3161
            if estimate > 0:
3162
                add_delay_reason(order.id, DelayReason.OTHERS, estimate)
3163
            order.status = OrderStatus.LOW_INV_REVERSAL_IN_PROCESS
4362 rajveer 3164
            order.statusDescription = "Reversal Initiated"
4303 rajveer 3165
            quantity = quantity - lineitem.quantity
3166
            store_inventory_action(order, itemId, HotspotAction.REVERSAL_INITIATED, estimate, lineitem.quantity)
3167
            session.commit()
3168
 
4369 rajveer 3169
def mark_orders_as_not_available(vendorId, itemId, quantity, estimate, isReminder):
3170
    if isReminder:
3171
        statuses = tuple([OrderStatus.LOW_INV_PO_RAISED_TIMEOUT, OrderStatus.LOW_INV_REVERSAL_TIMEOUT])
3172
    else:
3173
        statuses = tuple([OrderStatus.SUBMITTED_FOR_PROCESSING, OrderStatus.INVENTORY_LOW])
3174
 
3175
    orders = Order.query.filter(Order.status.in_(statuses)).order_by(Order.expected_shipping_time).all()
4303 rajveer 3176
    for order in orders:
3177
        lineitem = order.lineitems[0]
3178
        if quantity >= lineitem.quantity and itemId == lineitem.item_id:
3179
            order.status = OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT
4362 rajveer 3180
            order.statusDescription = "Not Available"
4303 rajveer 3181
            quantity = quantity - lineitem.quantity
3182
            store_inventory_action(order, itemId, HotspotAction.NOT_AVAILABLE, estimate, lineitem.quantity)
3183
            session.commit()
3184
 
3185
def store_inventory_action(order, itemId, hotspotAction, estimate, quantity):
4369 rajveer 3186
    orderInv = OrderInventory.get_by(order_id=order.id)
3187
    if not orderInv:
3188
        orderInv = OrderInventory()
3189
        orderInv.order = order
4303 rajveer 3190
    orderInv.hotspotAction = hotspotAction  
3191
    orderInv.estimate = estimate
3192
    orderInv.itemId = itemId
3193
    orderInv.timestamp = datetime.datetime.now()
3194
    orderInv.quantity = quantity
3195
 
4556 mandeep.dh 3196
'''    
4369 rajveer 3197
def mark_orders_as_timeout(vendorId):
3198
    ret_timeouts = {}
3199
    orderInvs = OrderInventory.query.all()
3200
    for orderInv in orderInvs:
3201
        if orderInv.timestamp +  timedelta(days=orderInv.estimate) < datetime.datetime.now():
3202
            if not ret_timeouts.has_key(orderInv.itemId):
3203
                timeout = TimeoutSummary()
3204
                ret_timeouts[orderInv.itemId] = timeout
3205
            else:
3206
                timeout = ret_timeouts.get(orderInv.itemId)
3207
            if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3208
                if timeout.poRaised:
3209
                    timeout.poRaised += 1
3210
                else:
3211
                    timeout.poRaised = 1
3212
 
3213
                if timeout.poEstimate:
3214
                    timeout.poEstimate += orderInv.estimate
3215
                else:
3216
                    timeout.poEstimate = orderInv.estimate
3217
                orderInv.order.status = OrderStatus.LOW_INV_PO_RAISED_TIMEOUT
3218
                orderInv.order.statusDescription = "PO Raised Timeout"
3219
            elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3220
                if timeout.reversalInitiated:
3221
                    timeout.reversalInitiated += 1
3222
                else:
3223
                    timeout.reversalInitiated = 1
3224
 
3225
                if timeout.reversalEstimate:
3226
                    timeout.reversalEstimate += orderInv.estimate
3227
                else:
3228
                    timeout.reversalEstimate = orderInv.estimate
3229
                orderInv.order.status = OrderStatus.LOW_INV_REVERSAL_TIMEOUT
3230
                orderInv.order.statusDescription = "Reversal Initiated Timeout"
3231
            else:
3232
                orderInv.delete()
3233
    session.commit()
3234
    return ret_timeouts
4556 mandeep.dh 3235
'''
3236
 
3237
 
3238
def mark_orders_as_timeout(vendorId):
3239
    ret_timeouts = {}
3240
    orderInvs = OrderInventory.query.all()
3241
    for orderInv in orderInvs:
3242
        if not ret_timeouts.has_key(orderInv.itemId):
3243
            timeout = TimeoutSummary()
3244
            ret_timeouts[orderInv.itemId] = timeout
3245
        else:
3246
            timeout = ret_timeouts.get(orderInv.itemId)
3247
        if orderInv.hotspotAction == HotspotAction.PO_RAISED and orderInv.order.status == OrderStatus.LOW_INV_PO_RAISED:
3248
            if timeout.poRaised:
3249
                timeout.poRaised += 1
3250
            else:
3251
                timeout.poRaised = 1
3252
 
3253
            if timeout.poEstimate:
3254
                timeout.poEstimate = max(orderInv.estimate, timeout.poEstimate)
3255
            else:
3256
                timeout.poEstimate = orderInv.estimate
3257
        elif orderInv.hotspotAction == HotspotAction.REVERSAL_INITIATED and orderInv.order.status == OrderStatus.LOW_INV_REVERSAL_IN_PROCESS:
3258
            if timeout.reversalInitiated:
3259
                timeout.reversalInitiated += 1
3260
            else:
3261
                timeout.reversalInitiated = 1
3262
 
3263
            if timeout.reversalEstimate:
3264
                timeout.reversalEstimate = max(orderInv.estimate, timeout.reversalEstimate)
3265
            else:
3266
                timeout.reversalEstimate = orderInv.estimate
3267
        orderInv.order.status = OrderStatus.INVENTORY_LOW
3268
        orderInv.order.statusDescription = "Low Inventory"
3269
        orderInv.delete()
3270
    session.commit()
3271
    return ret_timeouts
3272
 
4386 anupam.sin 3273
def get_order_for_awb(awb):
3274
    order = Order.get_by(airwaybill_no=awb)
3275
    if not order:
3276
        raise TransactionServiceException(108, "no such order")
3277
 
3278
    return order
4369 rajveer 3279
 
4910 phani.kuma 3280
def get_orders_for_provider_for_status(provider_id, order_status_list):
3281
    if not provider_id or not order_status_list:
4506 phani.kuma 3282
        raise TransactionServiceException(101, "bad provider id or order status")
4910 phani.kuma 3283
    doa_provider = False
3284
    for order_status in order_status_list:
3285
        if order_status in [OrderStatus.DOA_PICKUP_CONFIRMED, OrderStatus.RET_PICKUP_CONFIRMED]:
3286
            doa_provider = True
3287
    if doa_provider:
3288
        query = Order.query.filter_by(doa_logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4815 phani.kuma 3289
    else:
4910 phani.kuma 3290
        query = Order.query.filter_by(logistics_provider_id = provider_id).filter(Order.status.in_(order_status_list))
4506 phani.kuma 3291
    return query.all()
4386 anupam.sin 3292
 
4600 varun.gupt 3293
def get_billed_orders_for_vendor(vendor_id, billing_date_from, billing_date_to):
5368 mandeep.dh 3294
    query = Order.query.filter(Order.status != OrderStatus.PAYMENT_PENDING)
3295
 
3296
    if vendor_id:
3297
        query = query.filter_by(vendorId = vendor_id)
3298
 
4600 varun.gupt 3299
    if billing_date_from:
3300
        query = query.filter(Order.billing_timestamp >= billing_date_from)
5368 mandeep.dh 3301
 
4600 varun.gupt 3302
    if billing_date_to:
3303
        query = query.filter(Order.billing_timestamp <= billing_date_to)
5368 mandeep.dh 3304
 
4600 varun.gupt 3305
    return query.all()
3306
 
5481 phani.kuma 3307
def get_billed_orders(vendor_id, onlyVendorNotPaid, billing_date_from, billing_date_to):
5386 phani.kuma 3308
    query = Order.query.filter(Order.billing_timestamp != None)
5481 phani.kuma 3309
 
3310
    if onlyVendorNotPaid:
5488 phani.kuma 3311
        query = query.filter_by(vendor_paid = False)
5481 phani.kuma 3312
 
5386 phani.kuma 3313
    if vendor_id != -1:
3314
        query = query.filter_by(vendorId = vendor_id)
3315
 
5481 phani.kuma 3316
    if billing_date_from:
3317
        query = query.filter(Order.billing_timestamp >= billing_date_from)
3318
 
3319
    if billing_date_to:
3320
        query = query.filter(Order.billing_timestamp <= billing_date_to)
3321
 
4885 varun.gupt 3322
    return query.all()
4875 varun.gupt 3323
 
4600 varun.gupt 3324
def save_bluedart_settlements(map_awb_and_amount):
3325
    payment_client = PaymentClient().get_client()
3326
 
3327
    for awb, amount in map_awb_and_amount.iteritems():
3328
        order = Order.get_by(airwaybill_no = awb)
3329
 
3330
        payment = payment_client.getSuccessfulPaymentForTxnId(order.transaction_id)
3331
        settlement = PaymentSettlement()
3332
        settlement.paymentId = payment.paymentId
3333
        settlement.paymentGatewayId = payment.gatewayId
3334
        settlement.netCollection = amount
3335
        session.commit()
3336
 
4905 varun.gupt 3337
def save_payment_settlements(settlementDate, paymentGatewayId, referenceId, serviceTax, otherCharges, netCollection):
5386 phani.kuma 3338
    originalOrderId = None
3339
    if paymentGatewayId == 4:
3340
        cod_order = Order.get_by(id = referenceId)
3341
        if cod_order.originalOrderId:
3342
            originalOrderId = cod_order.originalOrderId
3343
        else:
3344
            originalOrderId = referenceId
4600 varun.gupt 3345
    settlement = PaymentSettlement()
3346
    settlement.settlementDate = settlementDate
3347
    settlement.paymentGatewayId = paymentGatewayId
5386 phani.kuma 3348
    if originalOrderId is not None:
3349
        settlement.originalOrderId = originalOrderId
4905 varun.gupt 3350
    settlement.referenceId = referenceId
4600 varun.gupt 3351
    settlement.serviceTax = serviceTax
3352
    settlement.otherCharges = otherCharges
3353
    settlement.netCollection = netCollection
3354
    session.commit()
3355
 
5386 phani.kuma 3356
def get_settlement_for_Prepaid(reference_id, is_refund = False):
3357
    query = PaymentSettlement.query.filter_by(referenceId = reference_id).filter(PaymentSettlement.paymentGatewayId != 4)
4600 varun.gupt 3358
 
5189 varun.gupt 3359
    if is_refund:
3360
        query = query.filter(PaymentSettlement.netCollection < 0)
3361
    else:
3362
        query = query.filter(PaymentSettlement.netCollection > 0)
3363
 
5386 phani.kuma 3364
    return query.first()
3365
 
3366
def get_settlement_for_Cod(orderId, is_refund = False):
3367
    query = PaymentSettlement.query.filter_by(originalOrderId = orderId)
5382 varun.gupt 3368
 
5386 phani.kuma 3369
    if is_refund:
3370
        query = query.filter(PaymentSettlement.netCollection < 0)
3371
    else:
3372
        query = query.filter(PaymentSettlement.netCollection > 0)
3373
 
5189 varun.gupt 3374
    return query.first()
4600 varun.gupt 3375
 
3376
def save_ebs_settlement_summary(settlement_id, settlement_date, transaction_date_from, transaction_date_to, amount):
5551 phani.kuma 3377
    summary = EBSSettlementSummary.query.filter_by(settlementId = settlement_id).first()
5481 phani.kuma 3378
    if summary is None:
3379
        summary = EBSSettlementSummary()
3380
        summary.settlementId = settlement_id
3381
        summary.settlementDate = settlement_date
3382
        summary.transactionDateFrom = transaction_date_from
3383
        summary.transactionDateTo = transaction_date_to
3384
        summary.amount = amount
3385
        summary.detailsUploaded = False
3386
        session.commit()
4600 varun.gupt 3387
 
3388
def get_ebs_settlement_summaries():
3389
    summaries = EBSSettlementSummary.query.filter_by(detailsUploaded = False).order_by(EBSSettlementSummary.transactionDateFrom).all()
3390
    summary_map = {}
3391
 
3392
    for summary in summaries:
3393
        transactionDateFrom = str(summary.transactionDateFrom.year) + '-' + str(summary.transactionDateFrom.month) + '-' + str(summary.transactionDateFrom.day)
3394
        transactionDateTo = str(summary.transactionDateTo.year) + '-' + str(summary.transactionDateTo.month) + '-' + str(summary.transactionDateTo.day)
3395
 
3396
        summary_map[summary.settlementId] = "%s to %s" %(transactionDateFrom, transactionDateTo)
3397
 
3398
    return summary_map
3399
 
3400
def get_ebs_settlement_date(settlement_id):
3401
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3402
 
3403
    if summary:
3404
        return summary.settlementDate
3405
 
3406
def mark_ebs_settlement_uploaded(settlement_id):
3407
    summary = EBSSettlementSummary.get_by(settlementId = settlement_id)
3408
 
3409
    if summary:
3410
        summary.detailsUploaded = True
3411
        session.commit()
4715 varun.gupt 3412
 
3413
def get_settlements_by_date(settlement_date_from, settlement_date_to, is_refund):
3414
    query = PaymentSettlement.query
4600 varun.gupt 3415
 
4715 varun.gupt 3416
    if settlement_date_from:
3417
        query = query.filter(PaymentSettlement.settlementDate >= settlement_date_from)
3418
 
3419
    if settlement_date_to:
3420
        query = query.filter(PaymentSettlement.settlementDate <= settlement_date_to)
3421
 
4749 varun.gupt 3422
    if is_refund is True:
3423
        query = query.filter(PaymentSettlement.netCollection < 0.0)
3424
    else:
3425
        query = query.filter(PaymentSettlement.netCollection > 0.0)
4715 varun.gupt 3426
 
4749 varun.gupt 3427
    return query.all()
4715 varun.gupt 3428
 
3429
def get_reshipped_order_ids(order_ids):
3430
    reshipped_order_ids = []
3431
    return [order.new_order_id for order in Order.query.filter(Order.new_order_id.in_(order_ids)).all()]
3432
 
4749 varun.gupt 3433
def get_shipping_confirmation_email_body(order):
3434
 
3435
    html = """
3436
<html>
3437
<body>
3438
<div>
3439
    <p>Dear Customer,</p>
3440
    <p>
4885 varun.gupt 3441
        We are pleased to inform that we have shipped the order: $order_id for your product $product_name on $shipping_datetime. 
5139 varun.gupt 3442
        The shipment will be delivered to you via $courier_name Courier Service vide AWB# $awb.
4749 varun.gupt 3443
    </p>
3444
    <p>
6655 rajveer 3445
        Expected delivery date for your order is $expected_delivery_date.
6675 rajveer 3446
        <br/>
3447
        $otg_text
3448
        <br/> 
6716 rajveer 3449
        The product can be delivered to you between business hours of 10am to 6pm.
3450
        You can Check the current shipment updates for your product online at <a href="www.saholic.com/myaccount">Open Orders</a>.
4749 varun.gupt 3451
    </p>
3452
    <p>
5573 amit.gupta 3453
        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 3454
    </p>
5139 varun.gupt 3455
    <p>$courier_name: $courier_phone</p>
4749 varun.gupt 3456
    <p>
3457
        Warm Regards,<br />
6029 rajveer 3458
        $source_name Team
4749 varun.gupt 3459
    </p>
4750 varun.gupt 3460
</div>
4749 varun.gupt 3461
</body>
3462
</html>
3463
    """
5573 amit.gupta 3464
    logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}}
5139 varun.gupt 3465
    provider_name = logistics_providers[order.logistics_provider_id]['name']
3466
    provider_phone = logistics_providers[order.logistics_provider_id]['phone']
3467
 
5868 rajveer 3468
    lclient = LogisticsClient().get_client()
3469
    logistics_info = lclient.getLogisticsEstimation(order.lineitems[0].item_id, order.customer_pincode, DeliveryType.PREPAID)
4749 varun.gupt 3470
    dt = datetime.datetime.strptime(str(order.shipping_timestamp), "%Y-%m-%d %H:%M:%S")
4885 varun.gupt 3471
    shipping_date = dt.strftime("%A, %d %B %Y %I:%M%p")
6712 rajveer 3472
    product = str(order.lineitems[0])
5868 rajveer 3473
    new_expected_delivery_timestamp = datetime.datetime.now() + timedelta(adjust_delivery_time(datetime.datetime.now(), (logistics_info.deliveryTime - logistics_info.shippingTime)))
6728 rajveer 3474
    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 3475
    #update new expected timestamp
3476
    if order.cod:
6705 amar.kumar 3477
        new_expected_delivery_timestamp = new_expected_delivery_timestamp.replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6728 rajveer 3478
        order.courier_delivery_time = new_courier_delivery_time.replace(hour=COD_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6666 rajveer 3479
    else:
6705 amar.kumar 3480
        new_expected_delivery_timestamp = new_expected_delivery_timestamp.replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6728 rajveer 3481
        order.courier_delivery_time = new_courier_delivery_time.replace(hour=PREPAID_SHIPPING_CUTOFF_TIME, minute=0, second=0, microsecond=0)
6666 rajveer 3482
    order.expected_delivery_time = new_expected_delivery_timestamp
3483
    session.commit()
3484
 
4885 varun.gupt 3485
    new_expected_delivery_date = new_expected_delivery_timestamp.strftime("%A, %d %B %Y")
6655 rajveer 3486
    otg_text = ""
3487
    if order.otg:
6662 rajveer 3488
        promised_delivery_date = order.promised_delivery_time.strftime("%A, %d %B %Y")
6655 rajveer 3489
        if new_expected_delivery_timestamp > order.promised_delivery_time:
6712 rajveer 3490
            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 3491
        elif new_expected_delivery_timestamp < order.promised_delivery_time:
6662 rajveer 3492
            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 3493
        else:            
6662 rajveer 3494
            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 3495
 
3496
    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 3497
    return Template(html).substitute(info)
4749 varun.gupt 3498
 
5832 rajveer 3499
def enqueue_shipping_confirmation_email(order):
4915 varun.gupt 3500
    # Calling helper service on production
3501
    helperClient = HelperClient(host_key = "helper_service_server_host_prod").get_client()
5832 rajveer 3502
    try:
3503
        emailSubject = 'Shipping Details for Order ID: ' + str(order.id)
3504
        emailBody = get_shipping_confirmation_email_body(order)
6687 rajveer 3505
        if order.otg:
3506
            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'])
3507
        else:
3508
            helperClient.saveUserEmailForSending([order.customer_email], None, emailSubject, emailBody, str(order.id), 'ShippingConfirmation', [], [])
3509
 
5832 rajveer 3510
    except Exception as e:
3511
        print e
5139 varun.gupt 3512
 
4915 varun.gupt 3513
def get_order_distribution_by_status(start_date, end_date):
5067 varun.gupt 3514
    query = session.query(Order.status, func.count(Order.id)).group_by(Order.status)
3515
    query = query.filter(Order.created_timestamp >= start_date)
3516
    query = query.filter(Order.created_timestamp <= end_date)
3517
    return query.all()
4915 varun.gupt 3518
 
5067 varun.gupt 3519
def get_order_ids_for_status(status, start_datetime, end_datetime):
3520
    query = Order.query.filter(Order.status == status)
3521
    query = query.filter(Order.created_timestamp >= start_datetime)
3522
    query = query.filter(Order.created_timestamp <= end_datetime)
3523
    return query.all()
3524
 
5099 varun.gupt 3525
def update_orders_as_paid_to_vendor(order_id):
5139 varun.gupt 3526
    paid_order = Order.get_by(id = order_id)
5099 varun.gupt 3527
 
5139 varun.gupt 3528
    if paid_order.originalOrderId is None:
3529
        paid_order.vendor_paid = True
5099 varun.gupt 3530
        session.commit()
5139 varun.gupt 3531
 
3532
        for order in Order.query.filter(Order.originalOrderId == order_id).all():
3533
            order.vendor_paid = True
3534
            session.commit()
3535
    else:
5208 varun.gupt 3536
        original_order_id = paid_order.originalOrderId
5139 varun.gupt 3537
 
5208 varun.gupt 3538
        for order in Order.query.filter(Order.originalOrderId == original_order_id).all():
5139 varun.gupt 3539
            order.vendor_paid = True
3540
            session.commit()
3541
 
3542
        original_order = Order.get_by(id = original_order_id)
3543
        if original_order:  original_order.vendor_paid = True
3544
        session.commit()
5348 anupam.sin 3545
 
3546
def update_COD_agent(agentEmailId, orderId):
3547
    order = Order.get_by(id=orderId)
3548
    if not order:
3549
        raise TransactionServiceException(101, "No order found for the given order id" + str(orderId))
3550
    agent = CodVerificationAgent()
3551
    agent.orderId = orderId
3552
    agent.verificationAgent = agentEmailId
3553
    session.commit()
3554
 
5099 varun.gupt 3555
 
5386 phani.kuma 3556
def update_order_only_as_paid_to_vendor(order_id):
3557
    paid_order = Order.get_by(id = order_id)
3558
    if paid_order is None:
3559
        raise TransactionServiceException(116, "No order found for the given order id")
3560
    paid_order.vendor_paid = True
3561
    session.commit()
3562
 
5208 varun.gupt 3563
def get_refunded_orders_marked_paid():
3564
    orderStatusGroup = OrderStatusGroups()
3565
    return Order.query.filter(Order.vendor_paid == 1).filter(Order.status.in_(orderStatusGroup.refundedOrders)).all()
3566
 
5447 anupam.sin 3567
def get_all_verification_agents(minOrderId, maxOrderId):
3568
    return CodVerificationAgent.query.filter(CodVerificationAgent.orderId >= minOrderId).filter(CodVerificationAgent.orderId <= maxOrderId).all()
3569
 
5527 anupam.sin 3570
def get_all_attributes_for_order_id(orderId):
3571
    return Attribute.query.filter(Attribute.orderId == orderId).all()
3572
 
3573
def set_order_attribute_for_transaction(transactionId, t_attribute):
3574
    for order in Order.query.filter_by(transaction_id = transactionId).all():
3575
        attribute = Attribute()
3576
        attribute.orderId = order.id
3577
        attribute.name = t_attribute.name
3578
        attribute.value = t_attribute.value
3579
        session.commit()
5593 mandeep.dh 3580
 
5558 mandeep.dh 3581
def accept_order_for_item(itemId, quantity, fulfilmentWarehouseId, billingWarehouseId):
5944 mandeep.dh 3582
    inventoryClient = InventoryClient().get_client()
3583
    inventory = inventoryClient.getItemInventoryByItemId(itemId)
5684 mandeep.dh 3584
    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 3585
    for order in orders:
5593 mandeep.dh 3586
        lineitem = order.lineitems[0]
5558 mandeep.dh 3587
        if lineitem.item_id == itemId and lineitem.quantity <= quantity:
5944 mandeep.dh 3588
            warehouse = inventoryClient.getWarehouse(order.fulfilmentWarehouseId)
5684 mandeep.dh 3589
            if not warehouse.billingWarehouseId and warehouse.warehouseType == WarehouseType.THIRD_PARTY:
3590
                if (inventory.availability[fulfilmentWarehouseId] >= inventory.reserved[fulfilmentWarehouseId] + lineitem.quantity) and inventory.availability[order.fulfilmentWarehouseId] < inventory.reserved[order.fulfilmentWarehouseId]:
5966 rajveer 3591
                    inventoryClient.reduceReservationCount(itemId, order.fulfilmentWarehouseId, sourceId, order.id, lineitem.quantity)
3592
                    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 3593
                    order.fulfilmentWarehouseId = fulfilmentWarehouseId
5558 mandeep.dh 3594
                    quantity -= lineitem.quantity
5684 mandeep.dh 3595
                    session.commit()
5593 mandeep.dh 3596
                    if not quantity:
3597
                        break
5558 mandeep.dh 3598
 
6031 rajveer 3599
def get_recharge_order(rechargeOrderId):
6048 rajveer 3600
    return RechargeOrder.get_by(id = rechargeOrderId)
6031 rajveer 3601
 
3602
def get_recharge_orders(userId):
3603
    return RechargeOrder.query.filter_by(userId = userId).all()
3604
 
6279 rajveer 3605
def update_recharge_order_status(rechargeOrderId, rechargeOrderStatus, refundDate=None):
6031 rajveer 3606
    recharge_order = get_recharge_order(rechargeOrderId)
3607
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_FAILED:
3608
        recharge_order.status = RechargeOrderStatus.PAYMENT_FAILED
3609
        session.commit()
3610
        return True
6214 rajveer 3611
 
3612
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED:
3613
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
3614
        session.commit()
3615
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3616
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6214 rajveer 3617
        enqueue_recharge_info_email(recharge_order)
3618
        return True
3619
 
3620
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3621
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
6553 rajveer 3622
        recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
6214 rajveer 3623
        session.commit()
6285 rajveer 3624
        gvs = allocate_gift_voucher(recharge_order)
3625
        enqueue_recharge_info_email(recharge_order, gvs)
6214 rajveer 3626
        return True
3627
 
6279 rajveer 3628
    if rechargeOrderStatus == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3629
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED
3630
        order.responseTimestamp = refundDate
3631
        session.commit()
3632
        update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3633
        update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6279 rajveer 3634
        enqueue_recharge_info_email(recharge_order)
3635
        return True
3636
 
6031 rajveer 3637
    if rechargeOrderStatus == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6285 rajveer 3638
        gvs = {}
6206 rajveer 3639
        recharge_order.status = RechargeOrderStatus.PAYMENT_SUCCESSFUL
3640
        session.commit()
6031 rajveer 3641
        if recharge_order.walletAmount > 0:
3642
            wallet = get_user_wallet(recharge_order.userId)
3643
            if wallet and wallet.amount >= recharge_order.walletAmount:
3644
                update_amount_in_wallet(recharge_order.userId, -recharge_order.walletAmount, recharge_order.id)
3645
            else:
6441 rajveer 3646
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6031 rajveer 3647
                raise TransactionServiceException(103, 'Wallet amount has already been used')
3648
 
6092 rajveer 3649
        try:
3650
            if activate_recharge_txn(recharge_order):
3651
                recharge_order.invoiceNumber = get_next_invoice_number(OrderType.RECHARGE)
3652
                session.commit()
6285 rajveer 3653
                gvs = allocate_gift_voucher(recharge_order)
6092 rajveer 3654
                return True
3655
            else:
3656
                update_amount_in_wallet(recharge_order.userId, recharge_order.walletAmount, recharge_order.id)
6441 rajveer 3657
                update_amount_in_wallet(recharge_order.userId, recharge_order.totalAmount - recharge_order.walletAmount - recharge_order.couponAmount, recharge_order.id)
6092 rajveer 3658
                session.commit()
3659
                return False
3660
        except:
3661
            transaction_requiring_extra_processing = TransactionRequiringExtraProcessing()
3662
            transaction_requiring_extra_processing.category = 'RECHARGE_UNKNOWN'
3663
            transaction_requiring_extra_processing.transaction_id = recharge_order.transaction_id
6031 rajveer 3664
            session.commit()
3665
            return False
6102 rajveer 3666
        finally:
6285 rajveer 3667
            enqueue_recharge_info_email(recharge_order, gvs)
6102 rajveer 3668
 
6031 rajveer 3669
 
6285 rajveer 3670
def allocate_gift_voucher(recharge_order):            
3671
    totalAmount = recharge_order.totalAmount
3672
    gvs = {}
6438 rajveer 3673
    return gvs
6330 rajveer 3674
    if totalAmount >= 100:
3675
        totalAmount=500 if totalAmount >= 500 else totalAmount
6285 rajveer 3676
        try:
3677
            pc = PromotionClient().get_client()
6330 rajveer 3678
            enddate = datetime.datetime.now() + datetime.timedelta(days=45)
6285 rajveer 3679
            while totalAmount > 0:
6330 rajveer 3680
                gvAmount = totalAmount if totalAmount <= 250 else 250
6285 rajveer 3681
                totalAmount = totalAmount - gvAmount
6561 amit.gupta 3682
                gv = pc.createCoupon(26, to_java_date(enddate), recharge_order.userEmailId, gvAmount, False, 1, None)
6285 rajveer 3683
                gvs[gv] = gvAmount  
3684
        except:
3685
            print "Not able to create gift voucher for user " + recharge_order.userEmailId
3686
    return gvs     
3687
 
6048 rajveer 3688
def activate_recharge_txn(recharge_order):
3689
    if isinstance(recharge_order, MobileRechargeOrder):
3690
        rechargeType = 'MTP'
3691
        deviceNumber = recharge_order.mobileNumber
3692
        strProviderCode = get_provider_code(recharge_order.mobileOperatorId)
6161 rajveer 3693
        plan = recharge_order.rechargePlan
6048 rajveer 3694
    if isinstance(recharge_order, DTHRechargeOrder):
3695
        rechargeType = 'RCH'
3696
        deviceNumber = recharge_order.dthAccountNumber
3697
        strProviderCode = get_provider_code(recharge_order.dthOperatorId)
6161 rajveer 3698
        plan = ''
3699
    retStatus, retCode, spiceTID, description = RechargeService.rechargeDevice(recharge_order.id, rechargeType, strProviderCode, deviceNumber, recharge_order.totalAmount, plan)
6231 rajveer 3700
    recharge_order.spiceTID = spiceTID
3701
    recharge_order.responseTimestamp = datetime.datetime.now()
3702
    recharge_order.description = description
3703
    session.commit()
6092 rajveer 3704
    if retCode == '00' and retStatus == 'S':
3705
        recharge_order.status = RechargeOrderStatus.RECHARGE_SUCCESSFUL
3706
        session.commit()
3707
        return True
6259 rajveer 3708
    elif retCode in ('STO', 'US', 'UP') and retStatus == 'S':
6231 rajveer 3709
        raise TransactionServiceException(111, "No response from operator within specified time")
6092 rajveer 3710
    else:
3711
        recharge_order.status = RechargeOrderStatus.RECHARGE_FAILED
6265 rajveer 3712
        if retCode in ('SVAI', 'SVIA', 'AI', 'IA', 'EAI', 'SVEAI'):
3713
            recharge_order.description = "Invalid Amount"
3714
        elif retCode in ('ECL', 'SVECL', 'SCL'):
3715
            recharge_order.description = "Customer Exceeded Daily Limit"
3716
        elif retCode in ('CI', 'ECI', 'ESP', 'SVCI', 'SVECI', 'SVESP', 'SV_ECI', 'SV ECI'):
6399 rajveer 3717
            recharge_order.description = "Invalid Device Number"
6092 rajveer 3718
        session.commit()
6048 rajveer 3719
        return False
6031 rajveer 3720
 
6092 rajveer 3721
 
6031 rajveer 3722
def get_user_wallet(userId):
3723
    wallet = UserWallet.get_by(userId = userId)
3724
    if not wallet:
3725
        wallet = UserWallet()
3726
        wallet.amount = 0
3727
        wallet.userId = userId
3728
    return wallet
3729
 
3730
def get_user_wallet_history(userId):
3731
    wallet = get_user_wallet(userId)
3732
    if wallet.id:
3733
        return UserWalletHistory.query.filter_by(wallet = wallet).all()
3734
    else:
3735
        return []
3736
 
6125 rajveer 3737
def get_provider(providerId):
3738
    return ServiceProvider.query.filter_by(id = providerId).one()
3739
 
6048 rajveer 3740
def get_provider_code(providerId):
3741
    return ServiceProvider.query.filter_by(id = providerId).one().code
6031 rajveer 3742
 
6310 anupam.sin 3743
def get_provider_by_code(providerCode):
3744
    return ServiceProvider.query.filter_by(code = providerCode).one()
6049 rajveer 3745
 
6206 rajveer 3746
def get_service_providers(recharge_type, only_active):
3747
    query = ServiceProvider.query.filter_by(type = recharge_type)
3748
    if only_active:
3749
        query = query.filter_by(status = only_active)
3750
    providers = query.all()
6048 rajveer 3751
    serviceProviders = {}
3752
    for provider in providers:
3753
        serviceProviders[provider.id] = provider.name
3754
    return serviceProviders
3755
 
6049 rajveer 3756
def get_service_provider_for_device(rechargeType, deviceNumber):
3757
    if rechargeType == RechargeType.MOBILE:
3758
        serviceType = 'MTP'
3759
    if rechargeType == RechargeType.DTH:
3760
        serviceType = 'RCH'
6048 rajveer 3761
 
6313 anupam.sin 3762
    provider = None
6537 rajveer 3763
    try:   
3764
        l = len(deviceNumber) 
3765
        if l < 10:
3766
            deviceNumber = deviceNumber + "0" * (10-l) 
6235 rajveer 3767
        providerCode, operatorCircle = RechargeService.checkServiceProviderApi(serviceType, deviceNumber)
6092 rajveer 3768
        if providerCode == 'SNS' or providerCode == '':
3769
            providerId = 0
3770
        else:
6310 anupam.sin 3771
            provider = get_provider_by_code(providerCode)
3772
            providerId = provider.id
6049 rajveer 3773
    except:
6092 rajveer 3774
        providerId = -1
6643 rajveer 3775
        operatorCircle = ""
6092 rajveer 3776
 
6289 anupam.sin 3777
    deviceNumberInfo = DeviceNumberInfo()
6336 anupam.sin 3778
    deviceNumberInfo.circleCode = operatorCircle
6289 anupam.sin 3779
    deviceNumberInfo.operatorId = providerId
6313 anupam.sin 3780
    if provider:
3781
        deviceNumberInfo.operatorName = provider.name
6289 anupam.sin 3782
    return deviceNumberInfo
6269 rajveer 3783
 
6591 anupam.sin 3784
def validate_recharge(rechargeType, deviceNumber, userSelectedProviderId, clientAddress):
3785
 
3786
    addressComponents = clientAddress.split('.')
3787
    n = 3
3788
    addressNumber = 0
3789
    for addressComponent in addressComponents :
3790
        addressNumber = addressNumber + (int(addressComponent) * pow(256, n))
3791
        n = n-1
3792
    matchingRow = BlockedIpRange.query.filter(BlockedIpRange.start <= addressNumber).filter(BlockedIpRange.end >= addressNumber).first()
3793
    #if a match is found then check if date has expired.
3794
    if matchingRow :
3795
        #if expiredOn is None that means this range is permanently blocked.
3796
        if matchingRow.expiredOn is None:
3797
            deniedIpAddress = DeniedIpAddress()
3798
            deniedIpAddress.ip = clientAddress
3799
            deniedIpAddress.deniedOn = datetime.datetime.now()
3800
            deniedIpAddress.deviceNumber = deviceNumber
3801
            deniedIpAddress.rechargeType = rechargeType
3802
            session.commit()
3803
            return "Oops! There seems to be a problem. Please try after some time."
3804
        else :
3805
            #if expired is not None and the blockage is still not expired then block the ip.
3806
            if matchingRow.expiredOn > datetime.datetime.now():
3807
                deniedIpAddress = DeniedIpAddress()
3808
                deniedIpAddress.ip = clientAddress
3809
                deniedIpAddress.deniedOn = datetime.datetime.now()
3810
                deniedIpAddress.deviceNumber = deviceNumber
3811
                deniedIpAddress.rechargeType = rechargeType
3812
                session.commit()
3813
                return "Oops! There seems to be a problem. Please try after some time."
3814
 
3815
 
6307 anupam.sin 3816
    deviceNumberInfo = get_service_provider_for_device(rechargeType, deviceNumber)
3817
    if deviceNumberInfo.operatorId == -1:
3818
        return "Oops! There seems to be a problem. Please try after some time."
6336 anupam.sin 3819
    circle = TelecomCircle.query.filter_by(code = deviceNumberInfo.circleCode).first()
6313 anupam.sin 3820
    if circle:
6734 anupam.sin 3821
        serviceAvailability = ServiceAvailability.query.filter_by(circleId = circle.id).filter_by(operatorId = userSelectedProviderId).first()
3822
        if serviceAvailability.permIsServiceAvailable == False or serviceAvailability.tempIsServiceAvailable == False :
3823
 
6313 anupam.sin 3824
            if deviceNumberInfo.operatorName :
6734 anupam.sin 3825
                if serviceAvailability.permIsServiceAvailable == False:
3826
                    return "We currently do not provide service for " + deviceNumberInfo.operatorName + " in " + circle.name + ". We regret the inconvenience."
6314 anupam.sin 3827
                else :
3828
                    return "We are facing technical issues with " + deviceNumberInfo.operatorName + " in " + circle.name + " currently. Please try later." 
6316 anupam.sin 3829
            else :
6734 anupam.sin 3830
                if serviceAvailability.permIsServiceAvailable == False:
3831
                    return "We currently do not provide service for this operator in " + circle.name + ". We regret the inconvenience."
3832
                else:
3833
                    return "We are facing technical issues with this operator in " + circle.name + " currently. Please try later." 
6719 anupam.sin 3834
    totalSuccessfulRechargeAmount = get_previous_transactions(clientAddress)
3835
    if totalSuccessfulRechargeAmount >= 3000 :
3836
        return "You have exceeded your daily recharge limit. Please try after 24 hours."
6269 rajveer 3837
    return "SUCCESS"
6049 rajveer 3838
 
6719 anupam.sin 3839
def get_previous_transactions(clientAddress):
6271 rajveer 3840
    limittime = datetime.datetime.now() - datetime.timedelta(hours=24)
6719 anupam.sin 3841
    totalSuccessfulRechargeAmount = session.query(func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == 5).filter(RechargeOrder.ipAddress == clientAddress).filter(RechargeOrder.creationTimestamp  > limittime).scalar()
3842
    return totalSuccessfulRechargeAmount    
6269 rajveer 3843
 
6031 rajveer 3844
def update_amount_in_wallet(userId, amount, orderId):
3845
    if amount == 0:
3846
        return
3847
    wallet = get_user_wallet(userId)
3848
    wallet.amount = wallet.amount + amount
3849
 
3850
    history = UserWalletHistory()
3851
    history.amount = amount
3852
    history.orderId = orderId
3853
    history.wallet = wallet
3854
    history.timestamp = datetime.datetime.now()
3855
    session.commit()
6056 amit.gupta 3856
 
6094 rajveer 3857
def get_recharge_orders_for_device(deviceNumber):
3858
    orders = MobileRechargeOrder.query.filter_by(mobileNumber = deviceNumber).all()
3859
    if orders is None:
3860
        orders = DTHRechargeOrder.query.filter_by(dthAccountNumber = deviceNumber).all()
3861
    return orders
3862
 
6154 rajveer 3863
def get_recharge_orders_for_status(status):
3864
    if status == -1:
6161 rajveer 3865
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).all()
6154 rajveer 3866
    else:
6161 rajveer 3867
        orders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = status).all()
6154 rajveer 3868
    return orders
3869
 
6188 rajveer 3870
def get_recharge_statistics():
3871
    rs = RechargeStatistics()
3872
    statusCounts = {}
3873
    operatorCounts = {}
3874
    currentOrders = {}
3875
    amounts = {}
3876
 
3877
    sorders = session.query(RechargeOrder.status, func.count(RechargeOrder.status)).group_by(RechargeOrder.status).all()
3878
    for sorder in sorders:
6190 rajveer 3879
        statusCounts[sorder[0]] = sorder[1]
6188 rajveer 3880
 
3881
    oorders = session.query(MobileRechargeOrder.mobileOperatorId, func.count(MobileRechargeOrder.mobileOperatorId)).group_by(MobileRechargeOrder.mobileOperatorId).all()
3882
    for oorder in oorders:
6190 rajveer 3883
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 3884
 
3885
    oorders = session.query(DTHRechargeOrder.dthOperatorId, func.count(DTHRechargeOrder.dthOperatorId)).group_by(DTHRechargeOrder.dthOperatorId).all()
3886
    for oorder in oorders:
6190 rajveer 3887
        operatorCounts[oorder[0]] = oorder[1]
6188 rajveer 3888
 
6219 rajveer 3889
    forders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED).limit(20).all()
6188 rajveer 3890
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED)] = [order.to_thrift_object() for order in forders]
3891
    sorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_SUCCESSFUL).limit(20).all()
6197 rajveer 3892
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_SUCCESSFUL)] = [order.to_thrift_object() for order in sorders]
6216 rajveer 3893
    porders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.PAYMENT_SUCCESSFUL).limit(20).all()
3894
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.PAYMENT_SUCCESSFUL)] = [order.to_thrift_object() for order in porders]
6238 rajveer 3895
    rorders = RechargeOrder.query.order_by(desc(RechargeOrder.id)).filter_by(status = RechargeOrderStatus.RECHARGE_FAILED_REFUNDED).limit(20).all()
3896
    currentOrders[RechargeOrderStatus._VALUES_TO_NAMES.get(RechargeOrderStatus.RECHARGE_FAILED_REFUNDED)] = [order.to_thrift_object() for order in rorders]
6188 rajveer 3897
 
6190 rajveer 3898
    twa = session.query(func.sum(UserWallet.amount)).one()
3899
    tra = session.query(func.sum(RechargeOrder.totalAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
3900
    gwa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId > 100000).one()
6278 rajveer 3901
    #tpa = session.query(func.sum(UserWalletHistory.amount)).filter(UserWalletHistory.orderId < 100000).one()
6482 rajveer 3902
    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()
3903
    tda = session.query(func.sum(RechargeOrder.couponAmount)).filter(RechargeOrder.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL).one()
3904
 
6346 rajveer 3905
    balance = RechargeService.getBalance()
6305 rajveer 3906
    amounts['(a) Total Payment Amount'] = tpa[0]
3907
    amounts['(b) Gift Wallet Amount'] = gwa[0]
3908
    amounts['(c) Total Wallet Amount'] = twa[0]
3909
    amounts['(d) Total Recharge Amount'] = tra[0]
3910
    amounts['(e) Account Balance'] = balance
6482 rajveer 3911
    amounts['(f) Discount Balance'] = tda[0]
6278 rajveer 3912
    #amounts['Total Payment Amount'] = tra[0] + twa[0] - gwa[0]
6524 rajveer 3913
    amounts['Saholic Mismatch = (a+b+f-c-d)'] = tpa[0] + gwa[0] + tda[0] - tra[0] - (twa[0] + 63774)
3914
    amounts['SpiceDeck Mismatch = (d-e)'] = tra[0] + balance - 750000 
6278 rajveer 3915
 
6337 rajveer 3916
    '''
6318 rajveer 3917
    if amounts['SpiceDeck Mismatch = (d-e)'] != -739:
3918
        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)']), "", [], [], [])
3919
    if amounts['Saholic Mismatch = (a+b-c-d)'] != -1919:
3920
        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 3921
    '''
6318 rajveer 3922
 
6188 rajveer 3923
    rs.statusCounts = statusCounts
3924
    rs.operatorCounts = operatorCounts    
3925
    rs.currentOrders = currentOrders
3926
    rs.amounts = amounts
3927
 
3928
    return rs
3929
 
3930
 
6159 rajveer 3931
def get_plans_for_operator(operator_id):
3932
    return RechargePlan.query.filter_by(operatorId = operator_id).all()
3933
 
6056 amit.gupta 3934
def get_recharge_orders_for_transaction(txId):
3935
    return RechargeOrder.query.filter_by(transaction_id = txId).first()
6102 rajveer 3936
 
6285 rajveer 3937
def enqueue_recharge_info_email(recharge_order, gvs={}):
6102 rajveer 3938
    status = ""
3939
    message = ""
3940
    html_header = """
3941
 
3942
    <html>
3943
    <body>
3944
    <div>
3945
        <p>
3946
            Hello $email,<br /><br />
6127 rajveer 3947
            Thanks for placing recharge order with us. Following are the details of your recharge order:
6102 rajveer 3948
        </p>
3949
        <div>
6136 rajveer 3950
            Order Id : $order_id <br/>
3951
            Order Date : $order_date <br/>
3952
            Order Amount : Rs. $order_amount <br/>
3953
            Order Status : $order_status <br/>
3954
            Device Number : $device_number <br/>
3955
            Service Provider : $service_provider <br/>
6102 rajveer 3956
        </div>
6348 rajveer 3957
    <br />
6102 rajveer 3958
    """
6288 rajveer 3959
 
3960
    FailureReasonMap = {}
3961
    FailureReasonMap["Invalid Amount"] = "the amount you tried seems to be invalid. Please try another amount."
3962
    FailureReasonMap["Customer Exceeded Daily Limit"] = "you have exceeded daily recharge limit for this number. Please try after 12 hours."
6399 rajveer 3963
    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 3964
 
3965
    failureReason = FailureReasonMap.get(recharge_order.description)
3966
    if failureReason is None:
3967
        failureReason = "of network failure."
6102 rajveer 3968
    if recharge_order.status == RechargeOrderStatus.RECHARGE_SUCCESSFUL:
3969
        status = "Recharge Successful"
3970
        message = ""
6444 rajveer 3971
        if recharge_order.couponAmount > 0:
3972
            message = message + "<b>You have used coupon " + recharge_order.couponCode + " and got discount of Rs. " + str(recharge_order.couponAmount) + ".</b>" 
3973
 
6102 rajveer 3974
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED:
3975
        status = "Recharge Failed"
6127 rajveer 3976
        message = """
6288 rajveer 3977
                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 3978
                """
6206 rajveer 3979
    elif recharge_order.status == RechargeOrderStatus.PAYMENT_SUCCESSFUL:
6102 rajveer 3980
        status = "Recharge Under Process"
6127 rajveer 3981
        message = """
6288 rajveer 3982
                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 3983
                """
6279 rajveer 3984
    elif recharge_order.status == RechargeOrderStatus.RECHARGE_FAILED_REFUNDED:
3985
        status = "Recharge Failed, Amount Refunded"
3986
        message = """
3987
                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>
3988
                """
6285 rajveer 3989
    if len(gvs) > 0:
6340 rajveer 3990
        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 3991
        message = message + " <br />  <b>Voucher Code &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Amount</b>"
6285 rajveer 3992
        for gv in gvs.keys():
3993
            gvAmount = gvs.get(gv)
6330 rajveer 3994
            message = message + " <br />  <b>" + gv + "&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Rs. "  + str(gvAmount) + "</b>"
6285 rajveer 3995
 
6114 rajveer 3996
    message = message  + '<br />  In case of any problem, please  <a href="$source_url/contact-us">contact us</a>'
6102 rajveer 3997
 
6136 rajveer 3998
    html_header = html_header + message
6102 rajveer 3999
    html_footer = """
4000
    <p>
4001
        Best Wishes,<br />
4002
        $source_name Team
4003
    </p>
4004
    </div>
4005
    </body>
4006
    </html>
4007
    """
4008
 
6125 rajveer 4009
    if isinstance(recharge_order, MobileRechargeOrder):
4010
        deviceNumber = recharge_order.mobileNumber
4011
        providerName = get_provider(recharge_order.mobileOperatorId).name
4012
    if isinstance(recharge_order, DTHRechargeOrder):
4013
        deviceNumber = recharge_order.dthAccountNumber
4014
        providerName = get_provider(recharge_order.dthOperatorId).name
4015
 
6127 rajveer 4016
    display_order_id = recharge_order.idPrefix + str(recharge_order.id)
6102 rajveer 4017
    email = recharge_order.userEmailId
4018
    dt = datetime.datetime.strptime(str(recharge_order.creationTimestamp), "%Y-%m-%d %H:%M:%S")
4019
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
4020
 
6288 rajveer 4021
    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 4022
    email_footer = Template(html_footer).substitute(dict(source_url = source_url, source_name = source_name))
4023
 
4024
    try:
4025
        helper_client = HelperClient().get_client()
6643 rajveer 4026
        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 4027
        return True
4028
    except Exception as e:
4029
        print e
4030
        return False
4031
 
6307 anupam.sin 4032
def get_recharge_denominations(operator_id, circleCode, denomination_type):
4033
    circle_id = TelecomCircle.query.filter_by(code = circleCode).first().id
6289 anupam.sin 4034
    return RechargeDenomination.query.filter_by(operatorId = operator_id).filter_by(circleId = circle_id).filter_by(denominationType = denomination_type).all()
6371 rajveer 4035
 
4036
def update_availability_status(operatorId, circleId, isAvailable):
4037
    serviceAvailability = ServiceAvailability.query.filter_by(circleId = circleId).filter_by(operatorId = operatorId).first()
6734 anupam.sin 4038
    serviceAvailability.tempIsServiceAvailable = isAvailable
6371 rajveer 4039
    session.commit()
4040
 
6389 rajveer 4041
def get_misc_charges(transactionId):
4042
    retCharges = {}
4043
    miscCharges = MiscCharges.get_by(transaction_id = transactionId)
4044
    if miscCharges:
6426 rajveer 4045
        retCharges[1] = miscCharges.chargeAmount 
6389 rajveer 4046
    return retCharges
6396 amit.gupta 4047
 
4048
def get_available_emi_schemes():
4049
    t_emi_schemes = []
4050
    emi_schemes = EmiScheme.query.all()
4051
    if emi_schemes:
4052
        t_emi_schemes = [to_t_emi_scheme(emi_scheme) for emi_scheme in emi_schemes]
4053
    return t_emi_schemes
6389 rajveer 4054
 
6507 anupam.sin 4055
def refund_recharge_order(rechargeOrderId):
4056
    try :
4057
        rechargeOrder = RechargeOrder.query.filter_by(id = rechargeOrderId).first()
4058
        wallet = UserWallet.query.filter_by(userId = rechargeOrder.userId).first()
4059
    except:
4060
        return False
4061
 
4062
    paidAmount = rechargeOrder.totalAmount - rechargeOrder.walletAmount - rechargeOrder.couponAmount
4063
    amountToRefund = 0
4064
    status = None
4065
    if (paidAmount <= wallet.amount) :
4066
        amountToRefund = paidAmount
4067
        status = RechargeOrderStatus.REFUNDED
4068
    else :
4069
        amountToRefund = wallet.amount
4070
        status = RechargeOrderStatus.PARTIALLY_REFUNDED
4071
 
4072
    update_amount_in_wallet(rechargeOrder.userId, -amountToRefund, rechargeOrderId)
4073
 
4074
    try:    
4075
        pc = PaymentClient().get_client()
4076
        if pc.refundPayment(rechargeOrder.transaction_id, amountToRefund, True) :
4077
            rechargeOrder.status = status
6515 anupam.sin 4078
            rechargeOrder.refundTimestamp = datetime.datetime.now()
6507 anupam.sin 4079
            session.commit()
4080
            return True
4081
        else :
4082
            update_amount_in_wallet(rechargeOrder.userId, amountToRefund, rechargeOrderId)
4083
 
4084
    except:
4085
        update_amount_in_wallet(rechargeOrder.userId, amountToRefund, rechargeOrderId)
4086
 
4087
    return False 
4088
 
4089
 
766 rajveer 4090
def close_session():
4091
    if session.is_active:
4092
        print "session is active. closing it."
2783 chandransh 4093
        session.close()
3376 rajveer 4094
 
4095
def is_alive():
4096
    try:
4097
        session.query(Transaction.id).limit(1).one()
4098
        return True
4099
    except:
6000 mandeep.dh 4100
        return False
4101
 
4102
if __name__ == '__main__':
4103
    print 'Inside main'
4104
    DataService.initialize()
6561 amit.gupta 4105
    '''a = MobileRechargeOrder()
4106
    session.commit()
6000 mandeep.dh 4107
    a.mobileNumber = 89564785666
6567 amit.gupta 4108
    session.commit()
4109
    '''