Subversion Repositories SmartDukaan

Rev

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