Subversion Repositories SmartDukaan

Rev

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