Subversion Repositories SmartDukaan

Rev

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