Compare commits

..

4 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
20 changed files with 472 additions and 263 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

@@ -35,6 +35,7 @@
], ],
'web.assets_backend': [ 'web.assets_backend': [
'sf_base/static/src/scss/*.scss', 'sf_base/static/src/scss/*.scss',
'sf_base/static/src/js/*.js',
], ],
}, },

View File

@@ -0,0 +1,62 @@
/** @odoo-module **/
import { registry } from "@web/core/registry";
import { barcodeGenericHandlers } from '@barcodes/barcode_handlers';
import { patch } from "@web/core/utils/patch";
// 定义新的 clickOnButton 函数
function customClickOnButton(selector) {
console.log("This is the custom clickOnButton function!");
const buttons = document.body.querySelectorAll(selector);
let length = buttons.length;
if (length > 0) {
buttons[length - 1].click();
} else {
console.warn(`Button with selector ${selector} not found`);
}
}
patch(barcodeGenericHandlers, "start", {
start(env, { ui, barcode, notification }) {
// 使用新定义的 clickOnButton 函数
const COMMANDS = {
"O-CMD.EDIT": () => customClickOnButton(".o_form_button_edit"),
"O-CMD.DISCARD": () => customClickOnButton(".o_form_button_cancel"),
"O-CMD.SAVE": () => customClickOnButton(".o_form_button_save"),
"O-CMD.PREV": () => customClickOnButton(".o_pager_previous"),
"O-CMD.NEXT": () => customClickOnButton(".o_pager_next"),
"O-CMD.PAGER-FIRST": () => updatePager("first"),
"O-CMD.PAGER-LAST": () => updatePager("last"),
"O-CMD.CONFIRM": () => customClickOnButton(".jikimo_button_confirm"),
"O-CMD.FLUSHED": () => customClickOnButton(".jikimo_button_flushed"),
};
barcode.bus.addEventListener("barcode_scanned", (ev) => {
const barcode = ev.detail.barcode;
if (barcode.startsWith("O-BTN.")) {
let targets = [];
try {
targets = getVisibleElements(ui.activeElement, `[barcode_trigger=${barcode.slice(6)}]`);
} catch (_e) {
console.warn(`Barcode '${barcode}' is not valid`);
}
for (let elem of targets) {
elem.click();
}
}
if (barcode.startsWith("O-CMD.")) {
const fn = COMMANDS[barcode];
if (fn) {
fn();
} else {
notification.add(env._t("Barcode: ") + `'${barcode}'`, {
title: env._t("Unknown barcode command"),
type: "danger"
});
}
}
});
}
})

View File

@@ -0,0 +1,42 @@
/** @odoo-module **/
import { registry } from '@web/core/registry';
import { formView } from '@web/views/form/form_view';
import { FormController } from '@web/views/form/form_controller';
import { listView } from '@web/views/list/list_view';
import { ListController } from '@web/views/list/list_controller'
import { onRendered, onMounted } from "@odoo/owl";
export class RemoveFocusFormController extends FormController {
setup() {
super.setup();
onMounted(() => {
this.__owl__.bdom.el.querySelectorAll(':focus').forEach(element => element.blur());
})
}
}
registry.category('views').add('remove_focus_form_view', {
...formView,
Controller: RemoveFocusFormController,
});
export class RemoveFocusListController extends ListController {
setup() {
super.setup();
onMounted(() => {
this.__owl__.bdom.el.querySelectorAll(':focus').forEach(element => element.blur());
})
}
}
registry.category('views').add('remove_focus_list_view', {
...listView,
Controller: RemoveFocusListController,
});

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',
@@ -30,7 +30,6 @@
'web.assets_backend': [ 'web.assets_backend': [
'sf_demand_plan/static/src/scss/style.css', 'sf_demand_plan/static/src/scss/style.css',
'sf_demand_plan/static/src/js/print_demand.js', 'sf_demand_plan/static/src/js/print_demand.js',
'sf_demand_plan/static/src/js/custom_button.js',
] ]
}, },
'license': 'LGPL-3', 'license': 'LGPL-3',

View File

@@ -36,7 +36,7 @@ class PurchaseOrderLine(models.Model):
@api.model @api.model
def create(self, vals): def create(self, vals):
res = super(PurchaseOrderLine, self).create(vals) res = super(PurchaseOrderLine, self).create(vals)
if not res.demand_plan_line_id and res.order_id.origin: if not res.demand_plan_line_id:
origin = [origin.replace(' ', '') for origin in res.order_id.origin.split(',')] origin = [origin.replace(' ', '') for origin in res.order_id.origin.split(',')]
if self.env.context.get('demand_plan_line_id'): if self.env.context.get('demand_plan_line_id'):
res.demand_plan_line_id = self.env.context.get('demand_plan_line_id') res.demand_plan_line_id = self.env.context.get('demand_plan_line_id')

View File

@@ -222,15 +222,10 @@ 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')
check_overdelivery_allowed = False if not self.overdelivery_allowed and line_ids.filtered(lambda p: p.location_id.id == customer_location_id):
for line in line_ids: if float_compare(sum_product_uom_qty, self.product_uom_qty,
if line.location_id.id == customer_location_id: precision_rounding=self.product_id.uom_id.rounding) == 1:
if not self.overdelivery_allowed: raise ValidationError(f"已禁止向合作伙伴/客户超量发货,请更换“补货原因”或将“可超量发货”设置为“是”。")
if float_compare(sum_product_uom_qty, self.product_uom_qty,
precision_rounding=line.product_id.uom_id.rounding) == 1:
check_overdelivery_allowed = True
if check_overdelivery_allowed:
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 {

View File

@@ -7,17 +7,39 @@ 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'
_description = 'sf_production_demand_plan' _description = 'sf_production_demand_plan'
def get_location_id(self): def get_location_id(self):
customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers') stock_location = self.env['stock.location'].sudo().search([('name', '=', '客户')], limit=1)
return customer_location_id return stock_location.id
priority = fields.Selection(related='demand_plan_id.priority', string='优先级', store=True) priority = fields.Selection(related='demand_plan_id.priority', string='优先级')
status = fields.Selection([ status = fields.Selection([
('10', '草稿'), ('10', '草稿'),
('20', '待确认'), ('20', '待确认'),
@@ -34,7 +56,7 @@ class SfProductionDemandPlan(models.Model):
company_id = fields.Many2one( company_id = fields.Many2one(
related='sale_order_id.company_id', related='sale_order_id.company_id',
store=True, index=True, precompute=True) store=True, index=True, precompute=True)
customer_name = fields.Char('客户', related='sale_order_id.customer_name', store=True) customer_name = fields.Char('客户', related='sale_order_id.customer_name')
order_remark = fields.Text(related='sale_order_id.remark', order_remark = fields.Text(related='sale_order_id.remark',
string="订单备注", store=True) string="订单备注", store=True)
glb_url = fields.Char(related='sale_order_line_id.glb_url', string='glb文件地址') glb_url = fields.Char(related='sale_order_line_id.glb_url', string='glb文件地址')
@@ -83,7 +105,7 @@ class SfProductionDemandPlan(models.Model):
related='product_id.blank_precision') related='product_id.blank_precision')
unit_number = fields.Float('单件用量', digits=(16, 3), related='product_id.unit_number') 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', store=True) 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='精度')
model_process_parameters_ids = fields.Many2many(related='demand_plan_id.model_process_parameters_ids', model_process_parameters_ids = fields.Many2many(related='demand_plan_id.model_process_parameters_ids',
string='表面工艺', ) string='表面工艺', )
@@ -127,12 +149,6 @@ class SfProductionDemandPlan(models.Model):
string='字段自制类型只读' string='字段自制类型只读'
) )
is_processing = fields.Boolean(
string='正在处理中',
default=False,
help='用于防止重复点击按钮'
)
# hide_action_open_mrp_production = fields.Boolean( # hide_action_open_mrp_production = fields.Boolean(
# string='显示待工艺确认按钮', # string='显示待工艺确认按钮',
# compute='_compute_hid_button', # compute='_compute_hid_button',
@@ -613,6 +629,11 @@ class SfProductionDemandPlan(models.Model):
filtered_plan = self.filtered(lambda mo: mo.status == '30') filtered_plan = self.filtered(lambda mo: mo.status == '30')
if not filtered_plan: if not filtered_plan:
raise UserError(_("没有需要下达的计划!")) raise UserError(_("没有需要下达的计划!"))
check_overdelivery_allowed = False
if not self.demand_plan_id.overdelivery_allowed:
customer_location_id = self.env['ir.model.data']._xmlid_to_res_id('stock.stock_location_customers')
if self.location_id.id == customer_location_id:
check_overdelivery_allowed = True
# 按产品分组并计算总数 # 按产品分组并计算总数
product_data = {} product_data = {}
for plan in filtered_plan: for plan in filtered_plan:
@@ -660,15 +681,9 @@ class SfProductionDemandPlan(models.Model):
'default_demand_plan_line_id': self.ids, 'default_demand_plan_line_id': self.ids,
'default_release_message': warning_message, 'default_release_message': warning_message,
}} }}
else:
for demand_plan_line_id in filtered_plan:
demand_plan_line_id.action_confirm()
def button_release_plan(self): def button_release_plan(self):
self.ensure_one() self.ensure_one()
if self.is_processing:
return
self.is_processing = True
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')
@@ -695,9 +710,9 @@ class SfProductionDemandPlan(models.Model):
self.action_confirm() self.action_confirm()
def action_confirm(self): def action_confirm(self):
"""
#确认需求计划行,创建 BOM、触发库存规则并更新状态。 确认需求计划行,创建 BOM、触发库存规则并更新状态。
"""
# 将当前需求计划行 ID 写入上下文,便于后续方法使用 # 将当前需求计划行 ID 写入上下文,便于后续方法使用
self = self.with_context(demand_plan_line_id=self.id) self = self.with_context(demand_plan_line_id=self.id)
@@ -717,9 +732,9 @@ class SfProductionDemandPlan(models.Model):
def _get_embryo_template_by_supply_method(self): def _get_embryo_template_by_supply_method(self):
"""
#根据供货方式返回对应的胚料模板 product.template 记录。 根据供货方式返回对应的胚料模板 product.template 记录。
"""
supply_map = { supply_map = {
'automation': self.env.ref('sf_dlm.product_embryo_sf_self_machining').sudo(), 'automation': self.env.ref('sf_dlm.product_embryo_sf_self_machining').sudo(),
'outsourcing': self.env.ref('sf_dlm.product_embryo_sf_outsource').sudo(), 'outsourcing': self.env.ref('sf_dlm.product_embryo_sf_outsource').sudo(),
@@ -734,9 +749,9 @@ class SfProductionDemandPlan(models.Model):
def mrp_bom_create(self): def mrp_bom_create(self):
"""
#创建 BOM包含胚料与成品 BOM用于后续生产或采购流程。 创建 BOM包含胚料与成品 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(
@@ -851,9 +866,9 @@ class SfProductionDemandPlan(models.Model):
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
@@ -903,9 +918,9 @@ class SfProductionDemandPlan(models.Model):
def _prepare_procurement_group_vals(self): def _prepare_procurement_group_vals(self):
"""
#构造创建 procurement group 所需的字段。 构造创建 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,
@@ -915,9 +930,9 @@ class SfProductionDemandPlan(models.Model):
def _prepare_procurement_values(self, group_id=False): def _prepare_procurement_values(self, group_id=False):
"""
#构造单个 procurement 请求所需的字段字典。 构造单个 procurement 请求所需的字段字典。
"""
self.ensure_one() self.ensure_one()
# 交货日期与计划日期 # 交货日期与计划日期
@@ -942,6 +957,4 @@ class SfProductionDemandPlan(models.Model):
} }
return values return values
def button_plan_detail(self):
pass

View File

@@ -1,59 +0,0 @@
/** @odoo-module **/
import { registry } from "@web/core/registry";
import { ListRenderer } from "@web/views/list/list_renderer";
import { useService } from "@web/core/utils/hooks";
import { useEffect } from "@odoo/owl";
export class CustomDemandPlanListRenderer extends ListRenderer {
setup() {
super.setup();
this.orm = useService("orm");
this.notification = useService("notification");
console.log('setup', this.props);
// 监听selection属性的变化
useEffect(() => {
this.updateButtonState();
}, () => [this.props.list.selection]);
}
/**
* 更新按钮状态
*/
async updateButtonState() {
const selectedRecords = this.props.list.selection;
const isStatus30 = selectedRecords.some(record => record.data.status != "30");
const button = $(this.__owl__.parent.bdom.parentEl).find('button[name="button_batch_release_plan"]');
console.log('isStatus30', isStatus30, button);
if (isStatus30) {
// 禁用按钮
button.attr('disabled', true);
} else {
button.attr('disabled', false);
}
}
}
// 使用setTimeout延迟注册避免在模块加载时立即执行
setTimeout(() => {
const registerCustomRenderer = () => {
try {
const listView = registry.category("views").get("list");
if (listView) {
registry.category("views").add("custom_demand_plan_list", {
...listView,
Renderer: CustomDemandPlanListRenderer,
});
console.log("Custom demand plan list renderer registered successfully");
} else {
console.warn("List view not found, retrying...");
// 如果还没找到,再等一段时间
setTimeout(registerCustomRenderer, 1000);
}
} catch (error) {
console.error("Error registering custom renderer:", error);
}
};
registerCustomRenderer();
}, 1000);

View File

@@ -4,8 +4,7 @@
<field name="model">sf.production.demand.plan</field> <field name="model">sf.production.demand.plan</field>
<field name="arch" type="xml"> <field name="arch" type="xml">
<tree string="需求计划" default_order="sequence desc,id desc" editable="bottom" <tree string="需求计划" default_order="sequence desc,id desc" editable="bottom"
class="demand_plan_tree freeze-columns-before-part_number" create="false" delete="false" class="demand_plan_tree freeze-columns-before-part_number" create="false" delete="false">
js_class="custom_demand_plan_list">
<header> <header>
<button string="打印" name="button_action_print" type="object" <button string="打印" name="button_action_print" type="object"
class="btn-primary"/> class="btn-primary"/>

View File

@@ -108,9 +108,6 @@
class="btn-primary" class="btn-primary"
attrs="{'invisible': [('hide_release_production_order', '=', False)]}" attrs="{'invisible': [('hide_release_production_order', '=', False)]}"
/> />
<button string="详情" name="button_plan_detail" type="object"
class="btn-primary"
/>
</tree> </tree>
</field> </field>
</page> </page>

View File

@@ -37,7 +37,7 @@ class SfDemandPlanPrintWizard(models.TransientModel):
if pdf_data: if pdf_data:
try: try:
# 执行打印 # 执行打印
# self.env['jikimo.printing'].sudo().print_pdf(pdf_data) self.env['jikimo.printing'].sudo().print_pdf(pdf_data)
record.status = 'success' record.status = 'success'
production_demand_plan_id = self.env['sf.production.demand.plan'].sudo().search( production_demand_plan_id = self.env['sf.production.demand.plan'].sudo().search(
[('model_id', '=', record.model_id)]) [('model_id', '=', record.model_id)])

View File

@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import logging import logging
from odoo import models, fields, api, _ from odoo import models, fields, api, _
from werkzeug.exceptions import InternalServerError
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@@ -18,10 +17,4 @@ class SfReleasePlanWizard(models.TransientModel):
def confirm(self): def confirm(self):
if self.demand_plan_line_id: if self.demand_plan_line_id:
for demand_plan_line_id in self.demand_plan_line_id: for demand_plan_line_id in self.demand_plan_line_id:
try: demand_plan_line_id.action_confirm()
demand_plan_line_id.action_confirm()
except Exception as e:
self.env.cr.rollback()
demand_plan_line_id.write({'is_processing': False})
self.env.cr.commit()
raise InternalServerError('操作失败', e)

View File

@@ -11,7 +11,7 @@
'category': 'sf', 'category': 'sf',
'website': 'https://www.sf.jikimo.com', 'website': 'https://www.sf.jikimo.com',
'depends': ['sf_base', 'sf_maintenance', 'web_widget_model_viewer', 'sf_warehouse', 'jikimo_attachment_viewer', 'depends': ['sf_base', 'sf_maintenance', 'web_widget_model_viewer', 'sf_warehouse', 'jikimo_attachment_viewer',
'jikimo_sale_multiple_supply_methods', 'product', 'jikimo_tree_header_buttons_always_visible'], 'jikimo_sale_multiple_supply_methods', 'product'],
'data': [ 'data': [
'data/cron_data.xml', 'data/cron_data.xml',
'data/stock_data.xml', 'data/stock_data.xml',

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 判断类型并补充字段
}

View File

@@ -155,7 +155,7 @@ class ReSaleOrder(models.Model):
'glb_url': item['glb_url'], 'glb_url': item['glb_url'],
'remark': item.get('remark'), 'remark': item.get('remark'),
'embryo_redundancy_id': item.get('embryo_redundancy_id'), 'embryo_redundancy_id': item.get('embryo_redundancy_id'),
'is_incoming_material': True if item.get('incoming_size') else False, 'is_incoming_material': True if item.get('embryo_redundancy_id') else False,
'manual_quotation': item.get('manual_quotation'), 'manual_quotation': item.get('manual_quotation'),
'model_id': item['model_id'], 'model_id': item['model_id'],
'delivery_end_date': item['delivery_end_date'] 'delivery_end_date': item['delivery_end_date']
@@ -287,7 +287,7 @@ class ResaleOrderLine(models.Model):
check_status = fields.Selection(related='order_id.check_status') check_status = fields.Selection(related='order_id.check_status')
remark = fields.Char('备注') remark = fields.Char('备注')
is_incoming_material = fields.Boolean('客供料', store=True) is_incoming_material = fields.Boolean('客供料', compute='_compute_is_incoming_material', store=True)
embryo_redundancy_id = fields.Many2one('sf.embryo.redundancy', '坯料冗余') embryo_redundancy_id = fields.Many2one('sf.embryo.redundancy', '坯料冗余')
manual_quotation = fields.Boolean('人工编程', default=False) manual_quotation = fields.Boolean('人工编程', default=False)
model_url = fields.Char('模型文件地址') model_url = fields.Char('模型文件地址')