ttk-app-core
Version:
enterprise develop framework
1,313 lines (1,208 loc) • 49.7 kB
JavaScript
import React from 'react'
import { action as MetaAction } from 'edf-meta-engine'
import config from './config'
import { fromJS } from 'immutable'
import moment from 'moment'
import utils, { fetch, number } from 'edf-utils'
import extend from './extend'
import { consts, common } from 'edf-constant'
import {FormDecorator, Select, Form, DatePicker, Button, Input, ColumnsSetting} from 'edf-component'
import gridItemVis from './utils/gridItem'
import { blankDetail } from './data'
const bussinessTypePrefix = [{
prefix: 'CW',
name: '材料出库',
id: '5001001007'
}, {
prefix: 'CP',
name: '产品入库',
id: '5001001003'
}, {
prefix: 'PY',
name: '盘盈入库',
id: '5001001002'
}, {
prefix: 'PK',
name: '盘亏出库',
id: '5001001006'
}, {
prefix: 'CT',
name: '成本调整',
id: '5001001009'
}, {
prefix: 'CG',
name: '采购入库',
id: '5001001001'
}, {
prefix: 'XS',
name: '销售出库',
id: '5001001005'
}, {
prefix: 'ZR',
name: '暂估入库',
id: '5001001004'
}, {
prefix: 'ZH',
name: '暂估回冲',
id: '5001001008'
}]
const Option = Select.Option
const FormItem = Form.Item
class action {
constructor(option) {
this.metaAction = option.metaAction
this.extendAction = option.extendAction
this.voucherAction = option.voucherAction
this.config = config.current
this.webapi = this.config.webapi
}
onInit = ({ component, injections }) => {
this.extendAction.gridAction.onInit({ component, injections })
this.voucherAction.onInit({ component, injections })
this.component = component
this.injections = injections
let addEventListener = this.component.props.addEventListener
if (addEventListener) {
addEventListener('onTabFocus', :: this.onTabFocus)
addEventListener('enlargeClick', () => this.getDom({}))
}
this.billType = this.component.props.billType || 'product'
injections.reduce('init')
this.initLoad(this.component.props.id || null) //4445862265978880
this.renderNum = 1
}
initLoad = async (id) => {
let sourceVoucherCode = null, monthDate, findRes = {}
if(id) {
findRes = await this.webapi.inventoryDoc.findById({id})
findRes.businessDate = moment(findRes.businessDate)
let result = this.repairGetData(findRes)
let isManualCost = false
if(result.businessTypeId == 5001001001 || result.businessTypeId == 5001001005) {
isManualCost = !result.details[0].manualCost
}
this.metaAction.sfs({
'data.form': fromJS(result),
'data.other.typeName': `${result.businessTypeName}单`,
'data.other.isSaved': false,
'data.other.isAdd': isManualCost, // 是否可编辑,采购入库/销售出库
'data.form.attachmentStatus': !isManualCost ? 0 : 1, // 附件查看状态
})
}
if(!id){
// const currentOrg = this.metaAction.context.get("currentOrg")
// let periodDate = currentOrg.periodDate
// if (periodDate) monthDate = utils.date.monthStartEndDay(periodDate)
}
const initCreate = await this.webapi.inventoryDoc.initCreate()
this.injections.reduce('initLoad', { initCreate, sourceVoucherCode, findRes, id})
setTimeout(()=>{
this.getDom({})
}, 20)
}
load = (voucher) => {
this.injections.reduce('load', voucher)
}
getBillTypeName = () => {
let billTypeName
switch (this.billType) {
case 'arrival':
billTypeName = '采购入库单'
break
case 'manufacturCost':
billTypeName = '销售出库单'
break
case 'temporary':
billTypeName = '暂估单'
break
case 'otherBill':
billTypeName = '库存其他单据'
break
case 'product':
billTypeName = '产品入库单'
break
}
return billTypeName
}
getColumnVisible = (key) => {
const businessTypeId = `${this.metaAction.gf('data.form.businessTypeId')}`
if( !businessTypeId || businessTypeId == 'null'){
return true
}
let detail = gridItemVis[businessTypeId] && gridItemVis[businessTypeId].detail ? gridItemVis[businessTypeId].detail : {}
return !!detail[key]
}
renderStyle = () => {
const detailHeight = this.metaAction.gf('data.other.detailHeight')
return {height: detailHeight}
}
// 金额 数量 单价 必填
renderClass = () => {
let name = this.metaAction.gf('data.form.businessTypeId')
if(name == '5001001005' || name == '5001001006' || name == '5001001007'){
return ''
}else{
return 'ant-form-item-required'
}
}
getDom = (e) => {
const dom = document.querySelector('.ttk-scm-app-inventory-documents-form-details')
if( !dom ) {
if( e ) {
return
}
return setTimeout(() => {
return this.getDom()
}, 200)
}
const count = Math.floor(dom.offsetHeight/34) - 2
const details = this.metaAction.gf('data.form.details').toJS()
while (details.length < count) {
details.push(blankDetail);
}
this.metaAction.sfs({
'data.other.detailHeight': count,
'data.form.details': fromJS(details)
})
// this.injections.reduce('setrowsCount', details, details.length)
}
componentDidMount = () => {
this.getDom()
const win = window
if (win.addEventListener) {
document.body.addEventListener('keydown', this.bodyKeydownEvent, false)
window.addEventListener('resize', this.getDom, false)
} else if (win.attachEvent) {
document.body.attachEvent('onkeydown', this.bodyKeydownEvent)
window.attachEvent('onresize', this.getDom)
}
let thisStub = this
setTimeout(() => {
let dom = document.getElementsByClassName('ttk-scm-app-inventory-documents-form-header')[0] //ReactDOM.findDOMNode(thisStub.refs.auxItem)
if (dom) {
if (dom.addEventListener) {
dom.addEventListener('keydown', :: thisStub.handleKeyDown, false)
} else if (dom.attachEvent) {
dom.attachEvent('onkeydown', :: thisStub.handleKeyDown)
} else {
dom.onKeyDown = :: thisStub.handleKeyDown
}
}
}, 0)
}
handleKeyDown(e, index) {
if( !this.getVoucherVisible() ) {
return
}
if (e.key === 'Enter' || e.keyCode == 13 || e.keyCode == 108) {
let dom = document.getElementsByClassName('ttk-scm-app-payment-card-form-header')[0] //ReactDOM.findDOMNode(this.refs.auxItem)
if (dom) {
setTimeout(() => {
let nextFocusIndex = this.getNextFocusIndex()
if (index) {
nextFocusIndex = index
}
if (nextFocusIndex > -1) {
let c = dom.children[nextFocusIndex].children[1].getElementsByClassName('autoFocus_item')[0]
if(c){
if( c.className && c.className.includes('ant-calendar-picker') ) {
c = $(c).find('input')[0]
}
c.tabIndex = 0
c.focus()
c.click()
}
}
}, 0)
}
}
}
getNextFocusIndex() {
let nextFocusIndex
nextFocusIndex = $(document.activeElement).parents('.ant-row').index()
const length = $(document.activeElement).parents('.ant-row').siblings().length
nextFocusIndex++
if (nextFocusIndex == length + 1) {
let dom = document.getElementsByClassName('ttk-scm-app-payment-card-form-header')[0]
if (dom) {
try{
let c = dom.children[nextFocusIndex - 1].children[1].getElementsByClassName('autoFocus_item')[0]
if (c) {
c.blur()
}
}catch(err){
console.log(err)
}
}
setTimeout(() => {
this.metaAction.sf('data.other.focusFieldPath', 'root.children.content.children.details.columns.proceedsType.cell.cell,0')
setTimeout(() => {
let a = $('.ttk-scm-app-payment-card-form-details').find('.ant-cascader-input')
a.focus()
a.click()
}, 0)
}, 16)
}
return nextFocusIndex > length ? -1 : nextFocusIndex
}
componetWillUnmount = () => {
const win = window
if (win.removeEventListener) {
document.body.removeEventListener('keydown', this.bodyKeydownEvent, false)
window.removeEventListener('onresize', this.getDom, false)
} else if (win.detachEvent) {
document.body.detachEvent('onkeydown', this.bodyKeydownEvent)
window.detachEvent('onresize', this.getDom)
}
}
bodyKeydownEvent = (e) => {
const dom = document.getElementById('ttk-scm-app-inventory-documents')
const modalBody = document.getElementsByClassName('ant-modal-body')
if (dom && modalBody && modalBody.length<1){
this.keyDownCickEvent({event:e})
}
}
//监听键盘事件
keyDownCickEvent = (keydown) => {
if (keydown && keydown.event) {
let e = keydown.event
if (e.ctrlKey && e.altKey && (e.key == 'n' || e.keyCode == 78)) { //新增
if (e.preventDefault) {
e.preventDefault()
}
if (e.stopPropagation) {
e.stopPropagation()
}
}
else if (e.ctrlKey && !e.altKey && (e.key == 's' || e.keyCode == 83)) { //保存
this.save(false)
if (e.preventDefault) {
e.preventDefault()
}
if (e.stopPropagation) {
e.stopPropagation()
}
}
else if (e.ctrlKey && !e.altKey && (e.key == '/' || e.keyCode == 191)) {//保存并新增
this.save(true)
if (e.preventDefault) {
e.preventDefault()
}
if (e.stopPropagation) {
e.stopPropagation()
}
}
else if (e.ctrlKey && !e.altKey && (e.key == 'y' || e.keyCode == 89)) {
//审核
if (e.preventDefault) {
e.preventDefault()
}
if (e.stopPropagation) {
e.stopPropagation()
}
}
//判断设备是否为mac
else if (navigator.userAgent.indexOf('Mac OS X') !== -1) {
if (e.ctrlKey && !e.altKey && (e.key == "[" || e.keyCode == 219)) {
//上一张
this.prev()
}
else if (e.ctrlKey && !e.altKey && (e.key == "]" || e.keyCode == 221)) {
//下一张
this.next()
}
} else {
if (e.ctrlKey && !e.altKey && (e.key == "[" || e.keyCode == 37 || e.keyCode == 219)) {
//219 win7 IE11下的keyCode
//上一张
this.prev()
}
else if (e.ctrlKey && !e.altKey && (e.key == "]" || e.keyCode == 39 || e.keyCode == 221)) {
//221 win7 IE11下的keyCode
//下一张
this.next()
}
}
}
}
onTabFocus = async (props) => {
props = props.toJS()
if (props.id) {
this.initLoad(props.id)
} else if (props.isNew) {
this.initLoad()
}
}
setting = async () => {
let setting = this.metaAction.gf('data.setting').toJS()
let initOption = []
// setting = setting && setting.toJS()
let option1 = setting.body.tables[0]
if( option1 ) {
option1.option = option1.details
option1.name = setting.body.name
}else {
option1 = {}
option1.option = []
option1.name = '表体'
}
let option2 = setting.header
if( option2 ) {
option2.option = option2.cards
}else {
option2 = {}
option2.name = '表头'
option2.option = []
}
const res = await this.metaAction.modal('show',{
title: '显示设置',
width: 500,
iconType: null,
footer: null,
bodyStyle: {paddingBottom: '10px'},
children: <ColumnsSetting
option={[option2, option1]}
singleKey='id'
sort={false}
editName={true}
checkedKey='isVisible'
labelKey="caption"
/>
})
if (res && res.type == 'confirm') {
this.handleConfirmSet(res.option)
} else if (res && res.type == 'reset') {
this.handleResetSet(setting.code)
}
}
handleResetSet = async (code) => {
if (code) {
const result = await this.webapi.inventoryDoc.reInitByUser({code: code})
this.metaAction.sf('data.setting', fromJS(result))
setTimeout(()=>{
this.getDom({})
}, 10)
}
}
handleConfirmSet = async (params) => {
if (params) {
const setting = this.metaAction.gf('data.setting').toJS()
const cards = params[0] && params[0].option
const tables = params[1] && params[1].option
if (setting) {
setting.header.cards = cards
if( setting.body.tables[0] ) {
setting.body.tables[0].details = tables
}
}
const result = await this.webapi.inventoryDoc.updateWithDetail(setting)
this.metaAction.sf('data.setting', fromJS(result))
setTimeout(()=>{
this.getDom({})
}, 10)
}
}
add = async() => {
const res = await this.metaAction.modal('confirm', {
title: '放弃',
content: '点击放弃会重置你所有的操作,确定要放弃吗?',
})
if (res) {
this.editCloseTips(false)
if(this.component.props.id){ // 查看
this.initLoad(this.component.props.id)
}else{ // 新增
this.injections.reduce('init')
this.initLoad()
}
}
}
editCloseTips = (istip) => {
if (this.component.props.editing) {
//设置当前单据状态,供单据页签关闭用 false:关闭不提醒 true 关闭提醒
this.component.props.editing(this.component.props.appName, istip)
}
}
audit = async () => {
const id = this.metaAction.gf('data.form.id'),
ts = this.metaAction.gf('data.form.ts'),
status = this.metaAction.gf('data.form.status')
if (!id && !ts) {
this.metaAction.toast('error', '请保存单据')
return
}
if (status == consts.consts.VOUCHERSTATUS_NotApprove || status == consts.consts.VOUCHERSTATUS_Rejected) {
const response = await this.webapi.inventoryDoc.audit({ id, ts })
this.metaAction.toast('success', '单据审核成功')
this.load(response)
} else {
const response = await this.webapi.inventoryDoc.unaudit({ id, ts })
this.metaAction.toast('success', '单据反审核成功')
this.load(response)
}
}
history = async () => {
this.component.props.setPortalContent('出入库明细表', 'ttk-scm-app-warehouse-detail')
}
moreMenuClick = (e) => {
switch (e.key) {
case 'del':
this.del()
break
case 'pay':
this.pay()
break
case 'antiAudit':
this.audit()
break
}
}
del = async () => {
const id = this.metaAction.gf('data.form.id'),
ts = this.metaAction.gf('data.form.ts')
const ret = await this.metaAction.modal('confirm', {
title: '删除',
content: '确认删除?'
})
if (ret) {
if(id){
let businessTypeId = this.metaAction.gf('data.form.businessTypeId')
const response = await this.webapi.inventoryDoc.del({ id, ts })
if(response){
this.metaAction.toast('success', '删除单据成功')
this.injections.reduce('init')
await this.initLoad()
this.getCardCode(businessTypeId)
this.metaAction.sf('data.form.businessTypeId', businessTypeId)
}
}else{
this.initLoad()
this.metaAction.toast('success', '删除单据成功')
}
}
}
pay = () => {
this.metaAction.toast('error', 'TODO')
}
//检查基础项
checkForm = (data) => {
const businessTypeId = this.metaAction.gf('data.form.businessTypeId')
let form = this.metaAction.gf('data.form').toJS()
const requiredParams = [{
key: 'businessDate',
name: '记账日期'
}, {
key: 'businessTypeId',
name: '业务类型'
}]
let message = []
if( businessTypeId == 5001001001 ) {
requiredParams.push({
key: 'supplierId',
name: '供应商'
})
}
if( businessTypeId == 5001001005 ) {
requiredParams.push({
key: 'customerId',
name: '客户'
})
}
requiredParams.forEach(item => {
if( !data[item.key] ) {
message.push(item.name)
}
})
if( message.length > 0 ){
this.metaAction.toast('error', `${message.join(',')}不能为空`)
return false
}
let otherMsg = []
// 单价不能小于0
for (let i = 0; i < form.details.length; i++) {
if (form.details[i].price < 0) otherMsg.push('单价不能为负数')
}
if (otherMsg.length > 0) {
this.metaAction.toast('error', this.getDisplayErrorMSg(otherMsg))
return false
}
return true
}
// 当时产品入库的时候校验
checkProductSumAmount = (data) => {
const { businessTypeId } = data
if( businessTypeId == 5001001003 ) {
const { laborCost, manufacturCost, materialCost, details } = data
let sum1 = laborCost + manufacturCost + materialCost
let sum2 = 0
details.forEach(item => {
sum2 = sum2 + item.amount
})
if( sum1 != sum2 ) {
this.metaAction.toast('warn', '存货金额合计≠直接材料+直接人工+制造金额,请修改使其相等。')
return false
}
}
// 暂估入库不能为负。。。
if(businessTypeId == 5001001004){
const { details } = data
let errorArr = []
details.map(item => {
if(item.quantity<0) errorArr.push(item)
})
if(errorArr.length){
this.metaAction.toast('error', '暂估入库数量不能为负数')
return false
}
}
return true
}
// 检查明细
checkDetail = (data) => {
let businessTypeId = this.metaAction.gf('data.form.businessTypeId'), requiredParams
// 成本调整(无数量单价)
requiredParams = [{
key: 'inventoryCode',
name: '存货编码'
}, {
key: 'inventoryName',
name: '存货名称'
},{
key: 'amount',
name: '金额'
}]
if(businessTypeId != '5001001009' && businessTypeId != '5001001005' && businessTypeId != '5001001006' && businessTypeId != '5001001007'){
requiredParams.push( {
key: 'quantity',
name: '数量'
}, {
key: 'price',
name: '单价'
})
}else if(businessTypeId == '5001001005' || businessTypeId == '5001001006' || businessTypeId == '5001001007'){
requiredParams = [{
key: 'inventoryCode',
name: '存货编码'
}, {
key: 'inventoryName',
name: '存货名称'
},{
key: 'quantity',
name: '数量'
}]
}
let newDetail = []
let message = ''
data.forEach((item, index) => {
let flag = false
for( const value of Object.values(item) ) {
if( !!value ) {
flag = true
}
}
if( flag ) {
newDetail.push(item)
let messageArr = []
requiredParams.forEach(o => {
if( !item[o.key] ) {
messageArr.push(o.name)
}
})
if( messageArr.length > 0 ) {
message = `${message} 第${index+1}行${messageArr.join('、')}不能为空`
}
}
})
if( newDetail.length == 0 ) {
this.metaAction.toast('error', '请至少填写一条数据')
}
if( message ) {
this.metaAction.toast('error', message)
}
if( newDetail.length == 0 || message ) {
return false
}
return newDetail
}
save = async (isNew) => {
const formParams = this.metaAction.gf('data.form').toJS()
const isOk = this.metaAction.gf('data.other.isOk')
if( !this.checkForm(formParams) ) return false
let newDetail = this.checkDetail(formParams.details)
if( newDetail ) {
newDetail.map(item=> item.manualCost=true)
formParams.details = newDetail
}else {
return
}
if( !this.checkProductSumAmount(formParams) ) return
let response
formParams.businessDate = formParams.businessDate.format('YYYY-MM-DD')
formParams.attachments = this.repairAttachment(formParams.attachmentFiles)
const item = bussinessTypePrefix.find(o => formParams.businessTypeId == o.id)
formParams.codePrefix = item.prefix
// formParams.manualCost = true // 只有采购入库和销售出库,采购入库(都不可改),销售出库(单价和金额可改)
if (!isOk) return false
this.metaAction.sf('data.other.isOk', false)
if( formParams.id ){
response = await this.webapi.inventoryDoc.update(formParams)
this.metaAction.sf('data.other.isOk', true)
}else{
response = await this.webapi.inventoryDoc.createApi(formParams)
this.metaAction.sf('data.other.isOk', true)
}
if(response) {
this.metaAction.sf('data.other.isSaved', false)
this.metaAction.toast('success', '保存单据成功')
}
if( isNew ) {
this.injections.reduce('init')
this.initLoad()
}else {
response.businessDate = moment(response.businessDate)
this.metaAction.sf('data.form', fromJS(this.repairGetData(response)))
}
this.editCloseTips(false)
}
repairAttachment = (arr) => {
if( !arr ) {
return []
}
return arr.map(item =>{
return {
...item,
file: {
type: item.type,
id: item.fileId
}
}
})
}
newAction = () => {
this.injections.reduce('init')
this.initLoad()
}
prev = async () => {
const type = this.metaAction.gf('data.form.businessTypeId')
const code = this.metaAction.gf('data.form.sourceVoucherCode')
if( !type ) {
return this.metaAction.toast('warn', '请选择一种业务类型')
}
const response = await this.webapi.inventoryDoc.previous({ code })
response.businessDate = moment(response.businessDate)
this.metaAction.sfs({
'data.other.typeName': `${response.businessTypeName}单`,
'data.form': fromJS(this.repairGetData(response))
})
}
next = async () => {
const type = this.metaAction.gf('data.form.businessTypeId')
const code = this.metaAction.gf('data.form.sourceVoucherCode')
if( !type ) {
return this.metaAction.toast('warn', '请选择一种业务类型')
}
const response = await this.webapi.inventoryDoc.next({ code })
// response && this.load(response)
response.businessDate = moment(response.businessDate)
this.metaAction.sfs({
'data.other.typeName': `${response.businessTypeName}单`,
'data.form': fromJS(this.repairGetData(response))
})
}
repairGetData = (data) => {
// deepClone 一个对象
const result = fromJS(data).toJS()
if( result.department ) {
result.departmentName = result.department.name
delete result.department
}
if( result.project ) {
result.projectName = result.project.name
delete result.project
}
if( result.customer ) {
result.customerName = result.customer.name
delete result.customer
}
if( result.supplierDto ) {
result.supplierName = result.supplierDto.name
delete result.supplierDto
}
result.attachmentFiles = result.attachments
result.details = result.details.map((item) => {
let inventory = item.inventory
let obj = {
inventoryCode: inventory.code,
inventoryId: inventory.id,
inventoryName: inventory.name,
specification: inventory.specification,
unitName: inventory.unitName
}
delete item.inventory
return {
...item,
...obj,
amount: (item.price && item.quantity) ? item.price * item.quantity : item.amount,
taxInclusiveAmount : utils.number.round(item.price * item.quantity, 2)
}
})
const blankDetail = {
warehouseId: null,
inventoryId: null,
unitId: null,
quantity: null,
price: null,
taxInclusivePrice: null,
taxRateId: null,
tax: null,
amount: null,
taxInclusiveAmount: null
}
const length = result.details.length
for( let i = length; i < 12 ; i++ ) {
result.details.push(blankDetail)
}
return result
}
getDisplayErrorMSg = (msg) => {
return <div style={{ display: 'inline-table' }}>{msg.map(item => <div>{item}<br /></div>)}</div>
}
cancel = () => {
this.injections.reduce('init')
}
onFieldChange = (field, storeField,rowIndex,rowData,index) => async(id) => {
if (!field || !storeField) return
let typeId = this.metaAction.gf('data.form.businessTypeId')
if(typeId == '5001001003' || id == '5001001003'){ // 产品入库
setTimeout(()=>{
this.getDom({})
}, 10)
}
this.editCloseTips(true)
this.metaAction.sf('data.other.isSaved', true)
let value = this.metaAction.gf(storeField).find(o => o.get('id') == id)
if (value) {
Object.keys(field).forEach(key => {
this.metaAction.sf(field[key], value.get(key))
})
}else{
Object.keys(field).forEach(key => {
this.metaAction.sf(field[key], undefined)
})
}
if (storeField == 'data.other.inventory') { //当改变存货名称或编码时以下数据也要发生更改
const amount = utils.number.round(rowData.amount, 2),
tax = utils.number.round(amount * (value.get('rate')/100), 2),
taxInclusiveAmount = utils.number.round(amount + tax, 2)
this.metaAction.sfs({
[`data.form.details.${rowIndex}.taxRateId`]: value.get('rate'),
[`data.form.details.${rowIndex}.taxRateName`]: value.get('rateName'),
[`data.form.details.${rowIndex}.tax`]: tax,
[`data.form.details.${rowIndex}.taxInclusiveAmount`]: taxInclusiveAmount,
})
}
if (storeField == 'data.other.bankAccount') {
if (value) {
let settles = this.metaAction.gf('data.form.settles')
settles = settles ? settles.toJS() : []
const id = value.toJS().id, name = value.toJS().name,amount = this.metaAction.gf('data.form.manufacturCostAmount')
if (settles.length == 0) {
const obj ={
bankAccountId: id,
amount: '',
bankAccountName: name,
}
settles.push(obj)
} else {
settles[index].bankAccountId = id
settles[index].bankAccountName = name
}
this.metaAction.sf('data.form.settles', fromJS(settles))
}
}
if( storeField === 'data.other.bussinessType' ) {
this.getCardCode(value.get('id'))
}
}
//获取单据编号
getCardCode = async(id) => {
const item = bussinessTypePrefix.find(o => o.id == id)
const date = this.metaAction.gf('data.form.businessDate')
// return
const sourceVoucherCode = await this.webapi.inventoryDoc.getcode({
"businessDate": date.format('YYYY-MM-DD'),
"codePrefix": item.prefix
})
this.metaAction.sfs({
'data.form.sourceVoucherCode': sourceVoucherCode,
'data.other.typeName': `${item.name}单`
})
}
//支持搜索
filterOption = (inputValue, option, name) => {
if (!option || !option.props || !option.props.value) {
return false
}
//需要确定部门项目这些是否也需要支持助记码这些的搜索
let parmasName = null
if (name.currentPath) {
parmasName= name.currentPath
}
if (parmasName.indexOf('department') != -1) {
parmasName = 'department'
} else if (parmasName.indexOf('inventory') != -1) {
parmasName = 'inventory'
} else if (parmasName.indexOf('department') != -1) {
parmasName = 'department'
} else if (parmasName.indexOf('project') != -1) {
parmasName = 'project'
} else if (parmasName.indexOf('purchasePerson') != -1) {
parmasName = 'purchasePerson'
}
const paramsValues = this.metaAction.gf(`data.other.${parmasName}`),
value = option.props.value
let paramsValue = paramsValues.find(item => item.get('id') == option.props.value)
if (!paramsValue) {
return false
}
let regExp = new RegExp(inputValue, 'i')
return paramsValue.get('name').search(regExp) != -1
|| paramsValue.get('helpCode').search(regExp) != -1 // TODO 只支持助记码搜索,简拼
}
// 供应商搜索
filterOptionArchives = (name,inputValue, option) => {
const namePrmas = {
currentPath: name
}
return this.filterOption(inputValue, option, namePrmas)
}
//存货编码
filterOptionCode = (inputValue, option) => {
if (!option || !option.props || !option.props.value) {
return false
}
const paramsValues = this.metaAction.gf(`data.other.inventory`),
value = option.props.value
let paramsValue = paramsValues.find(item => item.get('id') == option.props.value)
if (!paramsValue) {
return false
}
let regExp = new RegExp(inputValue, 'i')
return paramsValue.get('code').search(regExp) != -1
}
//附件的下载操作
download = (ps) => {
this.voucherAction.download(ps)
}
getAccessToken = () => {
let token = fetch.getAccessToken()
return { token: token }
}
delFile = (index) => {
let form = this.metaAction.gf('data.form').toJS()
this.voucherAction.delFile(index, 'vouchers', this.updateEnclosure)
}
updateEnclosure = async (res) => {
res.ts = ''
const result = await this.webapi.inventoryDoc.updateEnclosure(res)
return result
}
attachmentChange = (info) => {
this.voucherAction.attachmentChange(info, 'vouchers', this.updateEnclosure)
}
beforeUpload = (info,infoList) => {
this.voucherAction.beforeUpload(info,infoList)
}
getDisable = () => {
// let pageStatus = this.metaAction.gf('data.other.pageStatus')
// let disabled = pageStatus == common.commonConst.PAGE_STATUS.READ_ONLY
// return disabled
let isAdd = this.metaAction.gf('data.other.isAdd')
return isAdd
}
//下拉选 票据类型 供应商
handleSelect = (params, isName) => {
params = params && params.toJS()
if (params) {
return params.map((item,index) => {
return <Option key={item.id} value={item && item.id}>{item && item.name}</Option>
})
}
}
//新增档案
addRecordClick = async (add, params, index, rowData) => {
if (params == 'inventory') {
await this.voucherAction[add]('data.other.inventoryItem')
let inventory = this.metaAction.gf('data.other.inventory').toJS()
const inventoryItem = this.metaAction.gf('data.other.inventoryItem').toJS()
inventory.push(inventoryItem)
this.metaAction.sf('data.other.inventory', fromJS(inventory))
let filed = {
id: `data.form.details.${index}.inventoryId`,
name: `data.form.details.${index}.inventoryName`,
code: `data.form.details.${index}.inventoryCode`,
unitId: `data.form.details.${index}.unitId`,
unitName: `data.form.details.${index}.unitName`,
propertyName: `data.form.details.${index}.propertyName`,
taxRateName: `data.form.details.${index}.taxRateName`,
specification: `data.form.details.${index}.specification`
}
this.onFieldChange(filed,'data.other.inventory',index,rowData)(inventoryItem.id)
} else {
await this.voucherAction[add](`data.other.${params}s`)
const res = this.metaAction.gf(`data.other.${params}s`).toJS()
const list = this.metaAction.gf(`data.other.${params}`).toJS()
list.push(res)
this.metaAction.sfs({
[`data.other.${params}`]: fromJS(list),
[`data.form.${params}Id`]: res.id,
[`data.form.${params}Name`]: res.name
})
}
}
// 获取存货
getInventorys = async() => {
await this.voucherAction.getInventory({entity:{isEnable:true}}, `data.other.inventory`)
let type = this.metaAction.gf('data.form.businessTypeId')
if(type == '5001001003'){
let inventory = this.metaAction.gf('data.other.inventory')
inventory = inventory.size ? inventory.toJS() : inventory
let newInventory = []
inventory.map(item=>{
if(item.propertyId == 1 || item.propertyId == 3) newInventory.push(item)
})
this.metaAction.sf('data.other.inventory', fromJS(newInventory))
}
}
//新增 部门 项目 供应商
handleAddRecord = (paramsU,params,index,rowData) => {
const add = `add${paramsU}`
return <Button type='primary'
style={{ width: '100%', borderRadius: '0' }}
onClick={this.addRecordClick.bind(null,add,params,index,rowData)}
>新增</Button>
}
//记账日期控制
handleDisabledDate = () => {
// 不能输入月末结账(后端给)之前的日期,默认当前登录日期
// let endMonth = this.metaAction.gf('data.other.endMonth')
// let beginDate = this.metaAction.gf('data.other.beginDate'), currentDate = current.format('YYYY-MM-DD')
// beginDate = beginDate.replace(/-/g, '')
// currentDate = currentDate.replace(/-/g, '')
// return currentDate && currentDate < beginDate
}
//控制显示
handleVisible = (params) => {
let columnSetting = this.metaAction.gf('data.setting')
columnSetting = columnSetting && columnSetting.toJS()
if (columnSetting) {
return !!columnSetting.header && columnSetting.header.cards.filter(o=> o.fieldName == params )[0].isVisible
}
}
//控制可选择的日期
disabledDate = (current) => {
const enableDate = this.metaAction.gf('data.other.enableDate')
let enableDateNum = parseInt(moment(enableDate).format('YYYYMMDD'))
let currentNum = parseInt(current.format('YYYYMMDD'))
return currentNum < enableDateNum ? true : false
}
//渲染表头
renderFormContent = () => {
let businessDate = this.metaAction.gf('data.form.businessDate'),
departmentName = this.metaAction.gf('data.form.departmentName'),
departmentId = this.metaAction.gf('data.form.departmentId'),
department = this.metaAction.gf('data.other.department'),
projectName = this.metaAction.gf('data.form.projectName'),
projectId = this.metaAction.gf('data.form.projectId'),
project = this.metaAction.gf('data.other.project'),
remark = this.metaAction.gf('data.form.remark'),
bussinessType = this.metaAction.gf('data.other.bussinessType'),
bussinessTypeValue = this.metaAction.gf('data.form.businessTypeId'),
businessTypeName = this.metaAction.gf('data.form.businessTypeName'),
setting = this.metaAction.gf('data.setting').toJS(),
supplierName = this.metaAction.gf('data.form.supplierName'),
supplierId = this.metaAction.gf('data.form.supplierId'),
supplier = this.metaAction.gf('data.other.supplier'),
customerName = this.metaAction.gf('data.form.customerName'),
customerId = this.metaAction.gf('data.form.customerId'),
customer = this.metaAction.gf('data.other.customer'),
businessTypeId = this.metaAction.gf('data.form.businessTypeId')
// billType = this.metaAction.gf('data.other.billType')
let defaultContentArr = [
<FormItem label='记账日期' required={true}>
<DatePicker
value={businessDate}
onChange={(d) => this.metaAction.sf('data.form.businessDate', d)}
disabled={this.getDisable()}
disabledDate={ this.disabledDate }
// disabledDate={this.handleDisabledDate}
>
</DatePicker>
</FormItem>,
<FormItem label='业务类型' required={true}>
<Select
showSearch={true}
disabled={this.getDisable()}
value={bussinessType.size ? bussinessTypeValue : businessTypeName}
onChange={this.onFieldChange({ id: `data.form.businessTypeId`, name: `data.form.businessTypeName` }, `data.other.bussinessType`)}
>
{this.handleSelect(bussinessType)}
</Select>
</FormItem>,
businessTypeId == '5001001001' ?
<FormItem label='供应商' required={true}>
<Select
showSearch={true}
filterOption={this.filterOptionArchives.bind(null, 'supplier')}
placeholder='按名称/拼音搜索'
disabled={this.getDisable()}
value={supplier ? supplierId : supplierName}
onFocus={() => this.voucherAction.getSupplier({entity:{isEnable:true}}, `data.other.supplier`)}
dropdownFooter={this.handleAddRecord('Supplier', 'supplier')}
onChange={this.onFieldChange({ id: `data.form.supplierId`, name: `data.form.supplierName` }, `data.other.supplier`)}
>
{this.handleSelect(supplier, "isName")}
</Select>
</FormItem> : null,
businessTypeId == '5001001005' ?
<FormItem label='客户' required={true}>
<Select
showSearch={true}
filterOption={this.filterOptionArchives.bind(null, 'customer')}
placeholder='按名称/拼音搜索'
allowClear={true}
disabled={this.getDisable()}
value={customer ? customerId : customerName}
onFocus={() => this.voucherAction.getCustomer({entity:{isEnable:true}}, `data.other.customer`)}
dropdownFooter={this.handleAddRecord('Customer', 'customer')}
onChange={this.onFieldChange({ id: `data.form.customerId`, name: `data.form.customerName` }, `data.other.customer`)}
>
{this.handleSelect(customer, "isName")}
</Select>
</FormItem> : null,
this.handleVisible('department') ?
<FormItem label='部门' required={false}>
<Select
showSearch={true}
filterOption={this.filterOptionArchives.bind(null, 'department')}
disabled={this.getDisable()}
placeholder='按名称/拼音搜索'
allowClear={true}
value={department ? departmentId : departmentName}
dropdownFooter={this.handleAddRecord('Department', 'getDepartment')}
onFocus={() => this.voucherAction.getDepartment({entity:{isEnable:true}}, `data.other.department`)}
onChange={this.onFieldChange({ id: `data.form.departmentId`, name: `data.form.departmentName` }, `data.other.department`)}
>
{this.handleSelect(department, "isName")}
</Select>
</FormItem> : null,
this.handleVisible('project') ?
<FormItem label='项目' required={false}>
<Select
showSearch={true}
filterOption={this.filterOptionArchives.bind(null, 'project')}
disabled={this.getDisable()}
placeholder='按名称/拼音搜索'
allowClear={true}
value={project ? projectId : projectName }
onFocus={() => this.voucherAction.getProject({entity:{isEnable:true}}, `data.other.project`)}
dropdownFooter={this.handleAddRecord('Project', 'getProject')}
onChange={this.onFieldChange({ id: `data.form.projectId`, name: `data.form.projectName` }, `data.other.project`)}
>
{this.handleSelect(project, "isName")}
</Select>
</FormItem> : null,
this.handleVisible('remark') ?
<FormItem label='备注'
className='ttk-scm-app-inventory-documents-form-header-remark'>
<Input
value={remark}
onChange={(e) => this.metaAction.sf("data.form.remark", e.target.value)}
disabled={this.getDisable()}>
</Input>
</FormItem> : null
]
return defaultContentArr
}
renderProduct = () => {
const type = this.metaAction.gf('data.form.businessTypeId')
return type == '5001001003' ? true : false
}
calc = (col, rowIndex, rowData, params) => (v) => {
params = Object.assign(params, {
value: v
})
this.voucherAction.calc(col, rowIndex, rowData, params)
this.editCloseTips(true)
this.metaAction.sf('data.other.isSaved', true)
}
quantityFormat = (quantity, decimals, isFocus) => {
if (quantity) {
return this.voucherAction.numberFormat(quantity, decimals, isFocus)
}
}
changeProNum = (path, value) => {
this.editCloseTips(true)
this.metaAction.sf('data.other.isSaved', true)
this.voucherAction.fieldChange(path, value, this.check)
}
check = async (option) => {
if (!option || !option.path)
return
if (option.path == 'data.form.materialCost') {
return { errorPath: 'data.other.error.materialCost', message: this.checkOrigValue(option) }
}else if(option.path == 'data.form.laborCost') {
return { errorPath: 'data.other.error.laborCost', message: this.checkOrigValue(option) }
}else if(option.path == 'data.form.manufacturCost') {
return { errorPath: 'data.other.error.manufacturCost', message: this.checkOrigValue(option) }
}
}
checkOrigValue = (option) => {
if(!this.checkIsNumber(option.value)){
return '请输入数字'
}else{
return ''
}
}
//是否为数字
checkIsNumber = (value) => {
let reg = /^(\-|\+)?\d+(\.\d+)?$/
if(value && !reg.test(value)){
return false
}
return true
}
// 获取栏目名称
getGridName = (code) => {
const setting = this.metaAction.gf('data.setting').toJS()
if( setting.body && setting.body.tables && setting.body.tables[0] && setting.body.tables[0].details) {
const item = setting.body.tables[0].details.find(item => item.fieldName == code)
if( item ) {
return item.caption
}
return '存货编码'
}
return '存货编码'
}
getGridVisible = (code) => {
const setting = this.metaAction.gf('data.setting').toJS()
if( setting.body && setting.body.tables && setting.body.tables[0] && setting.body.tables[0].details) {
const item = setting.body.tables[0].details.find(item => item.fieldName == code)
if( item ) {
return item.isVisible
}
return false
}
return false
}
}
export default function creator(option) {
const metaAction = new MetaAction(option),
extendAction = extend.actionCreator({ ...option, metaAction }),
voucherAction = FormDecorator.actionCreator({ ...option, metaAction }),
// voucherActionG = GridDecorator.actionCreator({ ...option, metaAction }),
o = new action({ ...option, metaAction, extendAction, voucherAction }),
ret = { ...metaAction, ...extendAction.gridAction, ...voucherAction, ...o }
metaAction.config({ metaHandlers: ret })
return ret
}