Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
6561 amit.gupta 1
#!/usr/bin/python
2
'''
3
It processes the following reports received from Couriers
4
through email:
5
 1. Pickup Report : contains details of orders that were 
6
     picked up from our warehouse, Return orders and DOA orders that were
7
     picked up from our customers.
8
 2. Delivery & RTO Report: contains details of orders that
9
     were either successfully delivered to our customers or
10
     which are being returned to us.
11
 3. Non-delivery Report: contains details of orders whose
12
     delivery date has passed but which have not been 
13
     delivered yet.
14
 
15
It sends out a Pickup mismatch report, Return orders Pickup Mismatch report, Doa Pickup mismatch report,
16
Undelivered orders report and Returned Orders report to cnc.center@shop2020.in
17
 
18
@author: Chandranshu
19
'''
13143 manish.sha 20
from shop2020.clients import HelperClient
21
from shop2020.clients.TransactionClient import TransactionClient
13085 amit.gupta 22
from shop2020.clients.CRMClient import CRMClient
23
from shop2020.clients.UserClient import UserClient
24
from shop2020.thriftpy.crm.ttypes import SearchFilter, TicketCategory, Ticket, \
25
    Activity, TicketPriority, TicketStatus, ActivityType
26
from shop2020.thriftpy.model.v1.order.ttypes import OrderStatus, \
27
    TransactionServiceException
28
from shop2020.thriftpy.model.v1.user.ttypes import PrivateDealUser
29
from shop2020.utils.Utils import to_py_date
6561 amit.gupta 30
from string import Template
31
import sys
32
import traceback
33
 
34
if __name__ == '__main__' and __package__ is None:
35
    import os
36
    sys.path.insert(0, os.getcwd())
37
 
8570 manish.sha 38
logistics_providers = {1: {'name': 'BlueDart', 'phone': '011-66111234'}, 2: {'name': 'Aramex', 'phone': '0124- 39419900'}, 3: {'name': 'Delhivery', 'phone' : '0124- 4212200'}, 7: {'name': 'FedEx', 'phone' : '0120-4354176'}, 6: {'name' : 'RedExpress', 'phone' : '8373915813'}}
6561 amit.gupta 39
FDASubjectTemplate = Template('First attempt made to deliver your $productName')
40
FDABodyTemplate = Template('<div>'+
41
                            '<p> Dear $customerName,<br>'+
42
                            '<br>An attempt was made to deliver the product you ordered. The Courier '+
43
                            'used was: $courierName and Airway Bill Number: $awbNumber. '+
44
                            'However, the product could not be delivered due to $delayReason. '+
45
                            'Please<a target="_blank" href="http://saholic.com/contactus"> Contact us </a>to coordinate the next delivery date.</p>'+
46
                            '<div> <span>Order</span> Date: $orderDate</div>'+
47
                            '<div>'+
48
                            '<table>'+
49
                            '  <tbody>'+
50
                            '    <tr>'+
51
                            '      <td colspan="6">'+
52
                            '      <hr></td>'+
53
                            '    </tr>'+
54
                            '    <tr>'+
55
                            '      <td align="left" colspan="6"><b><span>Order</span> <span>Details</span></b></td>'+
56
                            '    </tr>'+
57
                            '    <tr>'+
58
                            '      <td colspan="6">'+
59
                            '      <hr></td>'+
60
                            '    </tr>'+
61
                            '    <tr>'+
62
                            '      <th width="100"><span>Order</span> No.</th>'+
63
                            '      <th>Product</th>'+
64
                            '      <th width="100">Quantity</th>'+
65
                            '      <td style="vertical-align:top"><span style="font-weight:bold">First Delivery Attempt</span><br>'+
66
                            '      </td>'+
67
                            '<th width="100">Unit Price</th>'+
68
                            '      <th width="100">Amount</th>'+
69
                            '    </tr>'+
70
                            '    <tr>'+
71
                            '      <td align="center">$orderId</td>'+
72
                            '      <td>$productName</td>'+
73
                            '      <td align="center">$quantity</td>'+
74
                            '      <td style="vertical-align:top">$fdaDate</td>'+
75
                            '<td align="center"> Rs. $unitPrice</td>'+
76
                            '      <td align="center"> Rs. $total</td>'+
77
                            '    </tr>'+
78
                            '    '+
79
                            '    <tr>'+
80
                            '      <td colspan="6">'+
81
                            '      <hr></td>'+
82
                            '    </tr>'+
83
                            '    <tr>'+
84
                            '      <td colspan="5">Total Amount</td>'+
85
                            '      <td> Rs. $totalAmount</td>'+
86
                            '    </tr>'+
87
                            '    <tr>'+
88
                            '      <td style="vertical-align:top" rowspan="1" colspan="6"><br>'+
89
                            '</td>'+
90
                            '    </tr>'+
91
                            '<tr>'+
92
                            '      <td colspan="6">'+
93
                            '      <hr></td>'+
94
                            '    </tr>'+
95
                            '  </tbody>'+
96
                            '</table>'+
97
                            '</div>'+
98
                            '<br>'+
99
                            '<p>Best Wishes,<br>'+
100
                            'Saholic Team </p>'+
101
                            '</div>')
102
 
103
 
18458 manish.sha 104
dtrUndeliveredAsssigneeId = 18
105
defaultUndeliveredAsssigneeId = 18
13085 amit.gupta 106
 
107
 
6561 amit.gupta 108
def enqueueMailForFDA(order):
109
    dt = to_py_date(order.created_timestamp)
110
    formatted_order_date = dt.strftime("%A, %d. %B %Y %I:%M%p")
111
 
112
    sdt = to_py_date(order.first_attempt_timestamp)
113
    fda_date = sdt.strftime("%d %B %Y")
114
    '''order.lineitems[0]
115
    '''
116
    lineitem = order.lineitems[0]
117
    productName = "{0} {1} {2} {3}".format(lineitem.brand or "", lineitem.model_name or "", lineitem.model_number or "", lineitem.color or "")
118
    subject = FDASubjectTemplate.substitute(productName=productName)
119
    body = FDABodyTemplate.substitute(productName=productName, customerName=order.customer_name, quantity="%.0f" % lineitem.quantity,
120
                                      orderDate=formatted_order_date, orderId=order.id, unitPrice="%.2f" % lineitem.unit_price,
121
                                      total = "%.2f" % lineitem.total_price, totalAmount = "%.2f" % order.total_amount, fdaDate= fda_date,
122
                                      delayReason=order.statusDescription , awbNumber=order.airwaybill_no, courierName = logistics_providers[order.logistics_provider_id]['name'])
123
    print body
124
    try:
125
        helper_client = HelperClient(host_key = "helper_service_server_host_prod").get_client()
10298 manish.sha 126
        helper_client.saveUserEmailForSending([order.customer_email], "", subject, body, str(order.id), "FirstDeliveryAttempted", [], ['kshitij.sood@shop2020.in', 'rajneesh.arora@shop2020.in', 'pramit.singh@shop2020.in', 'amit.sirohi@shop2020.in', 'rajveer.singh@shop2020.in'], 1)
6561 amit.gupta 127
    except Exception as e:
128
        print "Some problem occurred while enquing mail for user" + str(order.id) +" to inform FIRST_DELIVERY_ATTEMPT_MADE status"
129
        print e
13085 amit.gupta 130
 
131
def create_crm_tickets_for_delivey_attempted_orders(provider):
132
    try:
133
        tickets_tobe_created = fetch_data(provider.id, [OrderStatus.FIRST_DELIVERY_ATTEMPT_MADE, OrderStatus.RTO_IN_TRANSIT])
134
        userClient = UserClient().get_client()
135
        crmServiceClient = CRMClient().get_client()
136
        for order in tickets_tobe_created:
137
            ticket_created = False
138
            searchFilter = SearchFilter()
139
            user = userClient.getUserByEmail(order.customer_email)
140
            privateDealUser = PrivateDealUser()
141
            if user is None or user.userId == -1:
142
                searchFilter.customerEmailId = order.customer_email
143
                searchFilter.customerMobileNumber = order.customer_mobilenumber
144
            else:
145
                searchFilter.customerId = user.userId
13145 manish.sha 146
                privateDealUser= userClient.getPrivateDealUser(user.userId)
13085 amit.gupta 147
            searchFilter.ticketCategory = TicketCategory.UNDELIVERED
148
            tickets = crmServiceClient.getTickets(searchFilter)
149
            print tickets
150
            for old_ticket in tickets:
151
                if old_ticket.orderId == order.id:
152
                    ticket_created = True
153
                    break
154
            if not ticket_created:
155
                if order.status == OrderStatus.RTO_IN_TRANSIT and not privateDealUser.isActive:
156
                    continue
157
 
158
                print "creating ticket for orderId:"+str(order.id)
159
                ticket = Ticket()
160
                activity = Activity()
161
                description = order.statusDescription + "\n\nOrder not delivered by courier due to problems at customer end."
162
                ticket.creatorId = 1
163
                #Tickets of Undelivered tickets to private deal user should be assigned to Ritesh
164
                if privateDealUser.isActive:
165
                    ticket.assigneeId = dtrUndeliveredAsssigneeId
166
                else:    
167
                    ticket.assigneeId = defaultUndeliveredAsssigneeId
168
                ticket.category = TicketCategory.UNDELIVERED
169
                ticket.priority = TicketPriority.HIGH
170
                ticket.status = TicketStatus.OPEN
171
                ticket.description = description
172
                ticket.orderId = order.id
173
                ticket.airwayBillNo = order.airwaybill_no
174
 
175
                activity.creatorId = 1
176
                activity.ticketAssigneeId = ticket.assigneeId
177
                activity.type = ActivityType.OTHER
178
                activity.description = description
179
                activity.ticketCategory = ticket.category
180
                activity.ticketDescription = ticket.description
181
                activity.ticketPriority = ticket.priority
182
                activity.ticketStatus = ticket.status
183
 
184
                if user is None or user.userId == -1:
185
                    ticket.customerEmailId = order.customer_email
186
                    ticket.customerMobileNumber = order.customer_mobilenumber
187
                    ticket.customerName = order.customer_name
188
                    activity.customerEmailId = order.customer_email
189
                    activity.customerMobileNumber = order.customer_mobilenumber
190
                    activity.customerName = order.customer_name
191
                else:
192
                    ticket.customerId = user.userId
193
                    activity.customerId = user.userId
194
 
195
                crmServiceClient.insertTicket(ticket, activity)
196
                '''
197
                Inform user about first delivery attempt
198
                '''
199
                if not OrderStatus.RTO_IN_TRANSIT:
200
                    enqueueMailForFDA(order)
201
    except:
202
        print "Some issue while creating crm tickets for orders in FIRST_DELIVERY_ATTEMPT_MADE status"
203
        traceback.print_exc()
204
 
205
def fetch_data(provider_id, order_status_list):
206
    txnClient = TransactionClient().get_client()
207
    try:
208
        doas_tobe_picked_up = txnClient.getOrdersForProviderForStatus(provider_id, order_status_list)
209
        return doas_tobe_picked_up
210
    except TransactionServiceException as tex:
211
        print tex.message