Subversion Repositories SmartDukaan

Rev

Rev 6916 | Rev 6927 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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