Subversion Repositories SmartDukaan

Rev

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