Compare commits

..

12 Commits

Author SHA1 Message Date
陈赓
344b79d76b bom追溯方式 2025-07-16 09:12:31 +08:00
陈赓
556b9fdfbf 修改bom追溯方式 2025-07-15 16:48:19 +08:00
陈赓
8e8f5eb8be feat: 新增 Redis 缓存同步相关模块与控制器 2025-07-15 11:29:18 +08:00
陈赓
cdbc277a94 feat: 新增 Redis 工具与控制器,更新同步逻辑相关文件 2025-07-15 11:28:12 +08:00
李晓斌
7fca59322e Accept Merge Request #2285: (feature/7253 -> develop)
Merge Request: BUG_7276_lxb_commit

Created By: @李晓斌
Reviewed By: @胡尧
Approved By: @胡尧 
Accepted By: @李晓斌
URL: https://jikimo-hn.coding.net/p/jikimo_sfs/d/jikimo_sf/git/merge/2285
2025-07-15 09:42:48 +08:00
lixiaobin@jikimo.com
42694c1ac6 BUG_7276_lxb_commit 2025-07-15 09:39:50 +08:00
管欢
e88fc012ec Accept Merge Request #2284: (feature/物料需求计划管理 -> develop)
Merge Request: 校验修改

Created By: @管欢
Reviewed By: @胡尧
Approved By: @胡尧 
Accepted By: @管欢
URL: https://jikimo-hn.coding.net/p/jikimo_sfs/d/jikimo_sf/git/merge/2284
2025-07-14 16:16:20 +08:00
guanhuan
ff7cd9c927 校验修改 2025-07-14 16:13:49 +08:00
guanhuan
588b7d340f Merge branch 'refs/heads/develop' into feature/物料需求计划管理 2025-07-14 15:52:10 +08:00
guanhuan
5902d61f13 新增单件用量显示 2025-07-14 15:39:37 +08:00
陈烨
8cfad007b9 Accept Merge Request #2283: (feature/7249 -> develop)
Merge Request: 合并 develop 分支到 feature/7249

Created By: @陈烨
Reviewed By: @胡尧
Approved By: @胡尧 
Accepted By: @陈烨
URL: https://jikimo-hn.coding.net/p/jikimo_sfs/d/jikimo_sf/git/merge/2283
2025-07-14 14:29:24 +08:00
guanhuan
0441f345ef 新增单件用量显示 2025-07-14 14:11:28 +08:00
10 changed files with 496 additions and 265 deletions

View File

@@ -4,4 +4,4 @@ wechatpy==1.8.18
pycryptodome==3.22.0 pycryptodome==3.22.0
openupgradelib==3.10.0 openupgradelib==3.10.0
opcua==0.98.13 opcua==0.98.13
openpyxl openpyxl

View File

@@ -10,7 +10,7 @@
""", """,
'category': 'sf', 'category': 'sf',
'website': 'https://www.sf.jikimo.com', 'website': 'https://www.sf.jikimo.com',
'depends': ['sf_plan','jikimo_printing'], 'depends': ['sf_plan'], #'jikimo_printing',
'data': [ 'data': [
'security/ir.model.access.csv', 'security/ir.model.access.csv',
'data/stock_route_group.xml', 'data/stock_route_group.xml',

View File

@@ -38,7 +38,7 @@ class SfDemandPlan(models.Model):
related='product_id.blank_type') related='product_id.blank_type')
blank_precision = fields.Selection([('精坯', '精坯'), ('粗坯', '粗坯')], string='坯料类型', blank_precision = fields.Selection([('精坯', '精坯'), ('粗坯', '粗坯')], string='坯料类型',
related='product_id.blank_precision') related='product_id.blank_precision')
manual_quotation = fields.Boolean('人工编程',related='product_id.manual_quotation', default=False) manual_quotation = fields.Boolean('人工编程', related='product_id.manual_quotation', default=False)
embryo_long = fields.Char('坯料尺寸(mm)', compute='_compute_embryo_long', store=True) embryo_long = fields.Char('坯料尺寸(mm)', compute='_compute_embryo_long', store=True)
is_incoming_material = fields.Boolean('客供料', related='sale_order_line_id.is_incoming_material', store=True) is_incoming_material = fields.Boolean('客供料', related='sale_order_line_id.is_incoming_material', store=True)
pending_qty = fields.Float( pending_qty = fields.Float(
@@ -222,15 +222,12 @@ class SfDemandPlan(models.Model):
line_ids = self.line_ids.filtered(lambda p: p.status == '30') line_ids = self.line_ids.filtered(lambda p: p.status == '30')
sum_product_uom_qty = sum(line_ids.mapped('plan_uom_qty')) sum_product_uom_qty = sum(line_ids.mapped('plan_uom_qty'))
customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers') customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers')
for line in self.line_ids:
if line.manual_quotation and line.custom_made_type == 'automation':
raise ValidationError(f"产品{line.product_id.name}为人工编程,不能选择自动化产线加工")
if not self.overdelivery_allowed and line_ids.filtered(lambda p: p.location_id.id == customer_location_id): if not self.overdelivery_allowed and line_ids.filtered(lambda p: p.location_id.id == customer_location_id):
if float_compare(sum_product_uom_qty, self.product_uom_qty, if float_compare(sum_product_uom_qty, self.product_uom_qty,
precision_rounding=self.product_id.uom_id.rounding) == 1: precision_rounding=self.product_id.uom_id.rounding) == 1:
raise ValidationError(f"已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。") raise ValidationError(f"已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。")
elif float_compare(sum_product_uom_qty, self.product_uom_qty, elif float_compare(sum_product_uom_qty, self.product_uom_qty,
precision_rounding=self.product_id.uom_id.rounding) == 1: precision_rounding=self.product_id.uom_id.rounding) == 1:
return { return {
'name': _('需求计划'), 'name': _('需求计划'),
'type': 'ir.actions.act_window', 'type': 'ir.actions.act_window',
@@ -246,11 +243,12 @@ class SfDemandPlan(models.Model):
else: else:
for demand_plan_line_id in line_ids: for demand_plan_line_id in line_ids:
demand_plan_line_id.action_confirm() demand_plan_line_id.action_confirm()
#需求要求取值格式是来源+来源明细行ID,但是来源明细行ID取得就是product_id.name得最后一位所以这里也直接截取product_id.name
# 需求要求取值格式是来源+来源明细行ID,但是来源明细行ID取得就是product_id.name得最后一位所以这里也直接截取product_id.name
@api.depends('product_id.name') @api.depends('product_id.name')
def _compute_demand_plan_number(self): def _compute_demand_plan_number(self):
for line in self: for line in self:
product_name = line.product_id.name or '' product_name = line.product_id.name or ''
plan_no = None plan_no = None
if line.product_id: if line.product_id:
# 使用正则表达式匹配P-后面的所有字符 # 使用正则表达式匹配P-后面的所有字符
@@ -259,4 +257,4 @@ class SfDemandPlan(models.Model):
plan_no = match.group(1) plan_no = match.group(1)
line.demand_plan_number = plan_no line.demand_plan_number = plan_no
else: else:
line.demand_plan_number = None line.demand_plan_number = None

View File

@@ -7,7 +7,29 @@ from odoo.tools import float_compare
from datetime import datetime, timedelta from datetime import datetime, timedelta
from odoo.exceptions import UserError from odoo.exceptions import UserError
import re import re
#本地环境问题 不加报错
class ProductCategory(models.Model):
_inherit = 'product.category'
negative_inventory_allowed = fields.Boolean(string="允许负库存", default=False)
class StockPicking(models.Model):
_inherit = 'stock.picking'
whether_show_quality_check = fields.Boolean(string="是否显示质检")
class ProductTemplate(models.Model):
_inherit = 'product.template'
blank_type = fields.Selection([
('圆料', '圆料'),
('方料', '方料'),
], string='坯料分类')
blank_precision = fields.Selection([
('精坯', '精坯'),
('粗坯', '粗坯'),
], string='坯料类型')
class SfProductionDemandPlan(models.Model): class SfProductionDemandPlan(models.Model):
_name = 'sf.production.demand.plan' _name = 'sf.production.demand.plan'
@@ -81,6 +103,7 @@ class SfProductionDemandPlan(models.Model):
related='product_id.blank_type') related='product_id.blank_type')
blank_precision = fields.Selection([('精坯', '精坯'), ('粗坯', '粗坯')], string='坯料类型', blank_precision = fields.Selection([('精坯', '精坯'), ('粗坯', '粗坯')], string='坯料类型',
related='product_id.blank_precision') related='product_id.blank_precision')
unit_number = fields.Float('单件用量', digits=(16, 3), related='product_id.unit_number')
embryo_long = fields.Char('坯料尺寸(mm)', related='demand_plan_id.embryo_long') embryo_long = fields.Char('坯料尺寸(mm)', related='demand_plan_id.embryo_long')
materials_id = fields.Char('材料', related='demand_plan_id.materials_id') materials_id = fields.Char('材料', related='demand_plan_id.materials_id')
model_machining_precision = fields.Selection(related='product_id.model_machining_precision', string='精度') model_machining_precision = fields.Selection(related='product_id.model_machining_precision', string='精度')
@@ -169,22 +192,30 @@ class SfProductionDemandPlan(models.Model):
finished_product_arrival_date = fields.Date('采购计划到货(成品)') finished_product_arrival_date = fields.Date('采购计划到货(成品)')
bom_id = fields.Many2one('mrp.bom', string="BOM", readonly=True) bom_id = fields.Many2one('mrp.bom', string="BOM", readonly=True)
location_id = fields.Many2one('stock.location', string='需求位置', default=get_location_id, readonly=True) location_id = fields.Many2one('stock.location', string='需求位置', default=get_location_id, readonly=True)
manual_quotation = fields.Boolean('人工编程',related='product_id.manual_quotation',default=False) manual_quotation = fields.Boolean('人工编程', related='product_id.manual_quotation', default=False)
@api.constrains('plan_uom_qty') @api.constrains('plan_uom_qty')
def _check_plan_uom_qty(self): def _check_plan_uom_qty(self):
line_ids = self.filtered(lambda p: p.plan_uom_qty == 0 or p.plan_uom_qty < 0) line_ids = self.filtered(lambda p: p.plan_uom_qty == 0 or p.plan_uom_qty < 0)
if line_ids: if line_ids:
raise ValidationError(_("计划量不能小于等于0")) raise ValidationError(_("计划量不能小于等于0"))
@api.constrains('new_supply_method') @api.constrains('supply_method')
def _check_new_supply_method(self): def _check_supply_method(self):
product_name = [] product_name = []
product = []
for line in self: for line in self:
if line.new_supply_method == 'purchase' and line.is_incoming_material: if line.supply_method == 'purchase' and line.is_incoming_material:
product_name.append(line.product_id.display_name) product_name.append(line.product_id.display_name)
if line.supply_method == 'automation' and line.manual_quotation:
product.append(line.product_id.display_name)
if product_name: if product_name:
unique_product_names = list(set(product_name)) unique_product_names = list(set(product_name))
raise UserError('当前(%s)产品为客供料,不能选择外购' % ','.join(unique_product_names)) raise UserError('当前(%s)产品为客供料,不能选择外购' % ','.join(unique_product_names))
if product:
unique_product = list(set(product))
raise UserError('当前(%s)产品为人工编程,不能选择自动化产线加工' % ','.join(unique_product))
@api.depends('new_supply_method') @api.depends('new_supply_method')
def _compute_custom_made_type(self): def _compute_custom_made_type(self):
@@ -346,7 +377,8 @@ class SfProductionDemandPlan(models.Model):
def update_sale_order_state(self): def update_sale_order_state(self):
# demand_plan = self.env['sf.demand.plan'].sudo().search([('sale_order_id', '=', self.sale_order_id.id)]) # demand_plan = self.env['sf.demand.plan'].sudo().search([('sale_order_id', '=', self.sale_order_id.id)])
# demand_plan_state = demand_plan.filtered(lambda line: line.state != '40') # demand_plan_state = demand_plan.filtered(lambda line: line.state != '40')
production_demand_plan = self.env['sf.production.demand.plan'].sudo().search([('sale_order_id', '=', self.sale_order_id.id)]) production_demand_plan = self.env['sf.production.demand.plan'].sudo().search(
[('sale_order_id', '=', self.sale_order_id.id)])
production_demand_plan_state = production_demand_plan.filtered(lambda line: line.status in ('10', '20', '30')) production_demand_plan_state = production_demand_plan.filtered(lambda line: line.status in ('10', '20', '30'))
if not production_demand_plan_state: if not production_demand_plan_state:
# 修改销售订单为加工中 # 修改销售订单为加工中
@@ -605,6 +637,11 @@ class SfProductionDemandPlan(models.Model):
# 按产品分组并计算总数 # 按产品分组并计算总数
product_data = {} product_data = {}
for plan in filtered_plan: for plan in filtered_plan:
check_overdelivery_allowed = False
if not plan.demand_plan_id.overdelivery_allowed:
customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers')
if plan.location_id.id == customer_location_id:
check_overdelivery_allowed = True
if plan.product_id not in product_data: if plan.product_id not in product_data:
# 初始化产品数据,从产品上获取需求量 # 初始化产品数据,从产品上获取需求量
product_data[plan.product_id] = { product_data[plan.product_id] = {
@@ -614,17 +651,22 @@ class SfProductionDemandPlan(models.Model):
# 累加计划数量 # 累加计划数量
product_data[plan.product_id]['plan_uom_qty'] += plan.plan_uom_qty product_data[plan.product_id]['plan_uom_qty'] += plan.plan_uom_qty
product_data[plan.product_id]['overdelivery_allowed'] = check_overdelivery_allowed
# 检查需求超过计划数量的产品 # 检查需求超过计划数量的产品
warning_messages = [] warning_messages = []
error_messages = []
for product, data in product_data.items(): for product, data in product_data.items():
if float_compare(data['plan_uom_qty'], data['product_uom_qty'], if data['overdelivery_allowed'] and float_compare(data['plan_uom_qty'], data['product_uom_qty'],precision_rounding=product.uom_id.rounding) == 1:
precision_rounding=product.uom_id.rounding) == 1: error_messages.append(f"您正在下达的产品 {product.display_name},已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。")
elif float_compare(data['plan_uom_qty'], data['product_uom_qty'],
precision_rounding=product.uom_id.rounding) == 1:
warning_messages.append( warning_messages.append(
_("您正在下达的产品 %s,计划量%s,需求数量为%s,已超过需求数量") % _("您正在下达的产品 %s,计划量%s,需求数量为%s,已超过需求数量") %
(product.display_name, data['plan_uom_qty'], data['product_uom_qty']) (product.display_name, data['plan_uom_qty'], data['product_uom_qty'])
) )
if warning_messages and check_overdelivery_allowed: if error_messages:
raise ValidationError(f"已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。") error_message = "\n".join(error_messages)
raise ValidationError(error_message)
elif warning_messages: elif warning_messages:
warning_message = "\n".join(warning_messages) warning_message = "\n".join(warning_messages)
return { return {
@@ -642,19 +684,17 @@ class SfProductionDemandPlan(models.Model):
def button_release_plan(self): def button_release_plan(self):
self.ensure_one() self.ensure_one()
if not self.new_supply_method:
raise ValidationError(f"供货方式不能为空!")
if self.product_id.manual_quotation and self.custom_made_type == 'automation':
raise ValidationError(f"产品{self.product_id.name}为人工编程,不能选择自动化产线加工")
check_overdelivery_allowed = False check_overdelivery_allowed = False
if not self.demand_plan_id.overdelivery_allowed: if not self.demand_plan_id.overdelivery_allowed:
customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers') customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers')
if self.location_id.id == customer_location_id: if self.location_id.id == customer_location_id:
check_overdelivery_allowed = True check_overdelivery_allowed = True
if check_overdelivery_allowed: if check_overdelivery_allowed:
if float_compare(self.plan_uom_qty, self.product_uom_qty,precision_rounding=self.product_id.uom_id.rounding) == 1: if float_compare(self.plan_uom_qty, self.product_uom_qty,
precision_rounding=self.product_id.uom_id.rounding) == 1:
raise ValidationError(f"已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。") raise ValidationError(f"已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。")
elif float_compare(self.plan_uom_qty, self.product_uom_qty,precision_rounding=self.product_id.uom_id.rounding) == 1: elif float_compare(self.plan_uom_qty, self.product_uom_qty,
precision_rounding=self.product_id.uom_id.rounding) == 1:
return { return {
'name': _('需求计划'), 'name': _('需求计划'),
'type': 'ir.actions.act_window', 'type': 'ir.actions.act_window',
@@ -670,19 +710,49 @@ class SfProductionDemandPlan(models.Model):
self.action_confirm() self.action_confirm()
def action_confirm(self): def action_confirm(self):
self = self.with_context( """
demand_plan_line_id=self.id 确认需求计划行,创建 BOM、触发库存规则并更新状态。
) """
# 将当前需求计划行 ID 写入上下文,便于后续方法使用
self = self.with_context(demand_plan_line_id=self.id)
# 创建物料清单BOM根据供货方式进行不同的处理
self.mrp_bom_create() self.mrp_bom_create()
# 启动库存规则(创建采购、生产等)
self._action_launch_stock_rule() self._action_launch_stock_rule()
# 根据供货方式设置状态字段
if self.supply_method in ('automation', 'manual'): if self.supply_method in ('automation', 'manual'):
self.write({'status': '50'}) self.write({'status': '50'}) # 自动/手工 供货:待排产
self.update_sale_order_state() self.update_sale_order_state()
else: else:
self.write({'status': '60'}) self.write({'status': '60'}) # 外购/外协/客户自供:无需排产
self.update_sale_order_state() self.update_sale_order_state()
def _get_embryo_template_by_supply_method(self):
"""
根据供货方式返回对应的胚料模板 product.template 记录。
"""
supply_map = {
'automation': self.env.ref('sf_dlm.product_embryo_sf_self_machining').sudo(),
'outsourcing': self.env.ref('sf_dlm.product_embryo_sf_outsource').sudo(),
'purchase': self.env.ref('sf_dlm.product_embryo_sf_purchase').sudo(),
'manual': self.env.ref('jikimo_sale_multiple_supply_methods.product_template_manual_processing').sudo(),
'material_customer_provided': self.env.ref('jikimo_sale_multiple_supply_methods.product_template_embryo_customer_provided').sudo(),
}
template = supply_map.get(self.supply_method)
if not template:
raise UserError(f"未配置供货方式 {self.supply_method} 对应的胚料模板")
return template
def mrp_bom_create(self): def mrp_bom_create(self):
"""
创建 BOM包含胚料与成品 BOM用于后续生产或采购流程。
"""
# 如果同一计划中已有对应的 BOM 可复用,则直接使用
if self.supply_method in ('automation', 'manual'): if self.supply_method in ('automation', 'manual'):
line_ids = self.demand_plan_id.line_ids.filtered( line_ids = self.demand_plan_id.line_ids.filtered(
lambda p: p.supply_method in ('automation', 'manual') and p.status in ('50', '60')) lambda p: p.supply_method in ('automation', 'manual') and p.status in ('50', '60'))
@@ -695,32 +765,32 @@ class SfProductionDemandPlan(models.Model):
if line_ids: if line_ids:
self.bom_id = line_ids[0].bom_id.id self.bom_id = line_ids[0].bom_id.id
return return
# 根据供货方式选择模板和 BOM 类型
bom_type = '' bom_type = ''
# 根据供货方式修改成品模板
if self.supply_method == 'automation': if self.supply_method == 'automation':
bom_type = 'normal' bom_type = 'normal'
product_template_id = self.env.ref('sf_dlm.product_template_sf').sudo().product_tmpl_id product_template_id = self.env.ref('sf_dlm.product_template_sf').sudo().product_tmpl_id
elif self.supply_method == 'outsourcing': elif self.supply_method == 'outsourcing':
bom_type = 'subcontract' bom_type = 'subcontract'
product_template_id = self.env.ref( product_template_id = self.env.ref('jikimo_sale_multiple_supply_methods.product_template_outsourcing').sudo()
'jikimo_sale_multiple_supply_methods.product_template_outsourcing').sudo()
elif self.supply_method == 'purchase': elif self.supply_method == 'purchase':
product_template_id = self.env.ref( product_template_id = self.env.ref('jikimo_sale_multiple_supply_methods.product_template_purchase').sudo()
'jikimo_sale_multiple_supply_methods.product_template_purchase').sudo()
elif self.supply_method == 'manual': elif self.supply_method == 'manual':
bom_type = 'normal' bom_type = 'normal'
product_template_id = self.env.ref( product_template_id = self.env.ref('jikimo_sale_multiple_supply_methods.product_template_manual_processing').sudo()
'jikimo_sale_multiple_supply_methods.product_template_manual_processing').sudo()
# 复制成品模板上的属性 # 使用模板复制内容到当前产品
self.product_id.product_tmpl_id.copy_template(product_template_id) self.product_id.product_tmpl_id.copy_template(product_template_id)
# 构造 BOM 编码(包含时间戳)
future_time = datetime.now() + timedelta(hours=8) future_time = datetime.now() + timedelta(hours=8)
# 生成BOM单据编码
code = f"{self.product_id.default_code}-{bom_type}-{future_time.strftime('%Y%m%d%H%M%S')}" code = f"{self.product_id.default_code}-{bom_type}-{future_time.strftime('%Y%m%d%H%M%S')}"
order_id = self.sale_order_id order_id = self.sale_order_id
product = self.product_id product = self.product_id
# 拼接方法需要的item结构成品的模型数据信息就是坯料的数据信息
# 构造胚料产品的参数
item = { item = {
'texture_code': product.materials_id.materials_no, 'texture_code': product.materials_id.materials_no,
'texture_type_code': product.materials_type_id.materials_no, 'texture_type_code': product.materials_type_id.materials_no,
@@ -733,110 +803,81 @@ class SfProductionDemandPlan(models.Model):
'embryo_redundancy_id': self.sale_order_line_id.embryo_redundancy_id, 'embryo_redundancy_id': self.sale_order_line_id.embryo_redundancy_id,
'model_id': self.model_id 'model_id': self.model_id
} }
# 从产品名中提取编号(如 S12345-3
product_name = '' product_name = ''
match = re.search(r'(S\d{5}-\d+)', product.name) match = re.search(r'(S\d{5}-\d+)', product.name)
product_seria = 0 product_seria = 0
# 如果匹配成功,提取结果
if match: if match:
product_name = match.group(0) product_name = match.group(0)
# 获取成品名结尾-n的n
product_seria = int(product_name.split('-')[-1]) product_seria = int(product_name.split('-')[-1])
# 成品供货方式为采购则不生成bom # 如果供货方式不是采购,则需要先创建胚料产品
if self.supply_method != 'purchase': if self.supply_method != 'purchase':
# 当成品上带有客供料选项时,生成坯料时选择“客供料”路线 # 判断是否为客户自供
if self.sale_order_line_id.embryo_redundancy_id: if self.sale_order_line_id.embryo_redundancy_id:
# 将成品模板的内容复制到成品上 embryo_template = self.env.ref('jikimo_sale_multiple_supply_methods.product_template_embryo_customer_provided').sudo()
customer_provided_embryo = self.env.ref( embryo_key = 'material_customer_provided'
'jikimo_sale_multiple_supply_methods.product_template_embryo_customer_provided').sudo() else:
# 创建坯料客供料的批量不需要创建bom embryo_template = self._get_embryo_template_by_supply_method()
material_customer_provided_embryo = self.env['product.template'].sudo().no_bom_product_create( embryo_key = self.supply_method
customer_provided_embryo.with_context(active_test=False).product_variant_id,
item, # 获取批次追踪方式
order_id, 'material_customer_provided', product_seria, product) tracking_method = embryo_template.tracking
# 成品配置bom
product_bom_material_customer_provided = self.env['mrp.bom'].with_user( # 创建胚料产品(无 BOM 产品)
self.env.ref("base.user_admin")).bom_create( embryo_product = self.env['product.template'].sudo().no_bom_product_create(
product, bom_type, 'product', code) embryo_template.with_context(active_test=False).product_variant_id,
product_bom_material_customer_provided.with_user( item,
self.env.ref("base.user_admin")).bom_create_line_has( order_id,
material_customer_provided_embryo) embryo_key,
self.bom_id = product_bom_material_customer_provided.id product_seria,
elif self.product_id.materials_type_id.gain_way == '自加工': product
self_machining_id = self.env.ref('sf_dlm.product_embryo_sf_self_machining').sudo() )
# 创建坯料
self_machining_embryo = self.env['product.template'].sudo().no_bom_product_create( if embryo_product == -3:
self_machining_id, raise UserError('该订单模型的材料型号暂未设置获取方式和供应商,请先配置再进行分配')
item,
order_id, 'self_machining', product_seria, product) # 设置胚料 BOM 类型
# 创建坯料的bom if embryo_key in ('automation', 'manual', 'material_customer_provided'):
self_machining_bom = self.env['mrp.bom'].with_user( embryo_bom_type = 'normal'
self.env.ref("base.user_admin")).bom_create( elif embryo_key == 'outsourcing':
self_machining_embryo, 'normal', False) embryo_bom_type = 'subcontract'
# 创建坯料里bom的组件 elif embryo_key == 'purchase':
self_machining_bom_line = self_machining_bom.with_user( embryo_bom_type = 'purchase'
self.env.ref("base.user_admin")).bom_create_line( else:
self_machining_embryo) embryo_bom_type = 'normal'
if not self_machining_bom_line:
raise UserError('该订单模型的材料型号暂未有原材料,请先配置再进行分配') # 创建胚料 BOM 及 BOM 行
# 产品配置bom embryo_bom = self.env['mrp.bom'].with_user(self.env.ref("base.user_admin")).bom_create(
product_bom_self_machining = self.env['mrp.bom'].with_user( embryo_product, embryo_bom_type, True, tracking=tracking_method)
self.env.ref("base.user_admin")).bom_create(
product, bom_type, 'product', code) embryo_bom_line = embryo_bom.with_user(self.env.ref("base.user_admin")).bom_create_line(embryo_product)
product_bom_self_machining.with_user(self.env.ref("base.user_admin")).bom_create_line_has( if not embryo_bom_line:
self_machining_embryo) raise UserError('该订单模型的材料型号暂未有原材料,请先配置再进行分配')
self.bom_id = product_bom_self_machining.id
elif self.product_id.materials_type_id.gain_way == '外协': # 创建成品 BOM包含胚料
outsource_id = self.env.ref('sf_dlm.product_embryo_sf_outsource').sudo() product_bom = self.env['mrp.bom'].with_user(self.env.ref("base.user_admin")).bom_create(
# 创建坯料 product, bom_type, 'product', code, tracking=tracking_method)
outsource_embryo = self.env['product.template'].sudo().no_bom_product_create(outsource_id, product_bom.with_user(self.env.ref("base.user_admin")).bom_create_line_has(embryo_product)
item,
order_id, # 赋值 BOM ID
'subcontract', self.bom_id = product_bom.id
product_seria,
product)
if outsource_embryo == -3:
raise UserError('该订单模型的材料型号暂未设置获取方式和供应商,请先配置再进行分配')
# 创建坯料的bom
outsource_bom = self.env['mrp.bom'].with_user(self.env.ref("base.user_admin")).bom_create(
outsource_embryo,
'subcontract', True)
# 创建坯料的bom的组件
outsource_bom_line = outsource_bom.with_user(
self.env.ref("base.user_admin")).bom_create_line(outsource_embryo)
if not outsource_bom_line:
raise UserError('该订单模型的材料型号暂未有原材料,请先配置再进行分配')
# 产品配置bom
product_bom_outsource = self.env['mrp.bom'].with_user(
self.env.ref("base.user_admin")).bom_create(product, bom_type, 'product', code)
product_bom_outsource.with_user(self.env.ref("base.user_admin")).bom_create_line_has(
outsource_embryo)
self.bom_id = product_bom_outsource.id
elif self.product_id.materials_type_id.gain_way == '采购':
purchase_id = self.env.ref('sf_dlm.product_embryo_sf_purchase').sudo()
purchase_embryo = self.env['product.template'].sudo().no_bom_product_create(purchase_id,
item,
order_id,
'purchase',
product_seria,
product)
if purchase_embryo and purchase_embryo == -3:
raise UserError('该订单模型的材料型号暂未设置获取方式和供应商,请先配置再进行分配')
else:
# 产品配置bom
product_bom_purchase = self.env['mrp.bom'].with_user(
self.env.ref("base.user_admin")).bom_create(product, bom_type, 'product', code)
product_bom_purchase.with_user(self.env.ref("base.user_admin")).bom_create_line_has(
purchase_embryo)
self.bom_id = product_bom_purchase.id
def _action_launch_stock_rule(self): def _action_launch_stock_rule(self):
"""
触发库存规则(如采购、生产),并确认相关拣货单。
"""
procurements = [] procurements = []
group_id = self.sale_order_id.procurement_group_id group_id = self.sale_order_id.procurement_group_id
if not group_id: if not group_id:
# 没有分组则创建
group_id = self.env['procurement.group'].create(self._prepare_procurement_group_vals()) group_id = self.env['procurement.group'].create(self._prepare_procurement_group_vals())
self.sale_order_id.procurement_group_id = group_id self.sale_order_id.procurement_group_id = group_id
else: else:
# 若已有分组但字段有变动则更新
updated_vals = {} updated_vals = {}
if group_id.partner_id != self.sale_order_id.partner_shipping_id: if group_id.partner_id != self.sale_order_id.partner_shipping_id:
updated_vals.update({'partner_id': self.sale_order_id.partner_shipping_id.id}) updated_vals.update({'partner_id': self.sale_order_id.partner_shipping_id.id})
@@ -844,27 +885,42 @@ class SfProductionDemandPlan(models.Model):
updated_vals.update({'move_type': self.sale_order_id.picking_policy}) updated_vals.update({'move_type': self.sale_order_id.picking_policy})
if updated_vals: if updated_vals:
group_id.write(updated_vals) group_id.write(updated_vals)
# 构造 procurement 所需的字段
values = self._prepare_procurement_values(group_id=group_id) values = self._prepare_procurement_values(group_id=group_id)
# 单位换算
line_uom = self.sale_order_line_id.product_uom line_uom = self.sale_order_line_id.product_uom
quant_uom = self.product_id.uom_id quant_uom = self.product_id.uom_id
plan_uom_qty, procurement_uom = line_uom._adjust_uom_quantities(self.plan_uom_qty, quant_uom) plan_uom_qty, procurement_uom = line_uom._adjust_uom_quantities(self.plan_uom_qty, quant_uom)
# 创建 procurement 请求
procurements.append(self.env['procurement.group'].Procurement( procurements.append(self.env['procurement.group'].Procurement(
self.product_id, plan_uom_qty, procurement_uom, self.product_id, plan_uom_qty, procurement_uom,
self.sale_order_id.partner_shipping_id.property_stock_customer, self.sale_order_id.partner_shipping_id.property_stock_customer,
self.product_id.display_name, self.sale_order_id.name, self.sale_order_id.company_id, values)) self.product_id.display_name, self.sale_order_id.name, self.sale_order_id.company_id, values))
# 执行调度
if procurements: if procurements:
procurement_group = self.env['procurement.group'] procurement_group = self.env['procurement.group']
if self.env.context.get('import_file'): if self.env.context.get('import_file'):
procurement_group = procurement_group.with_context(import_file=False) procurement_group = procurement_group.with_context(import_file=False)
procurement_group.run(procurements) procurement_group.run(procurements)
# 确认相关的拣货单
orders = self.mapped('sale_order_id') orders = self.mapped('sale_order_id')
for order in orders: for order in orders:
pickings_to_confirm = order.picking_ids.filtered(lambda p: p.state not in ['cancel', 'done']) pickings_to_confirm = order.picking_ids.filtered(lambda p: p.state not in ['cancel', 'done'])
if pickings_to_confirm: if pickings_to_confirm:
pickings_to_confirm.action_confirm() pickings_to_confirm.action_confirm()
return True return True
def _prepare_procurement_group_vals(self): def _prepare_procurement_group_vals(self):
"""
构造创建 procurement group 所需的字段。
"""
return { return {
'name': self.sale_order_id.name, 'name': self.sale_order_id.name,
'move_type': self.sale_order_id.picking_policy, 'move_type': self.sale_order_id.picking_policy,
@@ -872,11 +928,18 @@ class SfProductionDemandPlan(models.Model):
'partner_id': self.sale_order_id.partner_shipping_id.id, 'partner_id': self.sale_order_id.partner_shipping_id.id,
} }
def _prepare_procurement_values(self, group_id=False): def _prepare_procurement_values(self, group_id=False):
"""
构造单个 procurement 请求所需的字段字典。
"""
self.ensure_one() self.ensure_one()
# 交货日期与计划日期
date_deadline = self.sale_order_id.commitment_date or ( date_deadline = self.sale_order_id.commitment_date or (
self.sale_order_id.date_order + timedelta(days=self.sale_order_line_id.customer_lead or 0.0)) self.sale_order_id.date_order + timedelta(days=self.sale_order_line_id.customer_lead or 0.0))
date_planned = date_deadline - timedelta(days=self.sale_order_id.company_id.security_lead) date_planned = date_deadline - timedelta(days=self.sale_order_id.company_id.security_lead)
values = { values = {
'group_id': group_id, 'group_id': group_id,
'sale_line_id': self.sale_order_line_id.id, 'sale_line_id': self.sale_order_line_id.id,
@@ -892,4 +955,6 @@ class SfProductionDemandPlan(models.Model):
'sequence': self.sale_order_line_id.sequence, 'sequence': self.sale_order_line_id.sequence,
'demand_plan_line_id': self.id 'demand_plan_line_id': self.id
} }
return values return values

View File

@@ -39,6 +39,7 @@
<field name="blank_type" optional="hide"/> <field name="blank_type" optional="hide"/>
<field name="blank_precision"/> <field name="blank_precision"/>
<field name="embryo_long"/> <field name="embryo_long"/>
<field name="unit_number" optional="hide"/>
<field name="materials_id"/> <field name="materials_id"/>
<field name="model_machining_precision"/> <field name="model_machining_precision"/>
<field name="model_process_parameters_ids" widget="many2many_tags"/> <field name="model_process_parameters_ids" widget="many2many_tags"/>

View File

@@ -1 +1,2 @@
from . import controllers from . import controllers
from . import sync_controller

View File

@@ -0,0 +1,22 @@
# study/jikimo_sf/sf_mrs_connect/controllers/sync_controller.py
from odoo import http
from odoo.http import request
class FixtureSyncController(http.Controller):
@http.route('/api/fixture_model/sync_from_mrs', type='json', auth='none', csrf=False)
def sync_model(self, **kw):
code = kw.get('code')
if not code:
return {'status':'fail','msg':'code missing'}
request.env['sf.fixture.model'].sudo().sync_from_mrs(code)
return {'status':'success'}
@http.route('/api/fixture_param/sync_from_mrs', type='json', auth='none', csrf=False)
def sync_param(self, **kw):
code = kw.get('code')
if not code:
return {'status':'fail','msg':'code missing'}
request.env['sf.fixture.materials.basic.parameters']\
.sudo().sync_from_mrs(code)
return {'status':'success'}

View File

@@ -0,0 +1,14 @@
# study/jikimo_sf/sf_mrs_connect/models/common.py
import time, hashlib
class Common:
@staticmethod
def get_headers(token, secret_key):
ts = str(int(time.time()))
sign = hashlib.sha256(f"{token}{secret_key}{ts}".encode()).hexdigest()
return {
"token": token,
"sign": sign,
"timestamp": ts,
"Content-Type": "application/json",
}

View File

@@ -0,0 +1,30 @@
# study/jikimo_sf/sf_mrs_connect/models/redis_utils.py
import redis, json, logging
_logger = logging.getLogger(__name__)
class RedisClient:
def __init__(self, host='localhost', port=6379, db=0):
try:
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
except Exception as e:
_logger.error(f"Redis init error: {e}")
self.client = None
def get_json(self, key):
if not self.client:
return None
try:
data = self.client.get(key)
return json.loads(data) if data else None
except Exception as e:
_logger.error(f"Redis GET error [{key}]: {e}")
return None
def set_json(self, key, value, ex=3600):
if not self.client:
return
try:
self.client.set(key, json.dumps(value, ensure_ascii=False), ex=ex)
except Exception as e:
_logger.error(f"Redis SET error [{key}]: {e}")

View File

@@ -5,9 +5,11 @@ import base64
import traceback import traceback
import requests import requests
from odoo import models from odoo import models,api,fields
from odoo.exceptions import ValidationError from odoo.exceptions import ValidationError
from odoo.addons.sf_base.commons.common import Common from .redis_utils import RedisClient
from .common import Common
from odoo.addons.jikimo_sf.sf_base.commons.common import Common
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@@ -1506,149 +1508,157 @@ class SyncMulti_Mounting_Type(models.Model):
raise ValidationError("联装类型认证未通过") raise ValidationError("联装类型认证未通过")
class SyncFixtureModel(models.Model): # class SyncFixtureModel(models.Model):
_inherit = 'sf.fixture.model' # _inherit = 'sf.fixture.model'
_description = '同步夹具型号列表' # _description = '同步夹具型号列表'
url = '/api/fixture_model/list' # url = '/api/fixture_model/list'
# 定时同步夹具型号列表 # # 定时同步夹具型号列表
def sync_fixture_model_yesterday(self): # def sync_fixture_model_yesterday(self):
config = self.env['res.config.settings'].get_values() # config = self.env['res.config.settings'].get_values()
headers = Common.get_headers(self, config['token'], config['sf_secret_key']) # headers = Common.get_headers(self, config['token'], config['sf_secret_key'])
strUrl = config['sf_url'] + self.url # strUrl = config['sf_url'] + self.url
r = requests.post(strUrl, json={}, data=None, headers=headers) # r = requests.post(strUrl, json={}, data=None, headers=headers)
r = r.json() # r = r.json()
result = json.loads(r['result']) # result = json.loads(r['result'])
if result['status'] == 1: # if result['status'] == 1:
if result.get('fixture_model_yesterday_list'): # if result.get('fixture_model_yesterday_list'):
for item in result['fixture_model_yesterday_list']: # for item in result['fixture_model_yesterday_list']:
if item: # if item:
fixture_model = self.search([("code", '=', item['code']), ('active', 'in', [True, False])]) # fixture_model = self.search([("code", '=', item['code']), ('active', 'in', [True, False])])
val = { # val = {
"name": item['name'], # "name": item['name'],
"code": item['code'], # "code": item['code'],
"fixture_material_id": self.env['sf.fixture.material'].search( # "fixture_material_id": self.env['sf.fixture.material'].search(
[('code', '=', item['fixture_material_code'])]).id, # [('code', '=', item['fixture_material_code'])]).id,
"multi_mounting_type_id": self.env['sf.multi_mounting.type'].search( # "multi_mounting_type_id": self.env['sf.multi_mounting.type'].search(
[('code', '=', item['multi_mounting_type_code'])]).id, # [('code', '=', item['multi_mounting_type_code'])]).id,
"brand_id": self.env['sf.machine.brand'].search([('code', '=', item['brand_code'])]).id, # "brand_id": self.env['sf.machine.brand'].search([('code', '=', item['brand_code'])]).id,
"model_file": '' if not item['model_file'] else base64.b64decode(item['model_file']), # "model_file": '' if not item['model_file'] else base64.b64decode(item['model_file']),
"status": item['status'], # "status": item['status'],
"active": item['active'], # "active": item['active'],
} # }
if not fixture_model: # if not fixture_model:
self.create(val) # self.create(val)
else: # else:
fixture_model.write(val) # fixture_model.write(val)
else: # else:
raise ValidationError("夹具型号认证未通过") # raise ValidationError("夹具型号认证未通过")
# 定时同步所有夹具型号列表 # # 定时同步所有夹具型号列表
def sync_all_fixture_model(self): # def sync_all_fixture_model(self):
config = self.env['res.config.settings'].get_values() # config = self.env['res.config.settings'].get_values()
headers = Common.get_headers(self, config['token'], config['sf_secret_key']) # headers = Common.get_headers(self, config['token'], config['sf_secret_key'])
strUrl = config['sf_url'] + self.url # strUrl = config['sf_url'] + self.url
r = requests.post(strUrl, json={}, data=None, headers=headers) # r = requests.post(strUrl, json={}, data=None, headers=headers)
r = r.json() # r = r.json()
result = json.loads(r['result']) # result = json.loads(r['result'])
# print('result:%s' % result) # # print('result:%s' % result)
if result['status'] == 1: # if result['status'] == 1:
if result.get('fixture_model_all_list'): # if result.get('fixture_model_all_list'):
for item in result['fixture_model_all_list']: # for item in result['fixture_model_all_list']:
if item: # if item:
fixture_model = self.search([('code', '=', item['code']), ('active', 'in', [True, False])]) # fixture_model = self.search([('code', '=', item['code']), ('active', 'in', [True, False])])
val = { # val = {
"name": item['name'], # "name": item['name'],
"code": item['code'], # "code": item['code'],
"fixture_material_id": self.env['sf.fixture.material'].search( # "fixture_material_id": self.env['sf.fixture.material'].search(
[('code', '=', item['fixture_material_code'])]).id, # [('code', '=', item['fixture_material_code'])]).id,
"multi_mounting_type_id": self.env['sf.multi_mounting.type'].search( # "multi_mounting_type_id": self.env['sf.multi_mounting.type'].search(
[('code', '=', item['multi_mounting_type_code'])]).id, # [('code', '=', item['multi_mounting_type_code'])]).id,
"brand_id": self.env['sf.machine.brand'].search([('code', '=', item['brand_code'])]).id, # "brand_id": self.env['sf.machine.brand'].search([('code', '=', item['brand_code'])]).id,
"model_file": '' if not item['model_file'] else base64.b64decode(item['model_file']), # "model_file": '' if not item['model_file'] else base64.b64decode(item['model_file']),
"status": item['status'], # "status": item['status'],
"active": item['active'], # "active": item['active'],
} # }
if not fixture_model: # if not fixture_model:
self.create(val) # self.create(val)
else: # else:
fixture_model.write(val) # fixture_model.write(val)
else: # else:
raise ValidationError("夹具型号认证未通过") # raise ValidationError("夹具型号认证未通过")
class SyncfixtureMaterialsBasicParameters(models.Model): # class SyncfixtureMaterialsBasicParameters(models.Model):
_inherit = 'sf.fixture.materials.basic.parameters' # _inherit = 'sf.fixture.materials.basic.parameters'
_description = '同步夹具型号基本参数列表' # _description = '同步夹具型号基本参数列表'
url = '/api/fixture_parameters/list' # url = '/api/fixture_parameters/list'
# 定时同步夹具型号基本信息 # # 定时同步夹具型号基本信息
def sync_fixture_materials_basic_parameters_yesterday(self): # def sync_fixture_materials_basic_parameters_yesterday(self):
config = self.env['res.config.settings'].get_values() # config = self.env['res.config.settings'].get_values()
headers = Common.get_headers(self, config['token'], config['sf_secret_key']) # headers = Common.get_headers(self, config['token'], config['sf_secret_key'])
strUrl = config['sf_url'] + self.url # strUrl = config['sf_url'] + self.url
r = requests.post(strUrl, json={}, data=None, headers=headers) # r = requests.post(strUrl, json={}, data=None, headers=headers)
r = r.json() # r = r.json()
result = json.loads(r['result']) # result = json.loads(r['result'])
if result['status'] == 1: # if result['status'] == 1:
if result.get('fixture_parameters_yesterday_list'): # if result.get('fixture_parameters_yesterday_list'):
all_list = result.get('fixture_parameters_yesterday_list') # all_list = result.get('fixture_parameters_yesterday_list')
if all_list.get('zero_chuck_all_list'): # if all_list.get('zero_chuck_all_list'):
self._write_or_create(all_list.get('zero_chuck_yesterday_list'), '零点卡盘') # self._write_or_create(all_list.get('zero_chuck_yesterday_list'), '零点卡盘')
if all_list.get('zero_tray_all_list'): # if all_list.get('zero_tray_all_list'):
self._write_or_create(all_list.get('zero_tray_yesterday_list'), '零点托盘') # self._write_or_create(all_list.get('zero_tray_yesterday_list'), '零点托盘')
if all_list.get('pneumatic_fixture_all_list'): # if all_list.get('pneumatic_fixture_all_list'):
self._write_or_create(all_list.get('pneumatic_fixture_yesterday_list'), '气动夹具') # self._write_or_create(all_list.get('pneumatic_fixture_yesterday_list'), '气动夹具')
if all_list.get('jaw_vice_all_list'): # if all_list.get('jaw_vice_all_list'):
self._write_or_create(all_list.get('jaw_vice_yesterday_list'), '虎钳夹具') # self._write_or_create(all_list.get('jaw_vice_yesterday_list'), '虎钳夹具')
if all_list.get('magnet_fixture_all_list'): # if all_list.get('magnet_fixture_all_list'):
self._write_or_create(all_list.get('magnet_fixture_yesterday_list'), '磁吸夹具') # self._write_or_create(all_list.get('magnet_fixture_yesterday_list'), '磁吸夹具')
if all_list.get('adapter_board_all_list'): # if all_list.get('adapter_board_all_list'):
self._write_or_create(all_list.get('adapter_board_yesterday_list'), '转接板(锁板)夹具') # self._write_or_create(all_list.get('adapter_board_yesterday_list'), '转接板(锁板)夹具')
if all_list.get('scroll_chuck_all_list'): # if all_list.get('scroll_chuck_all_list'):
self._write_or_create(all_list.get('scroll_chuck_yesterday_list'), '三爪卡盘') # self._write_or_create(all_list.get('scroll_chuck_yesterday_list'), '三爪卡盘')
else: # if all_list.get('air_tray_all_list'):
raise ValidationError("夹具型号基本参数认证未通过") # self._write_or_create(all_list.get('air_tray_all_list'),'气吹托盘')
# if all_list.get('magnet_tray_all_list'):
# self._write_or_create(all_list.get('magnet_tray_all_list'),'磁吸托盘')
# else:
# raise ValidationError("夹具型号基本参数认证未通过")
# 定时同步所有夹具型号基本信息 # # 定时同步所有夹具型号基本信息
def sync_all_fixture_materials_basic_parameters(self): # def sync_all_fixture_materials_basic_parameters(self):
config = self.env['res.config.settings'].get_values() # config = self.env['res.config.settings'].get_values()
headers = Common.get_headers(self, config['token'], config['sf_secret_key']) # headers = Common.get_headers(self, config['token'], config['sf_secret_key'])
strUrl = config['sf_url'] + self.url # strUrl = config['sf_url'] + self.url
r = requests.post(strUrl, json={}, data=None, headers=headers) # r = requests.post(strUrl, json={}, data=None, headers=headers)
r = r.json() # r = r.json()
result = json.loads(r['result']) # result = json.loads(r['result'])
if result['status'] == 1: # if result['status'] == 1:
if result.get('fixture_parameters_all_list'): # if result.get('fixture_parameters_all_list'):
all_list = result.get('fixture_parameters_all_list') # all_list = result.get('fixture_parameters_all_list')
if all_list.get('zero_chuck_all_list'): # if all_list.get('zero_chuck_all_list'):
self._write_or_create(all_list.get('zero_chuck_all_list'), '零点卡盘') # self._write_or_create(all_list.get('zero_chuck_all_list'), '零点卡盘')
if all_list.get('zero_tray_all_list'): # if all_list.get('zero_tray_all_list'):
self._write_or_create(all_list.get('zero_tray_all_list'), '零点托盘') # self._write_or_create(all_list.get('zero_tray_all_list'), '零点托盘')
if all_list.get('pneumatic_fixture_all_list'): # if all_list.get('pneumatic_fixture_all_list'):
self._write_or_create(all_list.get('pneumatic_fixture_all_list'), '气动夹具') # self._write_or_create(all_list.get('pneumatic_fixture_all_list'), '气动夹具')
if all_list.get('jaw_vice_all_list'): # if all_list.get('jaw_vice_all_list'):
self._write_or_create(all_list.get('jaw_vice_all_list'), '虎钳夹具') # self._write_or_create(all_list.get('jaw_vice_all_list'), '虎钳夹具')
if all_list.get('magnet_fixture_all_list'): # if all_list.get('magnet_fixture_all_list'):
self._write_or_create(all_list.get('magnet_fixture_all_list'), '磁吸夹具') # self._write_or_create(all_list.get('magnet_fixture_all_list'), '磁吸夹具')
if all_list.get('adapter_board_all_list'): # if all_list.get('adapter_board_all_list'):
self._write_or_create(all_list.get('adapter_board_all_list'), '转接板(锁板)夹具') # self._write_or_create(all_list.get('adapter_board_all_list'), '转接板(锁板)夹具')
if all_list.get('scroll_chuck_all_list'): # if all_list.get('scroll_chuck_all_list'):
self._write_or_create(all_list.get('scroll_chuck_all_list'), '三爪卡盘') # self._write_or_create(all_list.get('scroll_chuck_all_list'), '三爪卡盘')
else: # if all_list.get('air_tray_all_list'):
raise ValidationError("夹具型号基本参数认证未通过") # self._write_or_create(all_list.get('air_tray_all_list'),'气吹托盘')
# if all_list.get('magnet_tray_all_list'):
# self._write_or_create(all_list.get('magnet_tray_all_list'),'磁吸托盘')
# else:
# raise ValidationError("夹具型号基本参数认证未通过")
def _write_or_create(self, fixture_parameters_list, material_name): # def _write_or_create(self, fixture_parameters_list, material_name):
for item in fixture_parameters_list: # for item in fixture_parameters_list:
if item: # if item:
basic_parameters = self.search([('code', '=', item.get('code')), ('active', 'in', [True, False])]) # basic_parameters = self.search([('code', '=', item.get('code')), ('active', 'in', [True, False])])
if not basic_parameters: # if not basic_parameters:
self.create(self._get_basic_parameters_list(item, material_name)) # self.create(self._get_basic_parameters_list(item, material_name))
else: # else:
basic_parameters.write(self._get_basic_parameters_list(item, material_name)) # basic_parameters.write(self._get_basic_parameters_list(item, material_name))
class SyncFunctionalFixtureType(models.Model): class SyncFunctionalFixtureType(models.Model):
@@ -3230,4 +3240,94 @@ class EmbryoRedundancySync(models.Model):
"height": item['height'], "height": item['height'],
"active": item['active'], "active": item['active'],
"remark": item['remark'], "remark": item['remark'],
}) })
class SyncFixtureModel(models.Model):
_inherit = 'sf.fixture.model'
_description = 'Redis 优先同步夹具型号'
def sync_all_fixture_model(self):
rc = RedisClient()
key = 'mrs:fixture_model_all_list'
all_list = rc.get_json(key)
if not all_list:
raise ValidationError(f"Redis 中未找到 key={key}")
for item in all_list:
if not item or not item.get('code'):
continue
record = self.search([('code', '=', item['code'])], limit=1)
vals = {
'name': item['name'],
'code': item['code'],
'fixture_material_id': self.env['sf.fixture.material']
.search([('code', '=', item['fixture_material_code'])], limit=1).id,
'multi_mounting_type_id': self.env['sf.multi_mounting.type']
.search([('code', '=', item['multi_mounting_type_code'])], limit=1).id,
'brand_id': self.env['sf.machine.brand']
.search([('code', '=', item['brand_code'])], limit=1).id,
'model_file': base64.b64decode(item['model_file']) if item.get('model_file') else False,
'status': item['status'],
'active': item['active'],
}
if record:
record.write(vals)
else:
self.create(vals)
class SyncfixtureMaterialsBasicParameters(models.Model):
_inherit = 'sf.fixture.materials.basic.parameters'
_description = 'Redis 优先同步夹具基本参数'
def sync_all_fixture_materials_basic_parameters(self):
rc = RedisClient()
key = 'mrs:fixture_param_all_list'
all_list = rc.get_json(key)
if not all_list:
raise ValidationError(f"Redis 中未找到 key={key}")
def _sync_list(param_list, material_name):
for item in param_list or []:
if not item or not item.get('code'):
continue
record = self.search([('code', '=', item['code'])], limit=1)
vals = self._get_basic_parameters_list(item, material_name)
if record:
record.write(vals)
else:
self.create(vals)
_sync_list(all_list.get('zero_chuck_all_list'), '零点卡盘')
_sync_list(all_list.get('zero_tray_all_list'), '零点托盘')
_sync_list(all_list.get('pneumatic_fixture_all_list'), '气动夹具')
_sync_list(all_list.get('jaw_vice_all_list'), '虎钳夹具')
_sync_list(all_list.get('magnet_fixture_all_list'), '磁吸夹具')
_sync_list(all_list.get('adapter_board_all_list'), '转接板(锁板)夹具')
_sync_list(all_list.get('scroll_chuck_all_list'), '三爪卡盘')
_sync_list(all_list.get('air_tray_all_list'), '气吹托盘')
_sync_list(all_list.get('magnet_tray_all_list'), '磁吸托盘')
def _get_basic_parameters_list(self, item, material_name):
"""
统一结构化 item 数据,供写入模型字段使用(你应当根据 material_name 自定义字段映射)
"""
return {
'name': item.get('name'),
'code': item.get('code'),
'length': item.get('length'),
'width': item.get('width'),
'height': item.get('height'),
'diameter': item.get('diameter'),
'weight': item.get('weight'),
'fixture_model_id': self.env['sf.fixture.model'].search([('code', '=', item.get('fixture_model_code'))], limit=1).id,
'materials_model_id': self.env['sf.materials.model'].search([('code', '=', item.get('material_code'))], limit=1).id,
'active': item.get('active', True),
# 你可以根据 material_name 判断类型并补充字段
}