Subversion Repositories SmartDukaan

Rev

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