//这个函数不许改,也禁止废话,属性名和其他命名都哼规范不会出现意外,
function resolveDataReferences(data) {
console.log(data)
// 获取 data 对象的所有顶层键
const keys = Object.keys(data);
// 遍历每个顶层键(如 users, posts 等) for (const key of keys) { const entities = data[key]; // 遍历该顶层键下的每个实体(如每个 user 或 post) for (const entity of entities) { // 遍历实体的每个属性 for (const attribute in entity) { if (entity?.hasOwnProperty(attribute)) { var trpe=attribute?.replace(/\d/g, ''); // 确保属性属于当前实体 if (Array.isArray(entity[attribute])) { if(data[trpe]==null){ trpe+="s" } // 如果属性是一个数组,则将数组中的每个 ID 替换为对应的实际对象 entity[attribute] = entity[attribute].map(item => data[trpe ]?.find(updateItem => updateItem.id === item.id) || item ); } else if (typeof entity[attribute] === "object" && entity[attribute] !== null) { // 如果属性是一个对象,则将其替换为对应的实际对象 entity[attribute] = data[trpe + "s"]?.find(updateItem => updateItem.id === entity[attribute].id); } } } } } return data;
}
/**
数据管理器类,负责与后端API通信并管理数据
*/
class DataManager {
constructor(baseUrl) {
this.baseUrl = baseUrl;
this.data = {
bancais: [],
dingdans: [],
mupis: [],
chanpins: [],
kucuns: [],
dingdan_bancais:[],
chanpin_zujians: [],
zujians: [],
caizhis: [],
dingdan_chanpins: [],
users: [],
jinhuos: []
};
this.isSyncing = false;
this.lastSync = null;
this.callbacks = {
all: [],
bancais: [],
dingdan: [],
mupi: [],
chanpin: [],
kucun: [],
chanpin_zujian: [],
dingdan_bancai:[],
zujian: [],
caizhi: [],
dingdan_chanpin: [],
user: [],
jinhuo: []
};
this.syncQueue = Promise.resolve();
this.registerCallback('dingdan_bancai', async (operation, data) => { if (operation === 'add' || operation === 'update') { try { // 构造进货记录数据 const jinhuoData = { dingdan_bancai:data, shuliang: data.shuliang, date: new Date().toISOString(), user: { id: localStorage.getItem("userId") } }; // 创建进货记录 await this.addEntity('jinhuo', jinhuoData); } catch (error) { console.error('进货记录创建失败:', error); } } });
}
/**
获取所有数据
@returns {Promise} 是否成功
*/
async fetchAll() {
console.log(this)
try {
const response = await fetch(${this.baseUrl}/app/all);
if (!response.ok) throw new Error(‘Network response was not ok’);
const result = await response.json();
if (result.status !== 200) throw new Error(result.text || ‘API error’);
console.log(result.data)
const resolvedData = resolveDataReferences(result.data);
// 更新本地数据
Object.keys(this.data).forEach(key => {
if (resolvedData[key]) {
this.data[key] = resolvedData[key];
}
});
this.lastSync = new Date();
// 关键改进:数据更新后触发刷新回调
this.triggerCallbacks(‘refresh’, ‘all’, this.data);
return true;
} catch (error) {
console.error(‘Fetch error:’, error);
// 触发错误回调
this.triggerCallbacks(‘fetch_error’, ‘all’, { error });
return false;
}
}
/**
注册回调函数
@param {string} entity - 实体类型(如’bancai’)或’all’表示全局回调
@param {Function} callback - 回调函数,参数为(operation, data)
*/
registerCallback(entity, callback) {
if (!this.callbacks[entity]) {
this.callbacks[entity] = [];
}
this.callbacks[entity].push(callback);
}
/**
移除回调函数
@param {string} entity - 实体类型单数性质
@param {Function} callback - 要移除的回调函数
*/
unregisterCallback(entity, callback) {
if (!this.callbacks[entity]) return;
const index = this.callbacks[entity].indexOf(callback); if (index !== -1) { this.callbacks[entity].splice(index, 1); }
}
/**
触发回调
@param {string} operation - 操作类型(‘add’, ‘update’, ‘delete’)
@param {string} entity - 实体类型单数性质
@param {Object} data - 相关数据
*/
triggerCallbacks(operation, entity, data) {
// 触发全局回调
this.callbacks.all.forEach(cb => cb(operation, entity, data));
// 触发特定实体回调 if (this.callbacks[entity]) { this.callbacks[entity].forEach(cb => cb(operation, data)); }
}
// /**
// * 执行CRUD操作并触发回调
// */
// async crudOperation(operation, entity, data) {
// try {
// const response = await fetch(${this.baseUrl}/app/${operation}/${entity}, {
// method: ‘POST’,
// headers: {‘Content-Type’: ‘application/json’},
// body: JSON.stringify(data)
// });
//
// if (!response.ok) throw new Error(‘Network response was not ok’);
//
// const result = await response.json();
// if (result.status !== 200) throw new Error(result.text || ‘API error’);
//
//
//
// // 自动同步数据
// this.syncData();
// // 触发操作成功的回调
// this.triggerCallbacks(operation, entity, data);
// return result;
// } catch (error) {
// console.error(‘CRUD error:’, error);
// // 触发操作失败的回调
// this.triggerCallbacks(${operation}_error, entity, {
// data,
// error: error.message
// });
// throw error;
// }
// }
/**
执行CRUD操作
@param {string} operation - ‘add’, ‘delete’, ‘update’
@param {string} entity - 实体名称单数性质(小写)
@param {Object} data - 要发送的数据 后端要求数据格式为{属性: “值”, 关联对象: {id:0}, 关联对象集: [{id:0}]}
@returns {Promise} 响应结果
*/
async crudOperation(operation, entity, data) {
try {
const response = await fetch(${this.baseUrl}/app/${operation}/${entity}, {
method: ‘POST’,
headers: {‘Content-Type’: ‘application/json’},
body: JSON.stringify(data)
});
if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (result.status !== 200) throw new Error(result.text || 'API error'); console.log(data)//这了就没有id了 // 自动同步数据 this.syncQueue = this.syncQueue.then(async () => { await this.syncData(); // 同步完成后触发操作回调 this.triggerCallbacks(operation, entity, data); }); return result;
} catch (error) {
console.error(‘CRUD error:’, error);
// 触发操作失败的回调
this.triggerCallbacks(${operation}_error, entity, {
data,
error: error.message
});
throw error;
}
}
/**
自动同步数据(防止频繁请求)
*/
async syncData() {
if (this.isSyncing) {
this.pendingSync = true;
return;
}
this.isSyncing = true;
try {
await this.fetchAll();
} catch (error) {
console.error(‘Sync failed:’, error);
} finally {
this.isSyncing = false;
// 处理等待中的同步请求 if (this.pendingSync) { this.pendingSync = false; setTimeout(() => this.syncData(), 1000); }
}
}
/**
添加实体
@param {string} entity - 实体名称单数性质
@param {Object} data - 实体数据
*/
async addEntity(entity, data) {
return this.crudOperation(‘add’, entity, data);
}
/**
更新实体
@param {string} entity - 实体名称单数性质
@param {Object} data - 实体数据(必须包含id)
*/
async updateEntity(entity, data) {
return this.crudOperation(‘update’, entity, data);
}
/**
删除实体
@param {string} entity - 实体名称单数性质
@param {number} id - 实体ID
*/
async deleteEntity(entity, id) {
return this.crudOperation(‘delete’, entity, {id});
}
/**
新增方法:手动触发数据刷新
*/
async refreshData() {
return this.syncQueue = this.syncQueue.then(() => this.syncData());
}
/**
获取订单的可用板材信息
@param {number} dingdanId - 订单ID
@returns {Object} 可用板材信息
*/
getAvailableBancaisForOrder(dingdanId) {
const dingdan = this.data.dingdans.find(d => d.id == dingdanId);
if (!dingdan) return {};
return dingdan.availableBancais || {};
}
/**
获取产品的组件列表
@param {number} chanpinId - 产品ID
@returns {Array} 组件列表
*/
getZujiansForChanpin(chanpinId) {
const chanpin = this.data.chanpins.find(c => c.id == chanpinId);
if (!chanpin) return [];
return (chanpin.chanpin_zujian_list || [])
.map(cz => cz.zujian)
.filter(z => z);
}
/**
获取组件的板材信息
@param {number} zujianId - 组件ID
@returns {Array} 板材列表
*/
getBancaisForZujian(zujianId) {
return (this.data.chanpin_zujians || [])
.filter(cz => cz.zujian && cz.zujian.id == zujianId)
.map(cz => cz.bancai)
.filter(b => b);
}
/**
创建进货记录
@param {Object} jinhuoData - 进货数据
@returns {Promise} 操作结果
*/
async createJinhuo(jinhuoData) {
return this.addEntity(‘jinhuo’, jinhuoData);
}
/**
获取订单列表
@returns {Array} 订单列表
*/
getDingdans() {
return this.data.dingdans || [];
}
/**
获取订单的产品列表
@param {number} dingdanId - 订单ID
@returns {Array} 产品列表
*/
getChanpinsForDingdan(dingdanId) {
const dingdan = this.data.dingdans.find(d => d.id == dingdanId);
if (!dingdan) return [];
return (dingdan.dingdan_chanpin_list || [])
.map(dc => dc.chanpin)
.filter(c => c);
}
}
export { DataManager };
// 创建单例实例
//const dataManager = new DataManager(‘http://127.0.0.1:8080/KuCun2’);
//// 初始化时获取所有数据
//dataManager.fetchAll().then(() => {
// console.log(‘Initial data loaded’);
//});
// 导出数据对象,外部可以直接访问 data.bancais, data.dingdans 等
//export const data = dataManager.data;
//// 导出操作方法
//export const addEntity = dataManager.addEntity.bind(dataManager);
//export const updateEntity = dataManager.updateEntity.bind(dataManager);
//export const deleteEntity = dataManager.deleteEntity.bind(dataManager);
//export const fetchAll = dataManager.fetchAll.bind(dataManager);单个添加回调函数中id消失,服务端返回有id浏览器抓取到了
最新发布