Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
104 ashish 1
'''
2
Created on 29-Mar-2010
3
 
4
@author: ashish
5
'''
1262 varun.gupt 6
from string import Template
7
from shop2020.thriftpy.utils.ttypes import HelperServiceException, Mail
8
 
104 ashish 9
from shop2020.model.v1.order.impl.DataService import Transaction, LineItem,\
1225 chandransh 10
    Alerts, Order, BatchNoGenerator
104 ashish 11
from shop2020.thriftpy.model.v1.order.ttypes import Transaction as T_Transaction,\
690 chandransh 12
    TransactionServiceException, TransactionStatus, OrderStatus
1565 varun.gupt 13
import datetime 
1479 ankur.sing 14
import time
122 ashish 15
from elixir import *
855 rajveer 16
from shop2020.utils.Utils import to_py_date, to_java_date
1886 ankur.sing 17
from sqlalchemy.sql.expression import and_, or_, desc
1627 ankur.sing 18
from sqlalchemy.sql import func
483 rajveer 19
from shop2020.model.v1 import order
743 rajveer 20
from shop2020.clients.LogisticsClient import LogisticsClient
871 chandransh 21
from shop2020.clients.InventoryClient import InventoryClient
1262 varun.gupt 22
from shop2020.clients.UserClient import UserClient
1351 varun.gupt 23
from shop2020.clients.HelperClient import HelperClient
104 ashish 24
 
25
def get_new_transaction():
26
    transaction = Transaction()
27
    transaction.createdOn = datetime.datetime.now()
738 chandransh 28
    transaction.status = TransactionStatus.INIT
104 ashish 29
    transaction.status_message = "New transaction"
483 rajveer 30
    return transaction
31
 
32
def create_order(t_order):
33
    order = Order()
34
    if t_order.warehouse_id:
35
        order.warehouse_id = t_order.warehouse_id
509 rajveer 36
    if t_order.logistics_provider_id:    
483 rajveer 37
        order.logistics_provider_id = t_order.logistics_provider_id
38
        order.airwaybill_no = t_order.airwaybill_no
39
        order.tracking_id = t_order.tracking_id
40
    if t_order.expected_delivery_time:    
41
        order.expected_delivery_time = to_py_date(t_order.expected_delivery_time)
42
    if t_order.customer_id:    
43
        order.customer_id = t_order.customer_id
44
        order.customer_name = t_order.customer_name
860 rajveer 45
        order.customer_city = t_order.customer_city
46
        order.customer_state = t_order.customer_state
483 rajveer 47
        order.customer_mobilenumber = t_order.customer_mobilenumber
48
        order.customer_pincode = t_order.customer_pincode
738 chandransh 49
        order.customer_address1 = t_order.customer_address1
50
        order.customer_address2 = t_order.customer_address2
483 rajveer 51
        order.customer_email = t_order.customer_email
52
    #new status and status description to be added    
716 rajveer 53
    order.status = t_order.status  
483 rajveer 54
    order.statusDescription = t_order.statusDescription
55
    order.total_amount = t_order.total_amount
56
    order.total_weight = t_order.total_weight
57
    if t_order.created_timestamp:
58
        order.created_timestamp = to_py_date(t_order.created_timestamp)
59
    else:
685 chandransh 60
        order.created_timestamp = datetime.datetime.now()
483 rajveer 61
    return order
62
 
63
def create_transaction(t_transaction):
64
    t_orders = t_transaction.orders
65
    if not t_orders:
66
        raise TransactionServiceException(101, "Orders missing from the transaction")
67
    transaction = get_new_transaction()
68
    transaction.customer_id = t_transaction.customer_id 
69
    transaction.shopping_cart_id = t_transaction.shoppingCartid
70
 
71
    for t_order in t_orders:
72
        order = create_order(t_order)
73
        order.transaction = transaction 
74
        for line_item in t_order.lineitems:
75
            litem = LineItem()
716 rajveer 76
            litem.item_id = line_item.item_id
963 chandransh 77
            litem.productGroup = line_item.productGroup
483 rajveer 78
            litem.brand = line_item.brand
79
            if line_item.model_number:
80
                litem.model_number = line_item.model_number
81
            if line_item.model_name:    
82
                litem.model_name = line_item.model_name
908 chandransh 83
            if line_item.color:
84
                litem.color = line_item.color
483 rajveer 85
            if line_item.extra_info:
86
                litem.extra_info = line_item.extra_info
87
            litem.quantity = line_item.quantity
88
            litem.unit_price = line_item.unit_price
89
            litem.unit_weight = line_item.unit_weight
90
            litem.total_price = line_item.total_price
91
            litem.total_weight = line_item.total_weight
1262 varun.gupt 92
            litem.transfer_price = line_item.transfer_price
483 rajveer 93
            """
94
            if line_item.addedOn:
95
                litem.added_on = to_py_date(line_item.addedOn)
96
            else:
97
                litem.added_on = datetime.datetime.now()
98
            """
99
            litem.order = order
100
    session.commit()
101
    return transaction.id
102
 
103
def get_transaction(transaction_id):
104
    transaction = Transaction.get_by(id=transaction_id)
105
    if not transaction:
106
        raise TransactionServiceException(108, "no such transaction")
107
 
108
    return transaction
109
 
110
def get_transactions_for_customer(customer_id, from_date, to_date, status):
111
    if not customer_id:
112
        raise TransactionServiceException(101, "bad customer id")
113
    query = Transaction.query.filter(Transaction.customer_id == customer_id)
1493 vikas 114
    if status is not None:
483 rajveer 115
        query = query.filter(Transaction.status == status)
116
    if from_date:
117
        query = query.filter(Transaction.createdOn >from_date)
118
    if to_date:
119
        query = query.filter(Transaction.createdOn < to_date)
120
    return query.all()
121
 
122
def get_transactions_for_shopping_cart_id(shopping_cart_id):
123
    transactions = Transaction.query.filter_by(shopping_cart_id=shopping_cart_id).all()
124
    return transactions
125
 
126
def get_transaction_status(transaction_id):
127
    if not transaction_id:
128
        raise TransactionServiceException(101, "bad transaction id")
129
 
130
    transaction = get_transaction(transaction_id)
131
 
132
    return transaction.status
133
 
134
def change_transaction_status(transaction_id, new_status, description):
135
    transaction = get_transaction(transaction_id)
136
    transaction.status = new_status
137
    transaction.status_message = description
690 chandransh 138
    if new_status == TransactionStatus.FAILED:
139
        for order in transaction.orders:
140
            order.status = OrderStatus.PAYMENT_FAILED
141
    elif new_status == TransactionStatus.IN_PROCESS:
142
        for order in transaction.orders:
143
            order.status = OrderStatus.SUBMITTED_FOR_PROCESSING
1219 chandransh 144
            order.statusDescription = "Submitted to warehouse"
743 rajveer 145
            #After we got payment success, we will set logistics info also 
146
            logistics_client = LogisticsClient().get_client()
147
            #FIXME line item is only one now. If multiple will come, need to fix.
871 chandransh 148
            item_id = order.lineitems[0].item_id
149
            logistics_info = logistics_client.getLogisticsInfo(order.customer_pincode, item_id)
743 rajveer 150
 
1730 ankur.sing 151
            current_time = datetime.datetime.now()
152
            logistics_info.deliveryTime = adjust_delivery_time(current_time, logistics_info.deliveryTime)
153
 
743 rajveer 154
            order.warehouse_id = logistics_info.warehouseId
155
            order.logistics_provider_id = logistics_info.providerId
156
            order.airwaybill_no = logistics_info.airway_billno
157
            order.tracking_id = order.airwaybill_no
1730 ankur.sing 158
            order.expected_delivery_time = current_time + datetime.timedelta(days=logistics_info.deliveryTime)
871 chandransh 159
 
160
            catalog_client = InventoryClient().get_client()
161
            catalog_client.reserveItemInWarehouse(item_id, logistics_info.warehouseId, order.lineitems[0].quantity)
1351 varun.gupt 162
 
1341 chandransh 163
            item_pricing = catalog_client.getItemPricing(item_id, order.warehouse_id)
164
            order.lineitems[0].transfer_price = item_pricing.transferPrice
1262 varun.gupt 165
 
483 rajveer 166
    session.commit()
167
    return True
168
 
1730 ankur.sing 169
def adjust_delivery_time(order_time, delivery_days):
170
    order_date = order_time.date()
171
 
172
    delivery_date = order_date + datetime.timedelta(days = delivery_days)
173
    final_delivery_date = delivery_date
174
 
175
    time_format = "%Y-%m-%d %H:%M:%S.%f"
176
    t = time.strptime(str(order_time), time_format)
177
    midnightTime = datetime.datetime(*t[:3])
178
    fromDate = to_java_date(midnightTime)
179
    toDate = -1L
180
 
181
    logistics_client = LogisticsClient().get_client()
182
    holiday_dates = logistics_client.getHolidays(fromDate, toDate)
183
    holiday_dates = [(to_py_date(h_date)).date() for h_date in holiday_dates]
184
 
185
    while order_date <= final_delivery_date:
186
        if order_date.weekday() == 6 or is_holiday(holiday_dates, order_date):
187
            delivery_days = delivery_days + 1
188
            final_delivery_date = final_delivery_date + datetime.timedelta(days = 1)
189
        order_date = order_date + datetime.timedelta(days = 1)
190
    return delivery_days
191
 
192
 
193
 
194
def is_holiday(holidays, date):
195
    try:
196
        holidays.index(date)
197
        return 1
198
    except:
199
        return 0
200
 
1398 varun.gupt 201
def enqueue_transaction_info_email(transaction_id):
1262 varun.gupt 202
    transaction = get_transaction(transaction_id)
203
 
204
    html_header = """
205
<html>
206
<body>
207
<div>
208
    <p>
209
        Hello,<br /><br />
1742 rajveer 210
        Thanks for placing order with us. Following are the details of your order:
1262 varun.gupt 211
    </p>
212
    <div>
213
        Order Date: $order_date
1569 varun.gupt 214
    </div>
1262 varun.gupt 215
    <div>
216
        <table>
1569 varun.gupt 217
        <tr><td colspan="5"><hr /></td></tr>
218
        <tr><td colspan="5" align="left"><b>Order Details</b></td></tr>
219
        <tr><td colspan="5"><hr /></td></tr>
1262 varun.gupt 220
        <tr>
1569 varun.gupt 221
            <th>&nbsp;&nbsp;Order No.&nbsp;&nbsp;</th>
222
            <th>&nbsp;&nbsp;Product&nbsp;&nbsp;</th>
223
            <th>&nbsp;&nbsp;Quantity&nbsp;&nbsp;</th>
224
            <th>&nbsp;&nbsp;Unit Price&nbsp;&nbsp;</th>
225
            <th>&nbsp;&nbsp;Amount&nbsp;&nbsp;</th>
1262 varun.gupt 226
        </tr>
227
    """
1398 varun.gupt 228
    user_email = ""
1262 varun.gupt 229
    total_amount = 0.0
230
    html_table = ""
1569 varun.gupt 231
    order_date = datetime.datetime.now()
1262 varun.gupt 232
 
233
    for order in transaction.orders:
234
        order_date = order.created_timestamp
1398 varun.gupt 235
        user_email = order.customer_email
1569 varun.gupt 236
        html_tr = "<tr><td align='center'>" + str(order.id) + "</td>"
1262 varun.gupt 237
 
238
        for lineitem in order.lineitems:
1276 chandransh 239
            html_tr += "<td>" + str(lineitem) + "</td>"
1569 varun.gupt 240
            html_tr += "<td align='center'>" + str(lineitem.quantity) + "</td>"
241
            html_tr += "<td align='center'>" + str(lineitem.unit_price) + "</td>"
242
            html_tr += "<td align='center'>" + str(lineitem.total_price) + "</td></tr>"
1262 varun.gupt 243
            total_amount += lineitem.total_price
244
            html_table += html_tr
245
    html_footer = """
246
        <tr><td colspan=5>&nbsp;</td></tr>
1565 varun.gupt 247
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 248
        <tr>
249
            <td colspan=4>Total Amount</td>
250
            <td>$total_amount</td>
251
        </tr>
1569 varun.gupt 252
        <tr><td colspan=5><hr /></td></tr>
1262 varun.gupt 253
        </table>
1569 varun.gupt 254
    </div>
1262 varun.gupt 255
    <p>
256
        Best Wishes,<br />
257
        Saholic Team
258
    </p>
259
</div>
260
</body>
261
</html>
262
    """
1398 varun.gupt 263
 
1569 varun.gupt 264
    dt = datetime.datetime.strptime(str(order_date), "%Y-%m-%d %H:%M:%S")
1565 varun.gupt 265
    formated_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
266
 
1262 varun.gupt 267
    email_header = Template(html_header).substitute(dict(order_date = formated_order_date))
268
    email_footer = Template(html_footer).substitute(dict(total_amount = total_amount))
269
 
1351 varun.gupt 270
    try:
271
        helper_client = HelperClient().get_client()
1398 varun.gupt 272
        helper_client.saveUserEmailForSending(user_email, "", "Saholic - Order Details", email_header + html_table + email_footer, str(transaction_id), "TransactionInfo")
1351 varun.gupt 273
        return True
274
    except Exception as e:
275
        print e
276
        return False
1262 varun.gupt 277
 
483 rajveer 278
def get_order(order_id):
279
    order = Order.get_by(id=order_id)
280
    if not order:
281
        raise TransactionServiceException(108, "no such order")
282
 
283
    return order
284
 
285
def get_orders_for_customer(customer_id, from_date, to_date, status):
286
    if not customer_id:
287
        raise TransactionServiceException(101, "bad customer id")
288
    query = Order.query.filter(Order.customer_id == customer_id)
289
    if status:
290
        query = query.filter(Order.status == status)
291
    if from_date:
292
        query = query.filter(Order.created_timestamp >from_date)
293
    if to_date:
294
        query = query.filter(Order.created_timestamp < to_date)
295
    return query.all()
296
 
1528 ankur.sing 297
def get_order_for_customer(order_id, customer_id):
298
    if not customer_id:
299
        raise TransactionServiceException(101, "bad customer id")
300
    order = get_order(order_id)
301
    if order.customer_id != customer_id:
302
        raise TransactionServiceException(108, "order: " + str(order_id) + " does not belong to customer: " + str(customer_id))
303
    return order
304
 
483 rajveer 305
def get_all_orders(status, from_date, to_date, warehouse_id):
306
    if not warehouse_id:
307
        raise TransactionServiceException(101, "bad warehouse id")
308
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
309
    if status:
310
        query = query.filter(Order.status == status)
311
    if from_date:
312
        query = query.filter(Order.created_timestamp >from_date)
313
    if to_date:
314
        query = query.filter(Order.created_timestamp < to_date)
315
    return query.all()
316
 
1382 varun.gupt 317
def get_returnable_orders_for_customer(customer_id, limit = None):
318
    if not customer_id:
319
        raise TransactionServiceException(101, "bad customer id")
320
 
321
    query = Order.query.filter(Order.customer_id == customer_id)
322
    query = query.filter(Order.status != OrderStatus.PAYMENT_FAILED)
323
    query = query.filter(Order.status != OrderStatus.REJECTED)
324
    query = query.filter(Order.status > OrderStatus.SHIPPED_FROM_WH)
325
    query = query.filter(or_(Order.status < OrderStatus.DELIVERY_SUCCESS, Order.delivery_timestamp < datetime.datetime.now() + datetime.timedelta(hours = 48)))
326
    orders = query.all()
327
    order_ids = [order.id for order in orders]
328
    return order_ids
329
 
330
def get_cancellable_orders_for_customer(customer_id, limit = None):
331
    if not customer_id:
332
        raise TransactionServiceException(101, "bad customer id")
333
 
334
    query = Order.query.filter(Order.customer_id == customer_id)
335
    query = query.filter(Order.status != OrderStatus.REJECTED)
1483 varun.gupt 336
    query = query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING)
1382 varun.gupt 337
    query = query.filter(Order.status < OrderStatus.BILLED)
338
    orders = query.all()
339
    return [order.id for order in orders]
340
 
995 varun.gupt 341
def get_orders_by_billing_date(status, start_billing_date, end_billing_date, warehouse_id):
342
    if not warehouse_id:
343
        raise TransactionServiceException(101, "bad warehouse id")
344
 
345
    query = Order.query.filter(Order.warehouse_id == warehouse_id)
346
 
347
    if status:
348
        query = query.filter(Order.status == status)
349
 
350
    if start_billing_date:
351
        query = query.filter(Order.billing_timestamp >= start_billing_date)
352
 
353
    if end_billing_date:
354
        query = query.filter(Order.billing_timestamp <= end_billing_date)
355
 
356
    return query.all()
357
 
1528 ankur.sing 358
def get_orders_for_transaction(transaction_id, customer_id):
359
    orders = Order.query.filter_by(transaction_id=transaction_id, customer_id=customer_id).all()
360
 
1208 chandransh 361
    if not orders:
362
        raise TransactionServiceException(101, "No order for the transaction")
363
    return orders
364
 
1405 ankur.sing 365
def get_undelivered_orders(provider_id, warehouse_id):
366
    query = Order.query
367
    if provider_id != -1:
368
        query = query.filter_by(Order.logistics_provider_id == provider_id)
369
    if warehouse_id != -1:
370
        query = query.filter(Order.warehouse_id == warehouse_id)
371
    query = query.filter(and_(Order.status != OrderStatus.DELIVERY_SUCCESS, Order.status != OrderStatus.FAILED, \
372
                              Order.status > OrderStatus.SHIPPED_FROM_WH))
1479 ankur.sing 373
    #Get last midnight time instead of current time as courier company would have sent the 
374
    #delivery records updated at least till midnight and not by the current time.
375
    time_format = "%Y-%m-%d %H:%M:%S.%f"
376
    t = time.strptime(str(datetime.datetime.now()), time_format)
377
    midnightTime = datetime.datetime(*t[:3])
378
    query = query.filter(Order.expected_delivery_time < midnightTime)
1405 ankur.sing 379
    orders = query.all()
380
    return orders
381
 
1208 chandransh 382
def get_line_items_for_order(order_id):
383
    query = LineItem.query.filter(LineItem.order_id == order_id)
384
    return query.all()
385
 
483 rajveer 386
def change_order_status(self, orderId, status, description):
387
    order = get_order(orderId)
388
    order.status = status
389
    order.statusDescription = description
390
    session.commit()
391
    return True
392
 
921 rajveer 393
def accept_order(self, orderId):
394
    order = get_order(orderId)
395
    order.status = OrderStatus.ACCEPTED
396
    order.statusDescription = "Order Accepted"
397
    order.accepted_timestamp = datetime.datetime.now()
398
    session.commit()
399
    return True
400
 
401
def bill_order(self, orderId):
402
    order = get_order(orderId)
403
    order.status = OrderStatus.BILLED
404
    order.statusDescription = "Order Billed"
405
    order.billing_timestamp = datetime.datetime.now()
406
    session.commit()
1208 chandransh 407
    return True
921 rajveer 408
 
1149 chandransh 409
def add_billing_details(orderId, invoice_number, billed_by):
494 rajveer 410
    order = Order.get_by(id=orderId)
411
    if not order:
412
        raise TransactionServiceException(101, "No order found for the givem orderid")
413
    order.invoice_number = invoice_number
414
    order.billed_by = billed_by
415
    session.commit()
416
    return True
759 chandransh 417
 
1149 chandransh 418
def add_jacket_number(orderId, jacket_number):
419
    order = Order.get_by(id=orderId)
420
    if not order:
421
        raise TransactionServiceException(101, "No order found for the givem orderid")
422
    order.jacket_number = jacket_number 
423
    session.commit()
424
    return True
425
 
1220 chandransh 426
def batch_orders(warehouseId):
427
    if not warehouseId:
428
        raise TransactionServiceException(101, "bad warehouse id")
1225 chandransh 429
 
430
    batchno_generator = BatchNoGenerator()
431
    session.commit()
1220 chandransh 432
    query = Order.query.filter_by(warehouse_id=warehouseId)
433
    query = query.filter_by(status=OrderStatus.SUBMITTED_FOR_PROCESSING)
434
    query = query.order_by(Order.created_timestamp)
435
    pending_orders = query.all()
1225 chandransh 436
 
1220 chandransh 437
    serial_no = 1
438
    for order in pending_orders:
1276 chandransh 439
        order.batchNo = batchno_generator.id
1220 chandransh 440
        order.serialNo = serial_no
441
        serial_no += 1
442
    session.commit() 
443
    pending_orders = query.all()
444
    return pending_orders
445
 
446
def order_outofstock(orderId):
447
    order = get_order(orderId)
448
    order.status = OrderStatus.INVENTORY_LOW
449
    order.statusDescription = "Low Inventory"
450
    order.outofstock_timestamp = datetime.datetime.now()
451
    session.commit()
452
    return True
453
 
759 chandransh 454
def mark_orders_as_manifested(warehouse_id, provider_id):
455
    try:
986 chandransh 456
        current_timestamp = datetime.datetime.now()
852 chandransh 457
        orders = Order.query.filter_by(warehouse_id = warehouse_id, logistics_provider_id = provider_id, status = OrderStatus.BILLED).all()
759 chandransh 458
        for order in orders:
459
            order.status = OrderStatus.SHIPPED_FROM_WH
987 chandransh 460
            order.statusDescription = "Order shipped from warehouse"
986 chandransh 461
            order.shipping_timestamp = current_timestamp
759 chandransh 462
        session.commit()
463
        return True
464
    except:
465
        return False
1113 chandransh 466
 
467
def mark_orders_as_picked_up(provider_id, pickup_details):
468
    for awb, pickup_timestamp in pickup_details.iteritems():
1135 chandransh 469
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1113 chandransh 470
        if order == None:
471
            raise TransactionServiceException(102, "No order found for the awb: " + awb)
472
        order.status = OrderStatus.SHIPPED_TO_LOGST
473
        order.statusDescription = "Order picked up by Courier Company"
1246 chandransh 474
        order.pickup_timestamp = pickup_timestamp
1113 chandransh 475
    session.commit()
1217 chandransh 476
 
1132 chandransh 477
    current_time = datetime.datetime.now()
478
    to_datetime = datetime.datetime(current_time.year, current_time.month, current_time.day)
1246 chandransh 479
    from_datetime = to_datetime - datetime.timedelta(2)
1132 chandransh 480
    orders_not_picked_up = Order.query.filter_by(logistics_provider_id = provider_id).filter_by(status=OrderStatus.SHIPPED_FROM_WH).filter(Order.shipping_timestamp >= from_datetime).filter(Order.shipping_timestamp <= to_datetime).all()
1113 chandransh 481
    return orders_not_picked_up
482
 
1132 chandransh 483
def mark_orders_as_delivered(provider_id, delivered_orders):
484
    for awb, detail in delivered_orders.iteritems():
1135 chandransh 485
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
1132 chandransh 486
        if order == None:
487
            raise TransactionServiceException(103, "No order found for the awb:" + awb)
488
        order.status = OrderStatus.DELIVERY_SUCCESS
489
        order.statusDescription = "Order delivered"
490
        order.delivery_timestamp, order.receiver = detail.split('|')
491
    session.commit()
492
 
1135 chandransh 493
def mark_orders_as_failed(provider_id, returned_orders):
494
    for awb, detail in returned_orders.iteritems():
495
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
496
        if order == None:
497
            raise TransactionServiceException(103, "No order found for the awb:" + awb)
498
        order.status = OrderStatus.FAILED
499
        order.delivery_timestamp, reason = detail.split('|')
500
        order.statusDescription = "Order Returned to Origin:" + reason
501
    session.commit()    
502
 
1246 chandransh 503
def update_non_delivery_reason(provider_id, undelivered_orders):
504
    for awb, reason in undelivered_orders.iteritems():
505
        order = Order.query.filter_by(airwaybill_no=awb, logistics_provider_id = provider_id).first()
506
        if order == None:
507
            raise TransactionServiceException(103, "No order found for the awb:" + awb)
508
        order.statusDescription = reason
509
    session.commit()
510
 
483 rajveer 511
def get_alerts(order_id, all):
512
    query = Alerts.query.filter_by(order_id=order_id)
513
    if not all:
514
        query = query.filter_by(valid=True)
515
    return query.all()
516
 
517
def set_alert(order_id, unset, type, comment):
518
    #get existing alert
519
    if unset:
520
        query = Alerts.query.filter_by(order_id=order_id)
521
        query = query.filter_by(type=type)
522
        alerts = query.all()
523
        for alert in alerts:
524
            if alert.valid:
525
                alert.valid = False
526
                alert.comment = comment
527
                alert.time_unset = datetime.datetime.now()
528
    else:
529
        alert = Alerts()
530
        alert.order_id = order_id
531
        alert.valid = True
532
        alert.type = type
533
        alert.comment = comment
534
        alert.time_set = datetime.datetime.now()
766 rajveer 535
    session.commit()    
536
 
1596 ankur.sing 537
def get_valid_order_count():
538
    return Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).count()
539
 
1627 ankur.sing 540
def get_cust_count_with_successful_txn():
541
    return session.query(Order.customer_id).filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).distinct().count()
542
 
1730 ankur.sing 543
def get_valid_orders_amount_range():
1627 ankur.sing 544
    orders = Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING).all()
545
    order_amounts = [o.total_amount for o in orders]
1730 ankur.sing 546
    return [min(order_amounts), max(order_amounts)]
1627 ankur.sing 547
 
1886 ankur.sing 548
def get_valid_orders(limit):
549
    query = Order.query.filter(Order.status >= OrderStatus.SUBMITTED_FOR_PROCESSING)
550
    query = query.order_by(desc(Order.created_timestamp))
551
    if limit > 0:
552
        query = query.limit(limit)
553
    elif limit < 0:
554
        raise TransactionServiceException(101, "Invalid argument limit " + limit)
555
    return query.all()
556
 
766 rajveer 557
def close_session():
558
    if session.is_active:
559
        print "session is active. closing it."
560
        session.close()