Subversion Repositories SmartDukaan

Rev

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