Subversion Repositories SmartDukaan

Rev

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