diff --git a/sf_bf_connect/models/process_status.py b/sf_bf_connect/models/process_status.py index 111254c7..3bbdb5fc 100644 --- a/sf_bf_connect/models/process_status.py +++ b/sf_bf_connect/models/process_status.py @@ -1,3 +1,4 @@ +import traceback from datetime import datetime import logging import requests @@ -53,11 +54,14 @@ class StatusChange(models.Model): if not ret.get('error'): logging.info('接口已经执行=============') else: - logging.error('工厂加工同步订单状态失败 {}'.format(ret)) - raise UserError('工厂加工同步订单状态失败') + traceback_error = traceback.format_exc() + logging.error("bfm订单状态同步失败:%s request info %s" % traceback_error) + logging.error('/api/get/state/get_order 请求失败{}'.format(ret)) + raise UserError('工厂加工同步订单状态到bfm失败') except UserError as e: - logging.error('工厂加工同步订单状态失败 {}'.format(e)) - raise UserError('工厂加工同步订单状态失败') + traceback_error = traceback.format_exc() + logging.error("工厂加工同步订单状态失败:%s " % traceback_error) + raise UserError(e) return res def action_cancel(self): diff --git a/sf_dlm_management/views/product_template_management_view.xml b/sf_dlm_management/views/product_template_management_view.xml index 2cdfd1a3..caefcb34 100644 --- a/sf_dlm_management/views/product_template_management_view.xml +++ b/sf_dlm_management/views/product_template_management_view.xml @@ -1,6 +1,11 @@ + + + {"search_default_categ_id":1,"search_default_consumable": 1, 'default_detailed_type': 'product'} + + product.template.form.inherit.sf product.template @@ -88,7 +93,8 @@ - + - - - - - + + + + + diff --git a/sf_machine_connect/controllers/controllers.py b/sf_machine_connect/controllers/controllers.py index 35f4a257..e301154b 100644 --- a/sf_machine_connect/controllers/controllers.py +++ b/sf_machine_connect/controllers/controllers.py @@ -6,7 +6,7 @@ import base64 import logging import psycopg2 from datetime import datetime, timedelta -from odoo import http +from odoo import http, fields from odoo.http import request # 数据库连接配置 @@ -15,14 +15,18 @@ db_config = { "user": "postgres", "password": "postgres", "port": "5432", - "host": "172.16.10.98" + "host": "172.16.10.113" } def convert_to_seconds(time_str): # 修改正则表达式,使 H、M、S 部分可选 + if time_str is None: + return 0 + pattern = r"(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?" + match = re.match(pattern, time_str) if match: @@ -66,7 +70,7 @@ class Sf_Dashboard_Connect(http.Controller): # 获取当前时间的时间戳 current_timestamp = datetime.now().timestamp() - print(current_timestamp) + # print(current_timestamp) # tem_list = [ # "XT-GNJC-WZZX-X800-Y550-Z550-T24-A5-1", "XT-GNJC-LSZX-X800-Y550-Z550-T24-A3-3", @@ -162,7 +166,8 @@ class Sf_Dashboard_Connect(http.Controller): 'first_online_duration': first_online_duration, # 停机时间:关机时间 - 运行时间 # 停机时长:关机时间 - 初次上线时间 - 'img': f'data:image/png;base64,{machine_data.machine_tool_picture.decode("utf-8")}', + # 'img': f'data:image/png;base64,{machine_data.machine_tool_picture.decode("utf-8")}', + 'img': f'https://xt.sf.jikimo.com/equipment/get_image/{machine_data.id}', 'equipment_type': machine_data.category_id.name, }) @@ -194,7 +199,7 @@ class Sf_Dashboard_Connect(http.Controller): begin_time = datetime.strptime(begin_time_str, '%Y-%m-%d %H:%M:%S') end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S') - print('begin_time: %s' % begin_time) + # print('begin_time: %s' % begin_time) for item in machine_list: sql = ''' @@ -275,7 +280,7 @@ class Sf_Dashboard_Connect(http.Controller): res = {'Succeed': True} line_list_obj = request.env['sf.production.line'].sudo().search([('name', 'ilike', 'CNC')]) line_list = list(map(lambda x: x.name, line_list_obj)) - print('line_list: %s' % line_list) + # print('line_list: %s' % line_list) res['LineList'] = line_list except Exception as e: @@ -300,21 +305,40 @@ class Sf_Dashboard_Connect(http.Controller): try: plan_obj = request.env['sf.production.plan'].sudo() + production_obj = request.env['mrp.production'].sudo() line_list = ast.literal_eval(kw['line_list']) - print('line_list: %s' % line_list) + # print('line_list: %s' % line_list) for line in line_list: - plan_data = plan_obj.search([('production_line_id.name', '=', line)]) - # 工单总量 - plan_data_total_counts = plan_obj.search_count([('production_line_id.name', '=', line)]) + + # 工单计划量 + plan_data_total_counts = production_obj.search_count( + [('production_line_id.name', '=', line), ('state', 'not in', ['cancel']), + ('active', '=', True)]) # 工单完成量 plan_data_finish_counts = plan_obj.search_count( [('production_line_id.name', '=', line), ('state', 'in', ['finished'])]) - # 工单计划量 - plan_data_plan_counts = plan_obj.search_count( - [('production_line_id.name', '=', line), ('state', 'not in', ['finished'])]) - # 工单不良累计 - plan_data_fault_counts = plan_obj.search_count( - [('production_line_id.name', '=', line), ('production_id.state', 'in', ['scrap', 'cancel'])]) + # # 工单计划量 + # plan_data_plan_counts = plan_obj.search_count( + # [('production_line_id.name', '=', line), ('state', 'not in', ['finished'])]) + + # 查找符合条件的生产计划记录 + plan_data = plan_obj.search([ + ('production_line_id.name', '=', line), + ]) + + # 过滤出那些检测结果状态为 '返工' 或 '报废' 的记录 + faulty_plans = plan_data.filtered(lambda p: any( + result.test_results in ['返工', '报废'] for result in p.production_id.detection_result_ids + )) + + # 查找制造订单取消与归档的数量 + cancel_order_count = production_obj.search_count( + [('production_line_id.name', '=', line), ('state', 'in', ['cancel']), + ('active', '=', False)]) + + # 计算符合条件的记录数量 + # plan_data_fault_counts = len(faulty_plans) + cancel_order_count + plan_data_fault_counts = len(faulty_plans) # 工单返工数量 @@ -326,17 +350,76 @@ class Sf_Dashboard_Connect(http.Controller): (plan_data_finish_counts / plan_data_total_counts if plan_data_total_counts > 0 else 0), 3) # 工单进度偏差 - plan_data_progress_deviation = plan_data_finish_counts - plan_data_plan_counts + plan_data_progress_deviation = plan_data_total_counts - plan_data_finish_counts - plan_data_fault_counts + + # 完成记录 + plan_data_finish_orders = plan_obj.search( + [('production_line_id.name', '=', line), ('state', 'in', ['finished'])]) + + # # 检测量 + # detection_nums = 0 + # for i in plan_data_finish_orders: + # print('i: %s' % i) + # if i.production_id.detection_result_ids: + # detection_nums += 1 + # + # print('detection_nums: %s' % detection_nums) + + # 检测量 + detection_data = len( + plan_data_finish_orders.mapped('production_id.detection_result_ids').filtered(lambda r: r)) + + # 检测合格量 + pass_nums = plan_data_finish_orders.filtered(lambda p: any( + result.test_results in ['合格'] for result in p.production_id.detection_result_ids + )) + + # 质量合格率 + pass_rate = 1 + if pass_nums: + pass_rate = round( + (len(pass_nums) / detection_data if len(plan_data_finish_orders) > 0 else 0), 3) + + # 返工率 + rework_rate = round( + (plan_data_rework_counts / plan_data_finish_counts if plan_data_finish_counts > 0 else 0), 3) + + # 交付准时率 + delay_num = 0 + for plan in plan_data_finish_orders: + sale_obj = request.env['sale.order'].sudo().search([('name', '=', plan.origin)]) + if sale_obj: + if sale_obj.deadline_of_delivery and plan.actual_end_time: + # 将 deadline_of_delivery 转换为字符串 + date_as_string = sale_obj.deadline_of_delivery.strftime('%Y-%m-%d') + # 然后使用 strptime 将字符串转换为 datetime 对象 + date_as_datetime = datetime.strptime(date_as_string, '%Y-%m-%d') + + # 将 actual_end_time 转换为 datetime 对象 + datetime_value = fields.Datetime.from_string(plan.actual_end_time) + + # 给 datetime_value 加1天 + new_datetime_value = datetime_value + timedelta(days=1) + + # 比较 new_datetime_value 和 date_as_datetime 的大小 + if new_datetime_value.date() > date_as_datetime.date(): + delay_num += 1 + delay_rate = round((delay_num / plan_data_finish_counts if plan_data_finish_counts > 0 else 0), 3) + on_time_rate = 1 - delay_rate if plan_data: data = { 'plan_data_total_counts': plan_data_total_counts, 'plan_data_finish_counts': plan_data_finish_counts, - 'plan_data_plan_counts': plan_data_plan_counts, + 'plan_data_plan_counts': plan_data_total_counts, 'plan_data_fault_counts': plan_data_fault_counts, + 'nopass_orders_counts': detection_data - len(pass_nums), 'finishe_rate': finishe_rate, 'plan_data_progress_deviation': plan_data_progress_deviation, - 'plan_data_rework_counts': plan_data_rework_counts + 'plan_data_rework_counts': plan_data_rework_counts, + 'on_time_rate': on_time_rate, + 'detection_data': detection_data, + 'pass_rate': pass_rate } res['data'][line] = data @@ -363,7 +446,28 @@ class Sf_Dashboard_Connect(http.Controller): end_time_str = kw['end_time'].strip('"') begin_time = datetime.strptime(begin_time_str, '%Y-%m-%d %H:%M:%S') end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S') - print('line_list: %s' % line_list) + # print('line_list: %s' % line_list) + print('kw', kw) + time_unit = kw.get('time_unit', 'day').strip('"') # 默认单位为天 + print('time_unit: %s' % time_unit) + + # 日期或小时循环生成器,根据time_unit决定是按天还是按小时 + def get_time_intervals(start_time, end_time, time_unit): + intervals = [] + current_time = start_time + if time_unit == 'hour': + delta = timedelta(hours=1) + else: + delta = timedelta(days=1) + + while current_time < end_time: + next_time = current_time + delta + # 确保最后一个时间段不会超出end_time + if next_time > end_time: + next_time = end_time + intervals.append((current_time, next_time)) + current_time = next_time + return intervals def get_date_list(start_date, end_date): date_list = [] @@ -374,10 +478,33 @@ class Sf_Dashboard_Connect(http.Controller): return date_list for line in line_list: - date_list = get_date_list(begin_time, end_time) + date_field_name = 'actual_end_time' # 替换为你模型中的实际字段名 order_counts = [] - date_field_name = 'actual_end_time' # 替换为你模型中的实际字段名 + if time_unit == 'hour': + time_intervals = get_time_intervals(begin_time, end_time, time_unit) + print('============================= %s' % time_intervals) + + time_count_dict = {} + + for time_interval in time_intervals: + start_time, end_time = time_interval + # print(start_time, end_time) + orders = plan_obj.search([('production_line_id.name', '=', line), ('state', 'in', ['finished']), + (date_field_name, '>=', start_time.strftime('%Y-%m-%d 00:00:00')), + (date_field_name, '<', end_time.strftime('%Y-%m-%d 00:00:00')) + ]) + # 使用小时和分钟作为键,确保每个小时的数据有独立的键 + key = start_time.strftime('%H:%M:%S') # 只取小时:分钟:秒作为键 + time_count_dict[key] = len(orders) + # order_counts.append() + res['data'][line] = { + 'finish_order_nums': time_count_dict, + 'plan_order_nums': 28 + } + return json.dumps(res) + + date_list = get_date_list(begin_time, end_time) for date in date_list: next_day = date + timedelta(days=1) @@ -487,7 +614,7 @@ class Sf_Dashboard_Connect(http.Controller): end_time_str = kw['end_time'].strip('"') begin_time = datetime.strptime(begin_time_str, '%Y-%m-%d %H:%M:%S') end_time = datetime.strptime(end_time_str, '%Y-%m-%d %H:%M:%S') - print('line_list: %s' % line_list) + # print('line_list: %s' % line_list) not_done_data = [] done_data = [] final_data = {} @@ -495,11 +622,16 @@ class Sf_Dashboard_Connect(http.Controller): for line in line_list: # 未完成订单 not_done_orders = plan_obj.search( - [('production_line_id.name', '=', line), ('state', 'not in', ['finished'])]) - print(not_done_orders) + [('production_line_id.name', '=', line), ('state', 'not in', ['finished']), + ('production_id.state', 'not in', ['cancel']), ('active', '=', True) + ]) + # print(not_done_orders) # 完成订单 - finish_orders = plan_obj.search([('production_line_id.name', '=', line), ('state', 'in', ['finished'])]) - print(finish_orders) + finish_orders = plan_obj.search([ + ('production_line_id.name', '=', line), ('state', 'in', ['finished']), + ('production_id.state', 'not in', ['cancel']), ('active', '=', True) + ]) + # print(finish_orders) # 获取所有未完成订单的ID列表 order_ids = [order.id for order in not_done_orders] @@ -622,11 +754,11 @@ class Sf_Dashboard_Connect(http.Controller): # 执行SQL命令 cur.execute(sql, (item,)) result = cur.fetchall() - print('result========', result) + # print('result========', result) cur.execute(sql2, (item,)) result2 = cur.fetchall() - print('result2========', result2) + # print('result2========', result2) # for row in result: res['data'][item] = {'idle_count': row[0]} @@ -682,7 +814,7 @@ class Sf_Dashboard_Connect(http.Controller): # 执行SQL命令 cur.execute(sql) result = cur.fetchall() - print('result', result) + # print('result', result) # 将查询结果转换为字典列表 data = [] @@ -830,3 +962,222 @@ class Sf_Dashboard_Connect(http.Controller): # 返回数据 res['data'] = oee_data return json.dumps(res) + + @http.route(['/equipment/get_image/'], type='http', auth="public", website=True) + def get_image(self, record_id, **kwargs): + # 获取模型中的记录 + record = request.env['maintenance.equipment'].sudo().browse(record_id) + + # 获取图片字段的数据 + image_data_base64 = record.machine_tool_picture + + if image_data_base64: + # 将Base64解码为二进制数据 + image_data_binary = base64.b64decode(image_data_base64) + + # 返回图片数据,并设置正确的Content-Type + return request.make_response(image_data_binary, headers=[('Content-Type', 'image/png')]) + else: + # 如果没有图片数据,返回404 + return request.not_found() + + # 设备运行率 + @http.route('/api/RunningTime', type='http', auth='public', methods=['GET', 'POST'], csrf=False, cors="*") + def RunningTime(self, **kw): + """ + 获取设备运行时长 + """ + res = {'status': 1, 'message': '成功', 'data': {}} + # 连接数据库 + conn = psycopg2.connect(**db_config) + # 获取请求的机床数据 + machine_list = ast.literal_eval(kw['machine_list']) + + def fetch_result_as_dict(cursor): + """辅助函数:将查询结果转为字典""" + columns = [desc[0] for desc in cursor.description] + return dict(zip(columns, cursor.fetchone())) if cursor.rowcount != 0 else None + + # 初始化当天、当月和有记录以来的总时长 + day_total_running_time = 0 + day_total_process_time = 0 + day_work_rate = 0 + month_total_running_time = 0 + month_total_process_time = 0 + month_work_rate = 0 + all_time_total_running_time = 0 + all_time_total_process_time = 0 + all_time_work_rate = 0 + + for item in machine_list: + # 获取当天第一条记录(排除device_state等于‘离线’的记录) + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND time::date = CURRENT_DATE + AND device_state != '离线' + ORDER BY time ASC + LIMIT 1; + """, (item,)) + first_today = fetch_result_as_dict(cur) + # print("当天第一条记录(非离线):", first_today) + + # 获取当天最新一条记录(排除device_state等于‘离线’的记录) + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND time::date = CURRENT_DATE + AND device_state != '离线' + ORDER BY time DESC + LIMIT 1; + """, (item,)) + last_today = fetch_result_as_dict(cur) + # print("当天最新一条记录(非离线):", last_today) + + # 计算当天运行时长 + if first_today and last_today: + running_time = convert_to_seconds(last_today['run_time']) - convert_to_seconds(first_today['run_time']) + process_time = convert_to_seconds(last_today['process_time']) - convert_to_seconds( + first_today['process_time']) + day_total_running_time += abs(running_time) + day_total_process_time += abs(process_time) + + # 获取当月第一条记录(排除device_state等于‘离线’的记录) + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND EXTRACT(YEAR FROM time) = EXTRACT(YEAR FROM CURRENT_DATE) + AND EXTRACT(MONTH FROM time) = EXTRACT(MONTH FROM CURRENT_DATE) + AND device_state != '离线' + ORDER BY time ASC + LIMIT 1; + """, (item,)) + first_month = fetch_result_as_dict(cur) + # print("当月第一条记录(非离线):", first_month) + + # 获取当月最新一条记录(排除device_state等于‘离线’的记录) + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND EXTRACT(YEAR FROM time) = EXTRACT(YEAR FROM CURRENT_DATE) + AND EXTRACT(MONTH FROM time) = EXTRACT(MONTH FROM CURRENT_DATE) + AND device_state != '离线' + ORDER BY time DESC + LIMIT 1; + """, (item,)) + last_month = fetch_result_as_dict(cur) + # print("当月最新一条记录(非离线):", last_month) + + # 计算当月运行时长 + if first_month and last_month: + month_running_time = convert_to_seconds(last_month['run_time']) - convert_to_seconds( + first_month['run_time']) + month_process_time = convert_to_seconds(last_month['process_time']) - convert_to_seconds( + first_month['process_time']) + month_total_running_time += abs(month_running_time) + month_total_process_time += abs(month_process_time) + + # 获取有记录以来的第一条记录(排除device_state等于‘离线’的记录) + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND device_state != '离线' + ORDER BY time ASC + LIMIT 1; + """, (item,)) + first_all_time = fetch_result_as_dict(cur) + # print("有记录以来的第一条记录(非离线):", first_all_time) + + # 获取有记录以来的最新一条记录(排除device_state等于‘离线’的记录) + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND device_state != '离线' + ORDER BY time DESC + LIMIT 1; + """, (item,)) + last_all_time = fetch_result_as_dict(cur) + # print("有记录以来的最新一条记录(非离线):", last_all_time) + + # 计算有记录以来的运行时长 + if first_all_time and last_all_time: + all_time_running_time = convert_to_seconds(last_all_time['run_time']) - convert_to_seconds( + first_all_time['run_time']) + all_time_process_time = convert_to_seconds(last_all_time['process_time']) - convert_to_seconds( + first_all_time['process_time']) + all_time_total_running_time += abs(all_time_running_time) + all_time_total_process_time += abs(all_time_process_time) + + # 计算当天工作效率 + if day_total_running_time > day_total_process_time: + day_work_rate = day_total_process_time / day_total_running_time if day_total_running_time != 0 else 0 + else: + day_work_rate = day_total_running_time / day_total_process_time if day_total_process_time != 0 else 0 + print("当天工作效率: %s" % day_work_rate) + + # 计算当月工作效率 + if month_total_running_time > month_total_process_time: + month_work_rate = month_total_process_time / month_total_running_time if month_total_running_time != 0 else 0 + else: + month_work_rate = month_total_running_time / month_total_process_time if month_total_process_time != 0 else 0 + print("当月工作效率: %s" % month_work_rate) + + # 计算有记录以来的工作效率 + if all_time_total_running_time > all_time_total_process_time: + all_time_work_rate = all_time_total_process_time / all_time_total_running_time if all_time_total_running_time != 0 else 0 + else: + all_time_work_rate = all_time_total_running_time / all_time_total_process_time if all_time_total_process_time != 0 else 0 + print("有记录以来的工作效率: %s" % all_time_work_rate) + + conn.close() + + # 返回数据 + res['data']['day_work_rate'] = day_work_rate + res['data']['month_work_rate'] = month_work_rate + res['data']['all_time_work_rate'] = all_time_work_rate + + return json.dumps(res) + + # 设备运行时长 + @http.route('/api/RunningTimeDetail', type='http', auth='public', methods=['GET', 'POST'], csrf=False, cors="*") + def RunningTimeDetail(self, **kw): + """ + 获取 + """ + res = {'status': 1, 'message': '成功', 'data': {}} + # 连接数据库 + conn = psycopg2.connect(**db_config) + # 获取请求的机床数据 + machine_list = ast.literal_eval(kw['machine_list']) + + def fetch_result_as_dict(cursor): + """辅助函数:将查询结果转为字典""" + columns = [desc[0] for desc in cursor.description] + return dict(zip(columns, cursor.fetchone())) if cursor.rowcount != 0 else None + + for item in machine_list: + with conn.cursor() as cur: + cur.execute(""" + SELECT * FROM device_data + WHERE device_name = %s + AND device_state != '离线' + ORDER BY time DESC + LIMIT 1; + """, (item,)) + last_all_time = fetch_result_as_dict(cur) + # 返回数据 + res['data'][item] = { + 'wait_time': last_all_time['run_time'] if last_all_time['run_time'] is not None else 0, + 'cut_time': last_all_time['process_time'] if last_all_time['process_time'] is not None else 0, + 'power_on_time': last_all_time['power_on_time'] if last_all_time['power_on_time'] is not None else 0 + } + + conn.close() + + return json.dumps(res) diff --git a/sf_machine_connect/models/res_config_setting.py b/sf_machine_connect/models/res_config_setting.py index c0bdf597..60862ccf 100644 --- a/sf_machine_connect/models/res_config_setting.py +++ b/sf_machine_connect/models/res_config_setting.py @@ -16,6 +16,7 @@ class ResBFMConfigSettings(models.TransientModel): # ("https://bfm.jikimo.com", "正式环境(https://bfm.jikimo.com)")], string='bfm环境', store=True) bfm_url_new = fields.Char('业务平台环境路径', placeholder='请输入当前对应的业务平台环境路径') + get_check_file_path = fields.Char('获取检查文件路径', default='') @api.model def get_values(self): @@ -26,9 +27,11 @@ class ResBFMConfigSettings(models.TransientModel): values = super(ResBFMConfigSettings, self).get_values() config = self.env['ir.config_parameter'].sudo() bfm_url_new = config.get_param('bfm_url_new', default='') + get_check_file_path = config.get_param('get_check_file_path', default='') values.update( bfm_url_new=bfm_url_new, + get_check_file_path=get_check_file_path ) return values @@ -36,3 +39,4 @@ class ResBFMConfigSettings(models.TransientModel): super(ResBFMConfigSettings, self).set_values() ir_config = self.env['ir.config_parameter'].sudo() ir_config.set_param("bfm_url_new", self.bfm_url_new or "") + ir_config.set_param("get_check_file_path", self.get_check_file_path or "") diff --git a/sf_machine_connect/views/res_config_settings_views.xml b/sf_machine_connect/views/res_config_settings_views.xml index 4ad5b0e7..fa3ba59c 100644 --- a/sf_machine_connect/views/res_config_settings_views.xml +++ b/sf_machine_connect/views/res_config_settings_views.xml @@ -18,6 +18,21 @@ + + + + +
+

获取检测报告服务配置

+
+
+
+
+
+
+
diff --git a/sf_manufacturing/__manifest__.py b/sf_manufacturing/__manifest__.py index b0556418..10c949f5 100644 --- a/sf_manufacturing/__manifest__.py +++ b/sf_manufacturing/__manifest__.py @@ -45,7 +45,6 @@ 'sf_manufacturing/static/src/scss/kanban_change.scss', 'sf_manufacturing/static/src/xml/button_show_on_tree.xml', 'sf_manufacturing/static/src/js/workpiece_delivery_wizard_confirm.js', - 'sf_manufacturing/static/src/js/custom_barcode_handlers.js', ] }, diff --git a/sf_manufacturing/models/agv_scheduling.py b/sf_manufacturing/models/agv_scheduling.py index 35b6b76d..9bd506d9 100644 --- a/sf_manufacturing/models/agv_scheduling.py +++ b/sf_manufacturing/models/agv_scheduling.py @@ -1,10 +1,10 @@ + +import logging import requests from odoo import models, fields, api, _ from odoo.exceptions import UserError -import logging - _logger = logging.getLogger(__name__) @@ -54,7 +54,7 @@ class AgvScheduling(models.Model): def web_search_read(self, domain=None, fields=None, offset=0, limit=None, order=None, count_limit=None): domain = domain or [] new_domain = [] - for index, item in enumerate(domain): + for item in domain: if isinstance(item, list): if item[0] == 'delivery_workpieces': new_domain.append('&') @@ -63,7 +63,7 @@ class AgvScheduling(models.Model): continue new_domain.append(item) - return super(AgvScheduling, self).web_search_read(new_domain, fields, limit=limit, offset=offset) + return super(AgvScheduling, self).web_search_read(new_domain, fields, offset, limit, order, count_limit) @api.depends('task_completion_time', 'task_delivery_time') def _compute_task_duration(self): diff --git a/sf_manufacturing/models/mrp_production.py b/sf_manufacturing/models/mrp_production.py index 063a67d8..c1cacb29 100644 --- a/sf_manufacturing/models/mrp_production.py +++ b/sf_manufacturing/models/mrp_production.py @@ -318,8 +318,10 @@ class MrpProduction(models.Model): # cnc程序获取 def fetchCNC(self, production_names): cnc = self.env['mrp.production'].search([('id', '=', self.id)]) - quick_order = self.env['quick.easy.order'].search( - [('name', '=', cnc.product_id.default_code.rsplit('-', 1)[0])]) + quick_order = False + if cnc.product_id.default_code: + quick_order = self.env['quick.easy.order'].search( + [('name', '=', cnc.product_id.default_code.rsplit('-', 1)[0])]) programme_way = False if cnc.manual_quotation is True: programme_way = 'manual operation' diff --git a/sf_manufacturing/models/mrp_workorder.py b/sf_manufacturing/models/mrp_workorder.py index 8b98e491..bc049c12 100644 --- a/sf_manufacturing/models/mrp_workorder.py +++ b/sf_manufacturing/models/mrp_workorder.py @@ -222,7 +222,7 @@ class ResMrpWorkOrder(models.Model): material_width = fields.Float(string='宽') material_height = fields.Float(string='高') # 零件图号 - part_number = fields.Char(string='零件图号') + part_number = fields.Char(related='production_id.part_number', string='零件图号') # 工序状态 process_state = fields.Selection([ ('待装夹', '待装夹'), @@ -414,12 +414,10 @@ class ResMrpWorkOrder(models.Model): # 获取三次元检测点数据 def get_three_check_datas(self): - factory_nick_name = 'XT' ftp_resconfig = self.env['res.config.settings'].get_values() ftp = FtpController(str(ftp_resconfig['ftp_host']), int(ftp_resconfig['ftp_port']), ftp_resconfig['ftp_user'], ftp_resconfig['ftp_password']) - # ftp.connect() local_dir_path = '/ftp/before' os.makedirs(local_dir_path, exist_ok=True) @@ -428,6 +426,17 @@ class ResMrpWorkOrder(models.Model): logging.info('local_file_path:%s' % local_file_path) remote_path = '/home/ftp/ftp_root/ThreeTest/XT/Before/' + local_filename logging.info('remote_path:%s' % remote_path) + if not ftp.file_exists(remote_path): + paload_data = { + "filename": local_filename + } + if not ftp_resconfig['get_check_file_path']: + raise UserError('请先配置获取检测报告地址') + url = ftp_resconfig['get_check_file_path'] + '/get/check/report' + response = requests.post(url, json=paload_data) + logging.info('response:%s' % response.json()) + if response.json().get('detail'): + raise UserError(response.json().get('detail')) if not ftp.file_exists(remote_path): raise UserError(f"文件不存在: {remote_path}") @@ -540,6 +549,7 @@ class ResMrpWorkOrder(models.Model): raise UserError('PT10点未测或数据错误') self.data_state = True + self.getcenter() return True @@ -1015,16 +1025,20 @@ class ResMrpWorkOrder(models.Model): # 查询工序最小的非完工、非返工的装夹预调工单 work_id = self.search( [('production_id', '=', workorder.production_id.id), - ('routing_type', '=', '装夹预调'), ('state', 'not in', ['rework', 'done', 'cancel'])], limit=1, order="sequence") - if workorder == work_id: - if workorder.production_id.reservation_state == 'assigned': - workorder.state = 'ready' - elif workorder.production_id.reservation_state != 'assigned': - workorder.state = 'waiting' - continue + if work_id.routing_type == '装夹预调': + if workorder == work_id: + if workorder.production_id.reservation_state == 'assigned': + workorder.state = 'ready' + elif workorder.production_id.reservation_state != 'assigned': + workorder.state = 'waiting' + continue + elif (workorder.name == '装夹预调' and + workorder.state not in ['rework', 'done', 'cancel']): + if workorder.state != 'pending': + workorder.state = 'pending' if workorder.production_id.tool_state in ['1', '2'] and workorder.state == 'ready': workorder.state = 'waiting' continue @@ -1169,7 +1183,7 @@ class ResMrpWorkOrder(models.Model): if not record.rfid_code and record.is_rework is False: raise UserError("请扫RFID码进行绑定") if record.is_rework is False: - if not record.material_center_point and record.X_deviation_angle > 0: + if not record.material_center_point or record.X_deviation_angle <= 0: raise UserError("坯料中心点为空或X偏差角度小于等于0") record.process_state = '待加工' # record.write({'process_state': '待加工'}) @@ -1328,6 +1342,7 @@ class ResMrpWorkOrder(models.Model): arch = etree.fromstring(tree_view['arch']) # 查找 tree 标签 tree_element = arch.xpath("//tree")[0] + tree_element.set('js_class', 'remove_focus_list_view') # 查找或创建 header 标签 header_element = tree_element.find('header') diff --git a/sf_manufacturing/models/stock.py b/sf_manufacturing/models/stock.py index e0c66076..1690b632 100644 --- a/sf_manufacturing/models/stock.py +++ b/sf_manufacturing/models/stock.py @@ -267,6 +267,11 @@ class StockRule(models.Model): workorder_duration += workorder.duration_expected sale_order = self.env['sale.order'].sudo().search([('name', '=', production.origin)]) + # 根据销售订单号查询快速订单 + quick_easy_order = self.env['quick.easy.order'].sudo().search([('sale_order_id', '=', sale_order.id)]) + if quick_easy_order: + production.write({'part_number': quick_easy_order.part_drawing_number, + 'part_drawing': quick_easy_order.machining_drawings}) if sale_order: # sale_order.write({'schedule_status': 'to schedule'}) self.env['sf.production.plan'].sudo().with_company(company_id).create({ @@ -288,6 +293,7 @@ class StockRule(models.Model): # 为同一个product_id创建一个生产订单名称列表 product_id_to_production_names[product_id] = [production.name for production in all_production] for production_item in productions: + production_programming = self.env['mrp.production'].search( [('product_id.id', '=', production_item.product_id.id), ('origin', '=', production_item.origin)], diff --git a/sf_manufacturing/views/mrp_workcenter_views.xml b/sf_manufacturing/views/mrp_workcenter_views.xml index 37ff8af5..5ba5290d 100644 --- a/sf_manufacturing/views/mrp_workcenter_views.xml +++ b/sf_manufacturing/views/mrp_workcenter_views.xml @@ -43,7 +43,7 @@
+
+ +

@@ -496,116 +508,77 @@ - - - - - + + + - + + + + - - + + + - + +
+ +
- - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + +
+
-
- - -
- -
- - - - - - - - -
- -
- -
- - - - - - - - - - -
-
- + attrs="{'invisible': [('integral_lot_id', '=', False),'|','|','|', ('blade_lot_id', '!=', False),('bar_lot_id', '!=', False),('pad_lot_id', '!=', False),('assemble_status', 'not in', ['0','01'])]}">
- - - - - - + + + + + + + + + + + -
-
- +
+
+ +
+
+ + +
+ +
+ @@ -614,10 +587,19 @@ + + + +
+
- +
@@ -630,9 +612,18 @@
+ + +
+
+
- +
@@ -645,30 +636,69 @@
+ + +
+
+
-
- - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -685,9 +715,27 @@ + + + + + + + + + + + + +
@@ -705,20 +753,19 @@ + + + - - - - - - - + + + @@ -743,7 +790,7 @@ tree,form,search - {'search_default_no_assemble_status':1} + {'search_default_no_assemble_status':[1,01]} @@ -844,7 +891,8 @@ - + diff --git a/sf_tool_management/wizard/jikimo_bom_wizard.py b/sf_tool_management/wizard/jikimo_bom_wizard.py index f86a7a09..ed6fe790 100644 --- a/sf_tool_management/wizard/jikimo_bom_wizard.py +++ b/sf_tool_management/wizard/jikimo_bom_wizard.py @@ -15,7 +15,6 @@ class JikimoBomWizard(models.TransientModel): ('刀柄+刀杆+刀片', '刀柄+刀杆+刀片'), ('刀柄+刀盘+刀片', '刀柄+刀盘+刀片') ], string='组装方式', required=True) - # assembly_options_ids = fields.Many2many('sf.cutting.tool.material', string="组装方式") is_ok = fields.Boolean('确认上述信息正确无误。') def submit(self): diff --git a/sf_tool_management/wizard/wizard.py b/sf_tool_management/wizard/wizard.py index aa5c645e..d1797855 100644 --- a/sf_tool_management/wizard/wizard.py +++ b/sf_tool_management/wizard/wizard.py @@ -598,361 +598,175 @@ class FunctionalToolAssemblyOrder(models.TransientModel): else: record.L_D_number = 0 - def functional_tool_assembly(self): - """ - 功能刀具组装 - :return: - """ - logging.info('功能刀具开始组装!') - # 获取组装单对象 - functional_tool_assembly = self.env['sf.functional.tool.assembly'].search([ - ('assembly_order_code', '=', self.assembly_order_code), - ('machine_tool_name_id', '=', self.machine_tool_name_id.id), - ('cutter_spacing_code_id', '=', self.cutter_spacing_code_id.id), - ('assemble_status', '=', '0'), - ]) - # 对物料做必填判断 - self.materials_must_be_judged() - - product_id = self.env['product.product'] - # 创建组装入库单 - # 创建功能刀具批次/序列号记录 - stock_lot = product_id.create_assemble_warehouse_receipt(self.id, functional_tool_assembly, self) - # 封装功能刀具数据,用于更新组装单信息 - desc_1 = self.get_desc_1(stock_lot) - # 封装功能刀具数据,用于创建功能刀具记录 - desc_2 = self.get_desc_2(stock_lot, functional_tool_assembly) - # 创建功能刀具组装入库单 - self.env['stock.picking'].create_tool_stocking_picking(stock_lot, functional_tool_assembly, self) - # 创建刀具物料出库单 - self.env['stock.picking'].create_tool_stocking_picking1(self) - - # ============================创建功能刀具列表、安全库存记录=============================== - # 创建功能刀具列表记录 - record_1 = self.env['sf.functional.cutting.tool.entity'].create(desc_2) - # 创建安全库存信息 - self.env['sf.real.time.distribution.of.functional.tools'].create_or_edit_safety_stock({ - 'functional_name_id': self.after_name_id.id - }, record_1) - - # =====================修改功能刀具组装单、机床换刀申请、CAM工单程序用刀计划的状态============== - # 修改功能刀具组装单信息 - functional_tool_assembly.write(desc_1) - if functional_tool_assembly.sf_machine_table_tool_changing_apply_id: - # 修改机床换刀申请的状态 - self.env['sf.machine.table.tool.changing.apply'].sudo().search([ - ('id', '=', functional_tool_assembly.sf_machine_table_tool_changing_apply_id.id) - ]).write({'status': '3'}) - elif functional_tool_assembly.sf_cam_work_order_program_knife_plan_id: - # 修改CAM工单程序用刀计划状态 - cam_plan = self.env['sf.cam.work.order.program.knife.plan'].sudo().search([ - ('id', '=', functional_tool_assembly.sf_cam_work_order_program_knife_plan_id.id) - ]) - cam_plan.write({'plan_execute_status': '2'}) - - logging.info('功能刀具组装完成!') - - # 关闭弹出窗口 - return {'type': 'ir.actions.act_window_close'} - - def materials_must_be_judged(self): - """ - 功能刀具组装必填判断 - """ - # 物料必填校验 - if not self.handle_code_id: - raise ValidationError('缺少【刀柄】物料信息!') - if not self.integral_product_id and not self.blade_product_id: - raise ValidationError('【整体式刀具】和【刀片】必须填写一个!') - if self.blade_product_id: - if not self.bar_product_id and not self.pad_product_id: - raise ValidationError('【刀盘】和【刀杆】必须填写一个!') - # 组装参数必填校验 - if self.after_assembly_functional_tool_length == 0: - raise ValidationError('组装参数信息【伸出长】不能为0!') - if self.after_assembly_max_lifetime_value == 0: - raise ValidationError('组装参数信息【最大寿命值】不能为0!') - if self.after_assembly_alarm_value == 0: - raise ValidationError('组装参数信息【报警值】不能为0!') - # if self.after_assembly_effective_length == 0: - # raise ValidationError('组装参数信息【有效长】不能为0!!!') - # if self.hiding_length == 0: - # raise ValidationError('组装参数信息【避空长】不能为0!!!') - if self.after_assembly_functional_tool_diameter == 0: - raise ValidationError('组装参数信息【刀具直径】不能为0!') - if self.after_assembly_tool_loading_length == 0: - raise ValidationError('组装参数信息【总长度】不能为0!!!') - if self.after_assembly_handle_length == 0: - raise ValidationError('组装参数信息【刀柄长度】不能为0!') - if self.after_assembly_tool_loading_length < self.after_assembly_handle_length: - raise ValidationError('组装参数信息【刀柄长度】不能大于【总长度】!') - - def get_desc_1(self, stock_lot): - return { - 'start_preset_bool': False, - 'barcode_id': stock_lot.id, - 'code': self.code, - 'rfid': self.rfid, - 'tool_groups_id': self.after_tool_groups_id.id, - 'handle_code_id': self.handle_code_id.id, - 'integral_freight_barcode_id': self.integral_freight_barcode_id.id, - 'integral_lot_id': self.integral_freight_lot_id.lot_id.id, - 'blade_freight_barcode_id': self.blade_freight_barcode_id.id, - 'blade_lot_id': self.blade_freight_lot_id.lot_id.id, - 'bar_freight_barcode_id': self.bar_freight_barcode_id.id, - 'bar_lot_id': self.bar_freight_lot_id.lot_id.id, - 'pad_freight_barcode_id': self.pad_freight_barcode_id.id, - 'pad_lot_id': self.pad_freight_lot_id.lot_id.id, - 'chuck_freight_barcode_id': self.chuck_freight_barcode_id.id, - 'chuck_lot_id': self.chuck_freight_lot_id.lot_id.id, - - 'after_assembly_functional_tool_name': self.after_assembly_functional_tool_name, - 'after_assembly_functional_tool_type_id': self.after_assembly_functional_tool_type_id.id, - 'after_assembly_functional_tool_diameter': self.after_assembly_functional_tool_diameter, - 'after_assembly_knife_tip_r_angle': self.after_assembly_knife_tip_r_angle, - 'after_assembly_new_former': self.after_assembly_new_former, - 'cut_time': self.cut_time, - 'cut_length': self.cut_length, - 'cut_number': self.cut_number, - 'after_assembly_whether_standard_knife': self.after_assembly_whether_standard_knife, - 'after_assembly_coarse_middle_thin': self.after_assembly_coarse_middle_thin, - 'after_assembly_max_lifetime_value': self.after_assembly_max_lifetime_value, - 'after_assembly_alarm_value': self.after_assembly_alarm_value, - 'after_assembly_used_value': self.after_assembly_used_value, - 'after_assembly_tool_loading_length': self.after_assembly_tool_loading_length, - 'after_assembly_handle_length': self.after_assembly_handle_length, - 'after_assembly_functional_tool_length': self.after_assembly_functional_tool_length, - 'after_assembly_effective_length': self.after_assembly_effective_length, - 'L_D_number': self.L_D_number, - 'hiding_length': self.hiding_length, - 'assemble_status': '1', - 'tool_loading_person': self.env.user.name, - 'image': self.image, - 'tool_loading_time': fields.Datetime.now() - } - - def get_desc_2(self, stock_lot, functional_tool_assembly_id): - return { - 'barcode_id': stock_lot.id, - 'code': self.code, - 'name': self.after_name_id.name, - 'tool_name_id': self.after_name_id.id, - 'rfid': self.rfid, - 'tool_groups_id': self.after_tool_groups_id.id, - 'functional_tool_name_id': functional_tool_assembly_id.id, - 'sf_cutting_tool_type_id': self.after_assembly_functional_tool_type_id.id, - 'cutting_tool_integral_model_id': self.integral_product_id.id, - 'cutting_tool_blade_model_id': self.blade_product_id.id, - 'cutting_tool_cutterbar_model_id': self.bar_product_id.id, - 'cutting_tool_cutterpad_model_id': self.pad_product_id.id, - 'cutting_tool_cutterhandle_model_id': self.handle_product_id.id, - 'cutting_tool_cutterhead_model_id': self.chuck_product_id.id, - - 'functional_tool_diameter': self.after_assembly_functional_tool_diameter, - 'knife_tip_r_angle': self.after_assembly_knife_tip_r_angle, - 'coarse_middle_thin': self.after_assembly_coarse_middle_thin, - 'new_former': self.after_assembly_new_former, - 'tool_loading_length': self.after_assembly_tool_loading_length, - 'handle_length': self.after_assembly_handle_length, - 'functional_tool_length': self.after_assembly_functional_tool_length, - 'effective_length': self.after_assembly_effective_length, - - 'max_lifetime_value': self.after_assembly_max_lifetime_value, - 'alarm_value': self.after_assembly_alarm_value, - 'used_value': self.after_assembly_used_value, - 'whether_standard_knife': self.after_assembly_whether_standard_knife, - 'L_D_number': self.L_D_number, - 'hiding_length': self.hiding_length, - 'cut_time': self.cut_time, - 'cut_length': self.cut_length, - 'cut_number': self.cut_number, - 'image': self.image, - } + # def functional_tool_assembly(self): + # """ + # 功能刀具组装 + # :return: + # """ + # logging.info('功能刀具开始组装!') + # # 获取组装单对象 + # functional_tool_assembly = self.env['sf.functional.tool.assembly'].search([ + # ('assembly_order_code', '=', self.assembly_order_code), + # ('machine_tool_name_id', '=', self.machine_tool_name_id.id), + # ('cutter_spacing_code_id', '=', self.cutter_spacing_code_id.id), + # ('assemble_status', '=', '0'), + # ]) + # # 对物料做必填判断 + # self.materials_must_be_judged() + # + # product_id = self.env['product.product'] + # # 创建组装入库单 + # # 创建功能刀具批次/序列号记录 + # stock_lot = product_id.create_assemble_warehouse_receipt(self.id, functional_tool_assembly, self) + # # 封装功能刀具数据,用于更新组装单信息 + # desc_1 = self.get_desc_1(stock_lot) + # # 封装功能刀具数据,用于创建功能刀具记录 + # desc_2 = self.get_desc_2(stock_lot, functional_tool_assembly) + # # 创建功能刀具组装入库单 + # self.env['stock.picking'].create_tool_stocking_picking(stock_lot, functional_tool_assembly, self) + # # 创建刀具物料出库单 + # self.env['stock.picking'].create_tool_stocking_picking1(self) + # + # # ============================创建功能刀具列表、安全库存记录=============================== + # # 创建功能刀具列表记录 + # record_1 = self.env['sf.functional.cutting.tool.entity'].create(desc_2) + # # 创建安全库存信息 + # self.env['sf.real.time.distribution.of.functional.tools'].create_or_edit_safety_stock({ + # 'functional_name_id': self.after_name_id.id + # }, record_1) + # + # # =====================修改功能刀具组装单、机床换刀申请、CAM工单程序用刀计划的状态============== + # # 修改功能刀具组装单信息 + # functional_tool_assembly.write(desc_1) + # if functional_tool_assembly.sf_machine_table_tool_changing_apply_id: + # # 修改机床换刀申请的状态 + # self.env['sf.machine.table.tool.changing.apply'].sudo().search([ + # ('id', '=', functional_tool_assembly.sf_machine_table_tool_changing_apply_id.id) + # ]).write({'status': '3'}) + # elif functional_tool_assembly.sf_cam_work_order_program_knife_plan_id: + # # 修改CAM工单程序用刀计划状态 + # cam_plan = self.env['sf.cam.work.order.program.knife.plan'].sudo().search([ + # ('id', '=', functional_tool_assembly.sf_cam_work_order_program_knife_plan_id.id) + # ]) + # cam_plan.write({'plan_execute_status': '2'}) + # + # logging.info('功能刀具组装完成!') + # + # # 关闭弹出窗口 + # return {'type': 'ir.actions.act_window_close'} + # + # def materials_must_be_judged(self): + # """ + # 功能刀具组装必填判断 + # """ + # # 物料必填校验 + # if not self.handle_code_id: + # raise ValidationError('缺少【刀柄】物料信息!') + # if not self.integral_product_id and not self.blade_product_id: + # raise ValidationError('【整体式刀具】和【刀片】必须填写一个!') + # if self.blade_product_id: + # if not self.bar_product_id and not self.pad_product_id: + # raise ValidationError('【刀盘】和【刀杆】必须填写一个!') + # # 组装参数必填校验 + # if self.after_assembly_functional_tool_length == 0: + # raise ValidationError('组装参数信息【伸出长】不能为0!') + # if self.after_assembly_max_lifetime_value == 0: + # raise ValidationError('组装参数信息【最大寿命值】不能为0!') + # if self.after_assembly_alarm_value == 0: + # raise ValidationError('组装参数信息【报警值】不能为0!') + # # if self.after_assembly_effective_length == 0: + # # raise ValidationError('组装参数信息【有效长】不能为0!!!') + # # if self.hiding_length == 0: + # # raise ValidationError('组装参数信息【避空长】不能为0!!!') + # if self.after_assembly_functional_tool_diameter == 0: + # raise ValidationError('组装参数信息【刀具直径】不能为0!') + # if self.after_assembly_tool_loading_length == 0: + # raise ValidationError('组装参数信息【总长度】不能为0!!!') + # if self.after_assembly_handle_length == 0: + # raise ValidationError('组装参数信息【刀柄长度】不能为0!') + # if self.after_assembly_tool_loading_length < self.after_assembly_handle_length: + # raise ValidationError('组装参数信息【刀柄长度】不能大于【总长度】!') + # + # def get_desc_1(self, stock_lot): + # return { + # 'start_preset_bool': False, + # 'barcode_id': stock_lot.id, + # 'code': self.code, + # 'rfid': self.rfid, + # 'tool_groups_id': self.after_tool_groups_id.id, + # 'handle_code_id': self.handle_code_id.id, + # 'integral_freight_barcode_id': self.integral_freight_barcode_id.id, + # 'integral_lot_id': self.integral_freight_lot_id.lot_id.id, + # 'blade_freight_barcode_id': self.blade_freight_barcode_id.id, + # 'blade_lot_id': self.blade_freight_lot_id.lot_id.id, + # 'bar_freight_barcode_id': self.bar_freight_barcode_id.id, + # 'bar_lot_id': self.bar_freight_lot_id.lot_id.id, + # 'pad_freight_barcode_id': self.pad_freight_barcode_id.id, + # 'pad_lot_id': self.pad_freight_lot_id.lot_id.id, + # 'chuck_freight_barcode_id': self.chuck_freight_barcode_id.id, + # 'chuck_lot_id': self.chuck_freight_lot_id.lot_id.id, + # + # 'after_assembly_functional_tool_name': self.after_assembly_functional_tool_name, + # 'after_assembly_functional_tool_type_id': self.after_assembly_functional_tool_type_id.id, + # 'after_assembly_functional_tool_diameter': self.after_assembly_functional_tool_diameter, + # 'after_assembly_knife_tip_r_angle': self.after_assembly_knife_tip_r_angle, + # 'after_assembly_new_former': self.after_assembly_new_former, + # 'cut_time': self.cut_time, + # 'cut_length': self.cut_length, + # 'cut_number': self.cut_number, + # 'after_assembly_whether_standard_knife': self.after_assembly_whether_standard_knife, + # 'after_assembly_coarse_middle_thin': self.after_assembly_coarse_middle_thin, + # 'after_assembly_max_lifetime_value': self.after_assembly_max_lifetime_value, + # 'after_assembly_alarm_value': self.after_assembly_alarm_value, + # 'after_assembly_used_value': self.after_assembly_used_value, + # 'after_assembly_tool_loading_length': self.after_assembly_tool_loading_length, + # 'after_assembly_handle_length': self.after_assembly_handle_length, + # 'after_assembly_functional_tool_length': self.after_assembly_functional_tool_length, + # 'after_assembly_effective_length': self.after_assembly_effective_length, + # 'L_D_number': self.L_D_number, + # 'hiding_length': self.hiding_length, + # 'assemble_status': '1', + # 'tool_loading_person': self.env.user.name, + # 'image': self.image, + # 'tool_loading_time': fields.Datetime.now() + # } + # + # def get_desc_2(self, stock_lot, functional_tool_assembly_id): + # return { + # 'barcode_id': stock_lot.id, + # 'code': self.code, + # 'name': self.after_name_id.name, + # 'tool_name_id': self.after_name_id.id, + # 'rfid': self.rfid, + # 'tool_groups_id': self.after_tool_groups_id.id, + # 'functional_tool_name_id': functional_tool_assembly_id.id, + # 'sf_cutting_tool_type_id': self.after_assembly_functional_tool_type_id.id, + # 'cutting_tool_integral_model_id': self.integral_product_id.id, + # 'cutting_tool_blade_model_id': self.blade_product_id.id, + # 'cutting_tool_cutterbar_model_id': self.bar_product_id.id, + # 'cutting_tool_cutterpad_model_id': self.pad_product_id.id, + # 'cutting_tool_cutterhandle_model_id': self.handle_product_id.id, + # 'cutting_tool_cutterhead_model_id': self.chuck_product_id.id, + # + # 'functional_tool_diameter': self.after_assembly_functional_tool_diameter, + # 'knife_tip_r_angle': self.after_assembly_knife_tip_r_angle, + # 'coarse_middle_thin': self.after_assembly_coarse_middle_thin, + # 'new_former': self.after_assembly_new_former, + # 'tool_loading_length': self.after_assembly_tool_loading_length, + # 'handle_length': self.after_assembly_handle_length, + # 'functional_tool_length': self.after_assembly_functional_tool_length, + # 'effective_length': self.after_assembly_effective_length, + # + # 'max_lifetime_value': self.after_assembly_max_lifetime_value, + # 'alarm_value': self.after_assembly_alarm_value, + # 'used_value': self.after_assembly_used_value, + # 'whether_standard_knife': self.after_assembly_whether_standard_knife, + # 'L_D_number': self.L_D_number, + # 'hiding_length': self.hiding_length, + # 'cut_time': self.cut_time, + # 'cut_length': self.cut_length, + # 'cut_number': self.cut_number, + # 'image': self.image, + # } -class StockPicking(models.Model): - _inherit = 'stock.picking' - - def create_tool_stocking_picking(self, stock_lot, functional_tool_assembly, obj): - """ - 创建功能刀具组装入库单 - """ - # 获取名称为刀具组装入库的作业类型 - picking_type_id = self.env['stock.picking.type'].sudo().search([('name', '=', '刀具组装入库')]) - # 创建刀具组装入库单 - picking_id = self.env['stock.picking'].create({ - 'name': self._get_name_stock(picking_type_id), - 'picking_type_id': picking_type_id.id, - 'location_id': picking_type_id.default_location_src_id.id, - 'location_dest_id': picking_type_id.default_location_dest_id.id, - 'origin': obj.assembly_order_code - }) - # 创建作业详情对象记录,并绑定到刀具组装入库单 - self.env['stock.move.line'].create({ - 'picking_id': picking_id.id, - 'product_id': stock_lot.product_id.id, - 'location_id': picking_id.location_id.id, - 'location_dest_id': picking_id.location_dest_id.id, - 'lot_id': stock_lot.id, - 'install_tool_time': fields.Datetime.now(), - 'qty_done': 1, - 'functional_tool_name_id': functional_tool_assembly.id, - 'functional_tool_type_id': obj.functional_tool_type_id.id, - 'diameter': obj.after_assembly_functional_tool_diameter, - 'knife_tip_r_angle': obj.after_assembly_knife_tip_r_angle, - 'code': obj.code, - 'rfid': obj.rfid, - 'functional_tool_name': obj.after_assembly_functional_tool_name, - 'tool_groups_id': obj.after_tool_groups_id.id - }) - # 将刀具组装入库单的状态更改为就绪 - picking_id.action_confirm() - picking_id.button_validate() - - def _get_name_stock(self, picking_type_id): - name = picking_type_id.sequence_id.prefix + str( - datetime.strptime(str(fields.Date.today()), "%Y-%m-%d").strftime("%Y%m%d")) - stock_id = self.env['stock.picking'].sudo().search( - [('name', 'like', name), ('picking_type_id', '=', picking_type_id.id)], - limit=1, - order="id desc" - ) - if not stock_id: - num = "%03d" % 1 - else: - m = int(stock_id.name[-3:]) + 1 - num = "%03d" % m - return name + str(num) - - def create_tool_stocking_picking1(self, obj): - """ - 创建刀具物料出库单 - """ - # 获取名称为内部调拨的作业类型 - picking_type_id = self.env['stock.picking.type'].sudo().search([('name', '=', '内部调拨')]) - # 创建刀具物料出库单 - picking_id = self.env['stock.picking'].create({ - 'name': self._get_name_stock1(picking_type_id), - 'picking_type_id': picking_type_id.id, - 'location_id': self.env['stock.location'].search([('name', '=', '刀具房')]).id, - 'location_dest_id': self.env['stock.location'].search([('name', '=', '刀具组装位置')]).id, - 'origin': obj.assembly_order_code - }) - # =============刀具物料出库=================== - stock_move_id = self.env['stock.move'] - datas = {'data': [], 'picking_id': picking_id} - if obj.handle_code_id: - # 修改刀柄序列号状态为【在用】 - obj.handle_code_id.sudo().write({'tool_material_status': '在用'}) - datas['data'].append( - {'current_location_id': self.env['sf.shelf.location'], 'lot_id': obj.handle_code_id}) - if obj.integral_product_id: - datas['data'].append( - {'current_location_id': obj.integral_freight_barcode_id, 'lot_id': obj.integral_freight_lot_id.lot_id}) - if obj.blade_product_id: - datas['data'].append( - {'current_location_id': obj.blade_freight_barcode_id, 'lot_id': obj.blade_freight_lot_id.lot_id}) - if obj.bar_product_id: - datas['data'].append( - {'current_location_id': obj.bar_freight_barcode_id, 'lot_id': obj.bar_freight_lot_id.lot_id}) - if obj.pad_product_id: - datas['data'].append( - {'current_location_id': obj.pad_freight_barcode_id, 'lot_id': obj.pad_freight_lot_id.lot_id}) - if obj.chuck_product_id: - datas['data'].append( - {'current_location_id': obj.chuck_freight_barcode_id, 'lot_id': obj.chuck_freight_lot_id.lot_id}) - # 创建刀具物料出库库存移动记录 - stock_move_id.create_tool_material_stock_moves(datas) - # 将刀具物料出库库单的状态更改为就绪 - picking_id.action_confirm() - # 修改刀具物料出库移动历史记录 - stock_move_id.write_tool_material_stock_move_lines(datas) - # 设置数量,并验证完成 - picking_id.action_set_quantities_to_reservation() - picking_id.button_validate() - logging.info(f'刀具物料调拨单状态:{picking_id.state}') - - def _get_name_stock1(self, picking_type_id): - name = f'{picking_type_id.sequence_id.prefix}DJ/{date.today().strftime("%y")}' - stock_id = self.env['stock.picking'].sudo().search( - [('name', 'like', name), ('picking_type_id', '=', picking_type_id.id)], - limit=1, - order="id desc" - ) - if not stock_id: - num = "%05d" % 1 - else: - m = int(stock_id.name[-5:]) + 1 - num = "%05d" % m - return name + str(num) - - -class StockMove(models.Model): - _inherit = 'stock.move' - - def create_tool_material_stock_moves(self, datas): - picking_id = datas['picking_id'] - data = datas['data'] - stock_move_ids = [] - for res in data: - if res: - # 创建库存移动记录 - stock_move_id = self.env['stock.move'].sudo().create({ - 'name': picking_id.name, - 'picking_id': picking_id.id, - 'product_id': res['lot_id'].product_id.id, - 'location_id': picking_id.location_id.id, - 'location_dest_id': picking_id.location_dest_id.id, - 'product_uom_qty': 1.00, - 'reserved_availability': 1.00 - }) - stock_move_ids.append(stock_move_id) - return stock_move_ids - - def write_tool_material_stock_move_lines(self, datas): - picking_id = datas['picking_id'] - data = datas['data'] - move_line_ids = picking_id.move_line_ids - for move_line_id in move_line_ids: - for res in data: - if move_line_id.lot_id.product_id == res['lot_id'].product_id: - move_line_id.write({ - 'current_location_id': res.get('current_location_id').id, - 'lot_id': res.get('lot_id').id - }) - return True - - -class ProductProduct(models.Model): - _inherit = 'product.product' - - def create_assemble_warehouse_receipt(self, tool_assembly_order_id, functional_tool_assembly, obj): - """ - 创建功能刀具批次/序列号记录 - """ - product_id = self.env['product.product'].search([('categ_type', '=', '功能刀具'), ('tracking', '=', 'serial')]) - if not product_id: - logging.info('没有搜索到功能刀具产品:%s' % product_id) - raise ValidationError('没有找到按唯一序列号追溯的功能刀具产品信息!') - stock_lot = self.env['stock.lot'].create({ - 'name': self.get_stock_lot_name(obj), - 'product_id': product_id[0].id, - 'company_id': self.env.company.id - }) - return stock_lot - - def get_stock_lot_name(self, obj): - """ - 生成功能刀具序列号 - """ - company = obj.cutting_tool_cutterhandle_model_id.code.split('-', 1)[0] - new_time = datetime.strptime(str(fields.Date.today()), "%Y-%m-%d").strftime("%Y%m%d") - code = '%s-GNDJ-%s-%s' % (company, obj.after_assembly_functional_tool_type_id.code, new_time) - stock_lot_id = self.env['stock.lot'].sudo().search( - [('name', 'like', code)], limit=1, order="id desc") - if not stock_lot_id: - num = "%03d" % 1 - else: - m = int(stock_lot_id.name[-3:]) + 1 - num = "%03d" % m - return '%s-%s' % (code, num) diff --git a/sf_tool_management/wizard/wizard_view.xml b/sf_tool_management/wizard/wizard_view.xml index b5c2f82e..53a45d85 100644 --- a/sf_tool_management/wizard/wizard_view.xml +++ b/sf_tool_management/wizard/wizard_view.xml @@ -427,10 +427,10 @@