Subversion Repositories SmartDukaan

Rev

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