Subversion Repositories SmartDukaan

Rev

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