Subversion Repositories SmartDukaan

Rev

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