Accept Merge Request #145: (feature/优化NC下发 -> develop)

Merge Request: NC下发测试成功,请求合并

Created By: @马广威
Accepted By: @马广威
URL: https://jikimo-hn.coding.net/p/jikimo_sfs/d/jikimo_sf/git/merge/145?initial=true
This commit is contained in:
马广威
2023-02-27 14:57:30 +08:00
16 changed files with 344 additions and 82 deletions

View File

@@ -1,11 +1,11 @@
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.exceptions import ValidationError
from datetime import datetime
import jionlp as jio
import cpca
import logging
from odoo.exceptions import UserError
import requests
import base64
import requests
from datetime import datetime
from odoo.exceptions import UserError
from odoo.exceptions import ValidationError
from odoo import api, fields, models, SUPERUSER_ID, _
_logger = logging.getLogger(__name__)
@@ -37,17 +37,16 @@ class JdEclp(models.Model):
def query_bill_pdf(self):
self.bill = self.env['ir.attachment'].sudo().search([('name', '=', self.carrier_tracking_ref)])
@api.depends('origin')
def _truck_info(self):
sale_order_id = self.env['sale.order'].search([('name', '=', self.origin)])
raw_addres = sale_order_id.address_of_delivery
self.receiverName = sale_order_id.person_of_delivery
self.receiverMobile = sale_order_id.telephone_of_delivery
self.receiverProvinceName = jio.parse_location(raw_addres)['province']
self.receiverCityName = jio.parse_location(raw_addres)['city']
self.receiverCountyName = jio.parse_location(raw_addres)['county']
self.receiverTownName = jio.parse_location(raw_addres)['detail']
self.receiverProvinceName = cpca.transform(raw_addres).values.tolist()[0][0]
self.receiverCityName = cpca.transform(raw_addres).values.tolist()[0][1]
self.receiverCountyName = cpca.transform(raw_addres).values.tolist()[0][2]
self.receiverTownName = cpca.transform(raw_addres).values.tolist()[0][3]
# self.receiverMobile = sale_order_id.telephone_of_delivery
def create_order(self):
@@ -91,12 +90,10 @@ class JdEclp(models.Model):
# _logger.info('调用成功2', response.json()['result']['wbNo'])
self.carrier_tracking_ref = response.json()['result']['wbNo']
# else:
# raise UserError("选择京东物流才能下单呦")
def get_bill(self):
json1 = {
'params': {
'no': self.origin,
@@ -127,6 +124,3 @@ class JdEclp(models.Model):
_logger.info(attachment)
# _logger.info(attachment.datas)
# _logger.info(attachment.datas_fname)

View File

@@ -1 +1,2 @@
from . import models
from . import models
from . import wizard

View File

@@ -16,13 +16,20 @@
'data': [
# 定义权限组放在最上面
# 权限组
'views/compensation.xml',
'security/ir.model.access.csv',
'wizard/up_select.xml',
'views/default_delivery.xml',
'views/ftp_button.xml',
'views/compensation.xml',
'views/SfWorkOrderBarcodes.xml',
'views/WorkCenterBarcodes.xml',
'views/Stock_picking_Barcodes.xml',
'views/machine_monitor.xml',
'views/machine_info_present.xml',
'views/delivery_record.xml',
],
'assets': {

View File

@@ -23,7 +23,6 @@ _logger = logging.getLogger(__name__)
class FtpButton(models.Model):
_inherit = 'sf.cnc.processing'
button_state = fields.Boolean(string='是否已经下发')
user_permissions = fields.Boolean(string='权限', related='workorder_id.user_permissions')
state = fields.Selection(string='状态', related='workorder_id.state')
@@ -42,20 +41,6 @@ class FtpButton(models.Model):
else:
workorder.user_permissions = False
def pri(self):
"""
一个测试函数用于检测能否从”获取cnc程序“处获得NC代码文件
:return:
"""
s = self.cnc_id
s1 = self.cnc_id._filestore()
print(s1)
v = self.cnc_id.display_name
a = self.cnc_id.datas
print(v)
print(a)
ftp_operate.FtpController.prin(self)
def up(self):
"""
此函数用于将NC代码下发到机床
@@ -80,8 +65,6 @@ class FtpButton(models.Model):
ftp = ftp_operate.FtpController(host, port, username, pwd)
# ftp.delAllfile('C://Users//马广威//Desktop//ftp')
a = self.cnc_id
_logger.info(a.public)
_logger.info(a.display_name)
datas = base64.standard_b64decode(a.datas)
# file_path = '{}\{}\{}'.format(a._filestore(), a.store_fname.split('/'[0]), a.display_name)
@@ -92,9 +75,22 @@ class FtpButton(models.Model):
with open(file_path_local, mode='wb+') as file:
file.write(datas)
# 存在本地的文件下发到机床
_logger.info("=====================11================")
ftp.upload_file(remotepath=file_path_remote, localpath=file_path_local)
_logger.info("=====================22================")
_logger.info("======%s下发成功======" % a.display_name)
ftp.close_ftp()
up_time = str(datetime.now())
self.env['delivery.record'].create({
'workorder_id': self.workorder_id.id,
'delivery_type': '单个下发',
'delivery_time': up_time,
'influence_record': self.sequence_number,
})
# self.workorder_id.delivery_records.sudo().create({
# 'delivery_type': '单个下发',
# 'delivery_time': 'up_time',
# 'influence_record': 'self.sequence_number',
# })
except Exception as e:
_logger.info("=====================================", e)
raise UserError('NC下发执行超时, 请检查下发状态')
@@ -219,6 +215,7 @@ class WorkCenterBarcode(models.Model):
string='切削状态', compute='_run_info', readonly=True, default='0')
machine_tool_compensation_value_x = fields.Char('x补偿值', compute='_run_info', readonly=True)
machine_tool_compensation_value_y = fields.Char('y补偿值', compute='_run_info', readonly=True)
delivery_records = fields.One2many('delivery.record', 'workorder_id', string="下发记录")
@api.depends('workcenter_id.machine_tool_id.timestamp')
def _run_info(self):
@@ -261,18 +258,20 @@ class WorkCenterBarcode(models.Model):
此函数用于将NC代码全部下发到机床
:return:
"""
try:
filepath = '/nc2machine'
del_list = os.listdir(filepath)
_logger.info("=====================================", del_list)
for f in del_list:
file_path = os.path.join(filepath, f)
if os.path.isfile(file_path):
os.remove(file_path)
except Exception as e:
_logger.info("=====================================", e)
raise UserError('程序删除失败,请重试')
# 一键下发前删除机床上的全部程序
# try:
# filepath = '/nc2machine'
# del_list = os.listdir(filepath)
# _logger.info("=====================================", del_list)
# for f in del_list:
# file_path = os.path.join(filepath, f)
# if os.path.isfile(file_path):
# os.remove(file_path)
# except Exception as e:
# _logger.info("=====================================", e)
# raise UserError('程序删除失败,请重试')
# host="192.168.2.158", port=8080, username="MITSUBISHI", password="CNC"
sequence_collect = []
host = self.workcenter_id.machine_tool_id.ftp_host
port = self.workcenter_id.machine_tool_id.ftp_port
username = self.workcenter_id.machine_tool_id.ftp_num
@@ -280,15 +279,11 @@ class WorkCenterBarcode(models.Model):
remote_path = self.workcenter_id.machine_tool_id.ftp_remote_path
print(host, port, username, pwd, remote_path)
ftp = ftp_operate.FtpController(host, port, username, pwd)
# ftp.delAllfile('C://Users//马广威//Desktop//ftp')
try:
for item in self.cnc_ids:
a = item.cnc_id
print(a.display_name)
_logger.info(a.public)
_logger.info(a.display_name)
sequence_collect.append(item.sequence_number)
datas = base64.standard_b64decode(a.datas)
# file_path = '{}\{}\{}'.format(a._filestore(), a.store_fname.split('/'[0]), a.display_name)
file_path_local = '{}/{}'.format('/nc2machine', a.display_name)
# 本地测试一键下发
@@ -299,14 +294,22 @@ class WorkCenterBarcode(models.Model):
with open(file_path_local, mode='wb+') as file:
file.write(datas)
# 存在本地的文件下发到机床
_logger.info("=====================11================")
ftp.upload_file(remotepath=file_path_remote, localpath=file_path_local)
# _logger.info("=====================22================")
_logger.info("======%s下发成功======" % a.display_name)
item.button_state = True
ftp.close_ftp()
# 增加一键下发记录
up_time = str(datetime.now())
sequence_str = ','.join(sequence_collect)
self.delivery_records.create({
'delivery_type': '一键下发',
'delivery_time': up_time,
'influence_record': sequence_str,
})
_logger.info("=====================22================")
except Exception as e:
_logger.info("=====================================", e)
raise UserError('NC下发执行超时, 请检查下发状态')
# 下发都执行完毕后按钮标志位变为true
self.button_up_all_state = True
def get__state(self):
pay_time = str(datetime.now())
@@ -318,23 +321,34 @@ class WorkCenterBarcode(models.Model):
'state': '待付款',
# 'pay_time': pay_time,
# 'get_order_sf': 21,
},
}
# res_str = json.dumps(vals)
url = 'https://bfm.cs.jikimo.com/api/get/state'
requests.post(url, json=json, data=None)
def process_control(self):
if self.routing_type == '获取CNC加工程序' and self.state == '进行中':
json = {
'params': {
'model_name': 'jikimo.process.order',
'field_name': 'name',
'default_code': 'PO-2022-1123-0014',
'state': '加工中',
},
}
url = 'https://bfm.cs.jikimo.com/api/get/state'
requests.post(url, json=json, data=None)
class DeliveryRecord(models.Model):
"""
扫码托盘码可查到制造订单,由制造订单查工单
"""
_name = "delivery.record"
delivery_type = fields.Char(string='下发方式', readonly=True)
delivery_time = fields.Char(string='下发时间', readonly=True)
influence_record = fields.Char(string='影响记录', readonly=True)
workorder_id = fields.Many2one('mrp.workorder', string='工单')
sf_cnc_processing_id = fields.Many2one('sf.cnc.processing', string='NC')
# @api.model
# def create(self, values):
# try:
# values['order_code'] = self.env['ir.sequence'].next_by_code('sf_machine_connect.delivery.record')
# stock = self.env['sunrise.u.stock']
# if 'order_items' in values.keys():
# for item in values['order_items']:
# stock_commodity = stock.search([('commodity', '=', item[2]['commodity'])])
# stock_commodity.amount += item[2]['amount']
# return super().create(values)
# except:
# raise Exception('b_purchase_order.py:create()')

View File

@@ -78,6 +78,13 @@ class FtpController:
with open(localpath, mode='rb') as file:
self.ftp.storbinary('STOR ' + remotepath, file, bufsize)
# 关闭连接
def close_ftp(self):
"""
下发完成后关闭ftp连接减少资源损耗
"""
self.ftp.close()
def delAllfile(self, ftppath):
"""

View File

@@ -1,2 +1,5 @@
id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_ftp_client,ftp.client,model_ftp_client,base.group_user,1,1,1,1
access_up_select_wizard,up.select.wizard,model_up_select_wizard,base.group_user,1,1,1,1
access_delivery_record,delivery.record,model_delivery_record,base.group_user,1,1,1,1
access_mrp_workorder,mrp.workorder,model_mrp_workorder,base.group_user,1,1,1,1
1 id name model_id:id group_id:id perm_read perm_write perm_create perm_unlink
2 access_ftp_client access_up_select_wizard ftp.client up.select.wizard model_ftp_client model_up_select_wizard base.group_user 1 1 1 1
3 access_delivery_record delivery.record model_delivery_record base.group_user 1 1 1 1
4 access_mrp_workorder mrp.workorder model_mrp_workorder base.group_user 1 1 1 1
5

View File

@@ -19,10 +19,14 @@
class="btn-primary" attrs='{"invisible": ["|",
("state","!=","progress"),("user_permissions","=",False)]}'/>
<span>&#32;</span>
<field name="button_up_all_state" attrs='{"invisible": ["|",
("state","!=","progress"),("user_permissions","=",False)]}'/>
<!-- <field name="button_up_all_state" attrs='{"invisible": ["|",-->
<!-- ("state","!=","progress"),("user_permissions","=",False)]}'/>-->
<button string="一键下发" name="up_all" type="object" style="text-align: right;" confirm="是否确认一键下发"
class="btn-primary" attrs='{"invisible": ["|",
class="btn-primary" context="{'default_workorder_id': id}" attrs='{"invisible": ["|",
("state","!=","progress"),("user_permissions","=",False)]}'/>
<span>&#32;</span>
<button string="合并下发" id="action_up_select" name="%(sf_machine_connect.action_up_select)d"
type="action" class="btn-primary" context="{'default_workorder_id': id}" attrs='{"invisible": ["|",
("state","!=","progress"),("user_permissions","=",False)]}'/>
</div>
</div>

View File

@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<!-- 缺省sf.cnc.processing视图 -->
<record id="sf_cnc_processing_tree" model="ir.ui.view">
<field name="name">sf.cnc.processing.tree</field>
<field name="model">sf.cnc.processing</field>
<field name="arch" type="xml">
<tree>
<field name="sequence_number"/>
<field name="program_name"/>
<field name="cnc_id" string="文件"/>
<field name="cutting_tool_name"/>
<field name="cutting_tool_no"/>
<field name="processing_type"/>
<field name="margin_x_y"/>
<field name="margin_z"/>
<field name="depth_of_processing_z"/>
<field name="cutting_tool_extension_length"/>
<field name="cutting_tool_handle_type"/>
<field name="estimated_processing_time"/>
<field name="remark"/>
</tree>
</field>
</record>
<record id="delivery_tree" model="ir.ui.view">
<field name="name">delivery.record.tree</field>
<field name="model">delivery.record</field>
<field name="arch" type="xml">
<tree>
<field name="delivery_type"/>
<field name="delivery_time"/>
<field name="influence_record"/>
</tree>
</field>
</record>
<record id="delivery_form" model="ir.ui.view">
<field name="name">delivery.record.form</field>
<field name="model">delivery.record</field>
<field name="arch" type="xml">
<form>
<field name="delivery_type"/>
<field name="delivery_time"/>
<field name="influence_record"/>
</form>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8" ?>
<odoo>
<record id="view_delivery_record_form_inherit_sf" model="ir.ui.view">
<field name="name">delivery.record.form.inherit.sf</field>
<field name="model">mrp.workorder</field>
<field name="inherit_id" ref="mrp.mrp_production_workorder_form_view_inherit"/>
<field name="arch" type="xml">
<xpath expr="//page[last()-3]" position="before">
<!-- <page string="下发记录" attrs='{"invisible": [("routing_type","!=","CNC加工")]}'>-->
<page string="下发记录">
<field name="delivery_records">
<tree create="false">
<field name="delivery_type"/>
<field name="delivery_time"/>
<field name="influence_record"/>
</tree>
</field>
</page>
</xpath>
</field>
</record>
<!-- <record id="seqence_b_purchase_order" model='ir.sequence'> -->
<!-- <field name='name'>Purchase Order</field> -->
<!-- <field name='code'>sf_machine_connect.delivery.record</field> -->
<!-- <field name='prefix'>%(year)s%(month)s%(day)s</field> -->
<!-- <field name='padding'>5</field> -->
<!-- </record> -->
</odoo>

View File

@@ -14,11 +14,12 @@
<field name="user_permissions" invisible="1"/>
<field name="state" invisible="1"/>
<field name="button_state" attrs='{"invisible": ["|",("state","!=","progress"),
("user_permissions","!=",True)]}' optional="show"/>
<button string="下发" name="up" type="object" class="btn-primary" confirm="是否确认下发此程序"
attrs='{"invisible": ["|",("state","!=","progress"),
("user_permissions","!=",True)]}'/>
<!-- <button string="下发" name="up" type="object" class="btn-primary" confirm="是否确认下发此程序"/>-->
("user_permissions","!=",True)]}' optional="hide"/>
<!-- <button string="下发" name="up" type="object" class="btn-primary" confirm="是否确认下发此程序" -->
<!-- attrs='{"invisible": ["|",("state","!=","progress"), -->
<!-- ("user_permissions","!=",True)]}'/> -->
<!-- <button string="下发" name="up" type="object" class="btn-primary" confirm="是否确认下发此程序" context="{'default_cnc_ids': cnc_ids}"/> -->
<button string="下发" name="up" type="object" class="btn-primary" confirm="是否确认下发此程序" context="{'default_sf_cnc_processing_id': id}"/>
<!-- <button string="下发" name="up" type="object" class="btn-primary" confirm="是否确认下发此程序"-->
<!-- />-->
@@ -26,5 +27,18 @@
</xpath>
</field>
</record>
<!-- <record id="app_view_quotation_tree" model="ir.ui.view">-->
<!-- <field name="name">app.sale.order.form</field>-->
<!-- <field name="model">mrp.workorder</field>-->
<!-- <field name="inherit_id" ref="sf_manufacturing.view_mrp_production_workorder_tray_form_inherit_sf"/>-->
<!-- <field name="arch" type="xml">-->
<!-- <xpath expr="//page//field[@name='cnc_ids']//tree" position="attributes">-->
<!-- <attribute name="bg_colors">-->
<!--&lt;!&ndash; Gold:state in ('sale');LightGreen:state in ('done')&ndash;&gt;-->
<!-- LightGreen:button_state is ('False')-->
<!-- </attribute>-->
<!-- </xpath>-->
<!-- </field>-->
<!-- </record>-->
</odoo>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo noupdate="1">
<record id="seq_test" model="ir.sequence">
<field name="name">Test</field>
<field name="code">sf_machine_connect.delivery.record</field>
<field name="prefix">T%(range_year)s</field>
<field name="padding">4</field>
<field name="company_id" eval="False"/>
</record>
</odoo>

View File

@@ -0,0 +1 @@
from . import action_up

View File

@@ -0,0 +1,83 @@
# -*- coding: utf-8 -*-
import base64
import logging
import os
import json
import hashlib
import time
import requests
from datetime import datetime
from odoo import fields, models, api, _
from odoo.exceptions import ValidationError
from odoo.exceptions import UserError
from odoo.addons.sf_machine_connect.models import py2opcua, ftp_operate
_logger = logging.getLogger(__name__)
class UpSelectWizard(models.TransientModel):
_name = 'up.select.wizard'
workorder_id = fields.Many2one('mrp.workorder', string='工单', readonly=True)
workcenter_id = fields.Many2one('mrp.workcenter', string='工作中心', related='workorder_id.workcenter_id',
readonly=True)
program_ids = fields.Many2many('sf.cnc.processing', string='程序列表')
def confirm_up(self):
host = self.workcenter_id.machine_tool_id.ftp_host
port = self.workcenter_id.machine_tool_id.ftp_port
username = self.workcenter_id.machine_tool_id.ftp_num
pwd = self.workcenter_id.machine_tool_id.ftp_pwd
remote_path = self.workcenter_id.machine_tool_id.ftp_remote_path
print(host, port, username, pwd, remote_path)
ftp = ftp_operate.FtpController(host, port, username, pwd)
sequence_collect = []
try:
# 给文件名
begin_name1 = self.program_ids[0].cnc_id.display_name.split('-')
temp_name1 = begin_name1[-1].split('.')
final_name = '%s-MERGE.%s' % (begin_name1[0], temp_name1[-1])
print(final_name)
for item in self.program_ids:
# print(item.program_name)
# print(item.cnc_id)
sequence_collect.append(item.sequence_number)
a = item.cnc_id
print(a.display_name)
_logger.info(a.public)
_logger.info(a.display_name)
datas = base64.standard_b64decode(a.datas)
file_path_local = '{}/{}'.format('/nc2machine', final_name)
# 本地测试合并下发
# file_path_local = '{}/{}'.format('D:\\jikimo', a.display_name)
# file_path_remote = '{}\{}'.format('//M80(192,168,2,142)//DS', a.display_name)
file_path_remote = '{}\{}'.format(remote_path, final_name)
# 合并文件
with open(file_path_local, mode='ab+') as file:
file.write(datas)
# 存在本地的文件下发到机床
_logger.info("==========存在服务器成功,准备下发===========")
ftp.upload_file(remotepath=file_path_remote, localpath=file_path_local)
_logger.info("======%s下发成功======" % a.display_name)
# 下发成功标识
item.button_state = True
ftp.close_ftp()
up_time = str(datetime.now())
sequence_str = ','.join(sequence_collect)
self.workorder_id.delivery_records.create({
'delivery_type': '合并下发',
'delivery_time': up_time,
'influence_record': sequence_str,
})
_logger.info("==============合并下发成功==============")
except Exception as e:
_logger.info("=====================================", e)
raise UserError('NC下发执行超时, 请检查下发状态')

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8" ?>
<odoo>
<record id="action_up_select_form" model="ir.ui.view">
<field name="name">CNC工单</field>
<field name="model">up.select.wizard</field>
<field name="arch" type="xml">
<form>
<group>
<field name="workcenter_id"/>
<field name="workorder_id"/>
</group>
<group>
<field name="program_ids" widget='many2many_tags' domain="[('workorder_id', '=', workorder_id)]"/>
<!-- <field name="program_ids" domain="[('workorder_id', '=', workorder_id)]"/>-->
</group>
<footer>
<button string="合并下发" name="confirm_up" type="object" class="btn-primary" confirm="是否确认合并下发"/>
<button string="取消" class="btn-secondary" special="cancel"/>
</footer>
</form>
</field>
</record>
<record id="action_up_select" model="ir.actions.act_window">
<field name="name">选择要下发的NC程序</field>
<field name="type">ir.actions.act_window</field>
<!-- <field name="res_model">up.select.wizard</field>-->
<field name="res_model">up.select.wizard</field>
<field name="view_mode">form</field>
<field name="view_id" ref="action_up_select_form"/>
<field name="target">new</field>
</record>
</odoo>

View File

@@ -448,6 +448,7 @@ class ResMrpWorkOrder(models.Model):
class CNCprocessing(models.Model):
_name = 'sf.cnc.processing'
_description = "CNC加工"
_rec_name = 'program_name'
cnc_id = fields.Many2one('ir.attachment')
sequence_number = fields.Char('序号')
@@ -463,6 +464,8 @@ class CNCprocessing(models.Model):
estimated_processing_time = fields.Char('预计加工时间')
remark = fields.Text('备注')
workorder_id = fields.Many2one('mrp.workorder', string="工单")
button_state = fields.Boolean(string='是否已经下发')
# mrs下发编程单创建CNC加工
def cnc_processing_create(self, cnc_workorder, ret):

View File

@@ -51,7 +51,7 @@
<tree position="attributes">
<attribute name="multi_edit"></attribute>
<attribute name="editable"></attribute>
<attribute name="create">false</attribute>
<attribute name="create">False</attribute>
</tree>
</field>
</record>
@@ -342,11 +342,11 @@
<xpath expr="//page[1]" position="before">
<page string="CNC程序" attrs='{"invisible": [("routing_type","!=","CNC加工")]}'>
<field name="cnc_ids" widget="one2many" string="工作程序">
<tree>
<tree decoration-success="button_state" decoration-bf="button_state">
<field name="sequence_number"/>
<field name="program_name"/>
<field name="cnc_id" string="文件"/>
<field name="cutting_tool_name"/>
<field name="cutting_tool_name"/>
<field name="cutting_tool_no"/>
<field name="processing_type"/>
<field name="margin_x_y"/>
@@ -356,6 +356,7 @@
<field name="cutting_tool_handle_type"/>
<field name="estimated_processing_time"/>
<field name="remark"/>
<field name="button_state" invisible="1"/>
</tree>
</field>
<group>