acc_partner.py
14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# -*- coding: utf-8 -*-
import logging
from odoo import api, fields, models, _
from odoo.http import request
import logging
import xlrd
from collections import Counter
import re
import pytz
from odoo.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
from datetime import datetime
# from ..controllers.common import localizeStrTime
from odoo.exceptions import UserError, ValidationError
_logger = logging.getLogger(__name__)
class res_partner_acc(models.Model):
_inherit = 'res.partner'
charge_person = fields.Many2one('res.users',string="负责人",default=lambda self: self.env.user.id,required=True)
traffic_level = fields.Selection([('0', '一般'), ('1', '低'), ('2', '高'), ('3', '非常高')], '运输时间评级', default='0')
quality_level = fields.Selection([('0', '一般'), ('1', '低'), ('2', '高'), ('3', '非常高')], '质量评级', default='0')
price_level = fields.Selection([('0', '一般'), ('1', '低'), ('2', '高'), ('3', '非常高')], '价格评级', default='0')
acc_image = fields.Binary("营业执照", attachment=True)
# @api.model
# def create(self,vals):
# if vals.get('name') and not vals.get('parent_id'):
# name_list = []
# new_name = vals.get('name','')
# request.cr.execute("""select name from res_partner""")
# names = request.cr.dictfetchall()
# for name in names:
# name_list.append(name['name'])
# if new_name in name_list:
# raise ValidationError('供应商或客户名称重复!!')
# res = super(res_partner_acc, self).create(vals)
# return res
#采购订单中根据所选供应商对联系人进行筛选
@api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
args = args or []
context = self.env.context
if context.get('choose_contact') or context.get('sale_choose_contact'):
domain = []
contact = self.search(args, limit=limit)
return contact.name_get()
if context.get('crm_choose_contact'):
domain = []
contact = self.search(args, limit=limit)
return contact.name_get()
# else:
# contact = self.search(args, limit=limit)
# return contact.name_get()
return super(res_partner_acc, self).name_search(name=name, args=args, operator=operator, limit=limit)
@api.model
def search(self, args, offset=0, limit=None, order=None, count=False):
context = self.env.context
# if self._uid == 2:
# return super(res_partner_acc, self).search(args, offset, limit, order, count)
# # 管理部门
# elif self.env.user.has_group('acct_base.acc_manage_level1_group'):
# return super(res_partner_acc, self).search(args, offset, limit, order, count)
# # 商务部
# elif self.env.user.has_group('acct_base.acc_commerce_user_group'):
# args.extend([('supplier', '=', True)])
# return super(res_partner_acc, self).search(args, offset, limit, order, count)
if context.get('choose_contact') or context.get('sale_choose_contact'):
partner_id = context.get('partner_id','')
# print company_id
contact_ids = []
if partner_id:
# machines = machines_ids[0][2]
# print machines_ids
cr = self.env.cr
sql = """
SELECT
ID
FROM
res_partner
WHERE
parent_id = %s
""" %(partner_id)
cr.execute(sql)
contact_ids = cr.fetchall()
contact_ids = [contact[0] for contact in contact_ids]
args.append(('id','in',contact_ids))
order = 'name desc'
if context.get('crm_choose_contact'):
partner_id = context.get('partner_id','')
# print company_id
contact_ids = []
if partner_id:
# machines = machines_ids[0][2]
# print machines_ids
cr = self.env.cr
sql = """
SELECT
ID
FROM
res_partner
WHERE
parent_id = %s
""" %(partner_id)
cr.execute(sql)
contact_ids = cr.fetchall()
contact_ids = [contact[0] for contact in contact_ids]
args.append(('id','in',contact_ids))
order = 'name desc'
return super(res_partner_acc, self).search(args, offset, limit, order, count)
@api.onchange('charge_person')
def onchange_en_name(self):
if self.charge_person:
self.user_id = self.charge_person
def import_supply(self, fileName=None, content=None):
import_tips = ""
card_number_repeated = False
try:
if content:
workbook = xlrd.open_workbook(file_contents=content)
else:
raise ValidationError(u'请选择正确的文档')
book_sheet = workbook.sheet_by_index(0)
all_data = []
all_card_number = []
# all_card_id = []
# re_pattern = re.compile(u'^[0-9a-zA-Z]+$')
# re_pattern_id = re.compile(u'^[W]{1}[G]{1}[0-9]{6}')
for row in range(1, book_sheet.nrows):
row_data = []
for col in range(book_sheet.ncols):
cel = book_sheet.cell(row, col)
val = cel.value
row_data.append(val)
if type(row_data[2]).__name__ == 'float':
row_data[2] = int(row_data[2])
if type(row_data[3]).__name__ == 'float':
row_data[3] = int(row_data[3])
all_data.append(row_data)
all_card_number.append(str(row_data[0]))
# print (type(row_data[2]))
# all_card_id.append(str(row_data[1]))
card_counter = dict(Counter(all_card_number))
# card_counter_id = dict(Counter(all_card_id))
for key, value in card_counter.items():
if value > 1:
import_tips = "供应商名称:%s 在导入表中出现多次,请处理"%( key )
card_number_repeated = True
raise ValidationError(import_tips)
cr = self.env.cr
exist_cards = []
if all_card_number:
sql = """select name from res_partner where name in %s"""
cr.execute(sql,(tuple(all_card_number),))
exist_cards_tmp = cr.fetchall()
exist_cards = [tmp[0] for tmp in exist_cards_tmp]
error_card_number = []
success_num = 0
for import_line in all_data:
if import_line[0] in exist_cards:
error_card_number.append(import_line[0])
else:
# search([('name', '=ilike', currency_code)], limit=1)
res_country_state = self.env['res.country.state'].search([('name', '=', import_line[7])], limit=1)
res_country = self.env['res.country'].search([('name', '=', import_line[8])],limit=1)
try:
vals = {
"name":str(import_line[0]),
"street":import_line[1],
"phone":str(import_line[2]),
"mobile":str(import_line[3]),
"website":import_line[4],
"email":import_line[5],
'city':import_line[6],
'state_id':res_country_state.id,
"country_id":res_country.id,
"company_type":'company',
"supplier":True,
"customer":False,
}
# employee_id = self.with_context(user_type='employee').create(vals)
self.env['res.partner'].create(vals)
cr.commit()
success_num += 1
# print (import_line[0])
_logger.debug('===========%s===============', import_line[0])
except Exception as e:
logging.error(e)
error_card_number.append(import_line[0])
# exist_message = ""
if exist_cards:
exist_message = "导入名称在系统中存在的有 {} 条,不做导入处理,名称分别为 {}".format(len(exist_cards), ','.join(exist_cards))
# exist_id_message = ""
# if exist_card_ids:
# exist_message = "导入储值卡ID在系统中存在的有 {} 条,不做导入处理,储值卡ID分别为 {}".format(len(exist_card_ids), ','.join(exist_card_ids))
# error_message = ""
# if error_card_number:
# error_message = "由于卡号格式不正确导致导入失败 {} 条, 卡号分别为 {}".format(len(error_card_number), ','.join(error_card_number))
# error_id_message = ""
# if error_card_id:
# error_id_message = "由于储值卡ID格式不正确导致导入失败 {} 条, 卡号分别为 {}".format(len(error_card_id), ','.join(error_card_id))
import_tips = "一共导入 {} 条数据,导入成功条数为{} ,重复数据{}".format(len(all_data), success_num,exist_cards)
except Exception as e:
logging.error(e)
if card_number_repeated:
raise ValidationError(import_tips)
# elif card_id_repeated:
# raise ValidationError(import_id_tips)
else:
raise ValidationError('请使用正确的模板进行导入操作!')
else:
raise ValidationError(import_tips)
def import_contact(self, fileName=None, content=None):
import_tips = ""
# card_number_repeated = False
try:
if content:
workbook = xlrd.open_workbook(file_contents=content)
else:
raise ValidationError(u'请选择正确的文档')
book_sheet = workbook.sheet_by_index(0)
all_data = []
all_card_number = []
for row in range(1, book_sheet.nrows):
row_data = []
for col in range(book_sheet.ncols):
cel = book_sheet.cell(row, col)
val = cel.value
row_data.append(val)
if type(row_data[1]).__name__ == 'float':
row_data[1] = int(row_data[1])
if type(row_data[2]).__name__ == 'float':
row_data[2] = int(row_data[2])
all_data.append(row_data)
cr = self.env.cr
error_partner_name = []
success_num = 0
for import_line in all_data:
# if import_line[0] in exist_cards:
# error_card_number.append(import_line[0])
# else:
# res_country_state = self.env['res.country.state'].search([('name', '=', str(import_line[7]))])
res_partner = self.env['res.partner'].search([('name', '=', str(import_line[3]))],limit=1)
# title = self.env['res.partner.title'].search([('name', '=', str(import_line[7]))])
if not res_partner:
error_partner_name.append(import_line[0])
else:
parent_id = res_partner.id
try:
vals = {
"name":import_line[0],
"phone":import_line[1],
"mobile":import_line[2],
"parent_id":parent_id,
"email":import_line[4],
'function':import_line[5],
'website':str(import_line[6]),
# 'title':import_line[7],
# 'city':str(import_line[5]),
# "country_id":int(import_line[6]),
"company_type":'person',
"supplier":True
}
# employee_id = self.with_context(user_type='employee').create(vals)
self.env['res.partner'].create(vals)
cr.commit()
success_num += 1
# print (import_line[0],import_line[1])
_logger.debug('===========%s===============%s', import_line[0],import_line[1])
except Exception as e:
logging.error(e)
error_partner_name.append(import_line[0])
import_tips = "一共导入 {} 条数据,导入成功条数为{} 导入失败联系人名称{}".format(len(all_data), success_num,error_partner_name)
except Exception as e:
logging.error(e)
# if card_number_repeated:
# raise ValidationError(import_tips)
# elif card_id_repeated:
# raise ValidationError(import_id_tips)
# else:
# raise ValidationError('请使用正确的模板进行导入操作!')
else:
raise ValidationError(import_tips)
@api.multi
def action_see_attachments(self):
domain = ['&', ('res_model', '=', 'res.partner'), ('res_id', '=', self.id)]
attachment_view = self.env.ref('acct_base.view_partner_document_file_kanban_acct')
return {
'name': _('Attachments'),
'domain': domain,
'res_model': 'mrp.document',
'type': 'ir.actions.act_window',
'view_id': attachment_view.id,
'views': [(attachment_view.id, 'kanban'), (False, 'form')],
'view_mode': 'kanban,tree,form',
'view_type': 'form',
'help': _('''<p class="o_view_nocontent_smiling_face">
Upload files to your product
</p><p>
Use this feature to store any files, like drawings or specifications.
</p>'''),
'limit': 80,
'context': "{'default_res_model': '%s','default_res_id': %d}" % ('res.partner', self.id)
}