Subversion Repositories SmartDukaan

Rev

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