// ==UserScript==
// @name appendSWPORDER
// @namespace https://bbs.tampermonkey.net.cn/
// @version 1.1
// @description 在'换货单'增加功能
// @author fengxia
// @match http://122.13.25.247:8888/sales/swaporder/swapOrderPage.do
// @match http://47.107.106.156:8888/sales/swaporder/swapOrderPage.do
// @match http://47.107.106.156:8888/sales/swaporder/swapOrderPage.do?type=edit&id=*
// @match http://122.13.25.247:8888/sales/swaporder/swapOrderPage.do?type=edit&id=*
// @require https://scriptcat.org/lib/513/2.1.0/ElementGetter.js
// @require https://scriptcat.org/lib/637/1.4.6/ajaxHooker.js
// @grant none
// ==/UserScript==
(function() {
'use strict';
let re_url = /(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}/;
let temp_url = window.location.href;
window.site_url;
window.test = re_url.exec(temp_url)[0];
// unsafeWindow.addEventListener('keydown', (evt)=>{
// console.log('evt',evt);
// });
ajaxHooker.hook(request => {
// console.log(request.url)
if (request.url === 'sales/getGoodsDetail.do') {
request.response = res => {
let json_array,products_id
try {
json_array =((JSON.parse(res.responseText)).detail)['goodsInfo'];
// console.log(json_array.id)
products_id =json_array.id;
}
catch(err){
console.log(err)
}
let customer_id
let select_year = $('.new_div .tabs-selected span').html()
// console.log(customer_id?$('#sales-customer-hidden-swapOrderAddPage').val():document.querySelector('[id^="sales-customer-showid"] a').innerText,products_id,select_year )
queryHistoryPrice(customer_id?$('#sales-customer-hidden-swapOrderAddPage').val():document.querySelector('[id^="sales-customer-showid"] a').innerText,products_id,select_year )
};
}
});
const eg = elmGetter;
elmGetter.each('#sales-form-swapOrderDetailAddPage', document, reply => {
reply.addEventListener("keydown",checkKey);
var targetDiv = $('div.panel.window').filter("[style*='display: block;']");
const div_top = targetDiv.css("top")
const div_index = targetDiv.css("z-index")
// console.log(div_index);
var newDiv =`
`
const currentYear = new Date().getFullYear();
const startYear = (currentYear - 5 < 2022) ? 2022 : (currentYear - 5);
// 生成年份的li元素
var tab_div = ""
var table_div=""
for (let year = startYear; year <= currentYear; year++) {
// 创建新的li元素
let liClass = ""; // li的class属性初始化为
let divstyle="display: none"
if (year === startYear) {
liClass += "tabs-last"; // 第一个li添加tabs-last类,第一个是2022年
}
if (year === currentYear) {
liClass += " tabs-first tabs-selected"; // 最后一个li添加tabs-first类
divstyle = "display: block"
}
tab_div +=`- ${year}
`;
table_div +=``;
}
newDiv=newDiv+tab_div+'
'+table_div+'
'
targetDiv.before(newDiv);//添加新div
var remove_div = $(".new_div");
var remove_second_div = $(".second_div")
targetDiv.find(".panel-tool-close").on('click', function() {//添加一个关闭窗口的函数
remove_div.remove(); // 移除新DIV
remove_second_div.remove();
});
$('.new_div .tabs li').on('click', function() {//给新的分页添加切换效果
// 检查当前选中的标签
if (!$(this).hasClass('tabs-selected')) {
var index = $(this).index();
var div_table = $('.new_div .panel-body-noborder.layout-body');
div_table.css("display", "none");
div_table.eq(index).css("display", "block");
// 移除其他标签的选中状态
$('.tabs li').removeClass('tabs-selected');
// 添加选中状态到当前标签
$(this).addClass('tabs-selected');
let products_id = $("input[name=goodsid]").val()
if (products_id!=''){
let customer_id
let select_year = $('.new_div .tabs-selected span').html()
console.log(customer_id?$('#sales-customer-hidden-swapOrderAddPage').val():document.querySelector('[id^="sales-customer-showid"] a').innerText,products_id,select_year)
queryHistoryPrice(customer_id?$('#sales-customer-hidden-swapOrderAddPage').val():document.querySelector('[id^="sales-customer-showid"] a').innerText,products_id,select_year )
}
}});
return true;
});
})();
function add(go,price) { //添加新数据确定后操作,
var flag = true;
if (flag == false) {
return false;
}
var form = $("#sales-form-swapOrderDetailAddPage").serializeJSON();
var goodsJson = $("#sales-goodsId-swapOrderDetailAddPage").goodsWidget('getObject');
form.goodsInfo = goodsJson;
var customer = $("#sales-customer-swapOrderAddPage-hidden").val();
var f_t = Number(form.taxprice)
var f_b = Number(form.boxnum)
var f_u = Number(form.unitnum)
console.log(form.taxamount)
if (price>0){
form.taxprice = price
form.fixnum = f_u * -1
form.unitnum = form.fixnum
form.boxprice = price*f_b
form.taxamount = form.unitnum * price
}
else{
form.fixnum = form.unitnum
form.boxprice = form.taxprice * f_b
form.taxamount = form.unitnum * form.taxprice
}
if (form.overnum != 0) {
if (form.auxnum == null || form.auxnum == "") {
form.auxnum = 0;
}
form.auxnumdetail = form.auxnum + form.auxunitname + form.overnum + form.unitname;
} else {
form.auxnumdetail = form.auxnum + form.auxunitname;
}
var rowIndex = 0;
var rows = $wareList.datagrid('getRows');
var updateFlag = false;
for (var i = 0; i < rows.length; i++) {
var rowJson = rows[i];
if (rowJson.goodsid == undefined && rowJson.brandid == undefined) {
rowIndex = i;
break;
}
}
console.log(form)
if (rowIndex == rows.length - 1) {
$wareList.datagrid('appendRow', {}); //如果是最后一行则添加一新行
}
if (insertIndex == undefined) {
$wareList.datagrid('updateRow', {index: rowIndex, row: form}); //将数据更新到列表中
}
else {
$wareList.datagrid('insertRow', {index: insertIndex + 1, row: form});
insertIndex = undefined;
}
if (go && price>0) { //go为true确定并继续添加一条
$("#sales-form-swapOrderDetailAddPage").form("clear");
$("input[name=deliverydate]").val(deliverydate);
$("#sales-deliverytype-swapOrderDetailAddPage").val("0");
}
// else { //否则直接关闭
// $("#sales-dialog-swapOrderAddPage-content").dialog('close', true)
// }
countTotal(); //第添加一条商品明细计算一次合计
}
function getIntervalDate(year){
let start_date,end_date
if (year){
start_date = `${year}-01-01`;
end_date = `${year}-12-31`;
}
else if(typeof year == 'undefined') {
let date = new Date();
end_date = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,"0")}-${date.getDate().toString().padStart(2,'0')}`;
date.setDate(date.getDate()-90);
start_date = `${date.getFullYear()}-${date.getMonth().toString().padStart(2,"0")}-${date.getDate().toString().padStart(2,'0')}`;
}
let query_date ={
'start_date':start_date,
'end_date':end_date
}
return query_date
}
// 查询历史旧价
async function queryHistoryPrice(customer,products,year){
let user = new Object();
let list_order = [];
let returns_order=await showCustomerSalesFlowList(customer,products,year);
// let sale_order=await showSalesOrderTrackReportData(customer,products,year);
// console.log(sa2)
for (let row_num in returns_order){
user = { // 一个对象
goodsid:returns_order[row_num].goodsid,
date: returns_order[row_num].businessdate,
unitnum:returns_order[row_num].enternum===0?returns_order[row_num].outnum:returns_order[row_num].enternum*-1,
price:returns_order[row_num].price,
};
list_order.push(user)
}
// for (let row_num in sale_order){
// if (sale_order[row_num].ordernum > 0) {
// user = { // 一个对象
// goodsid:sale_order[row_num].goodsid,
// date: sale_order[row_num].businessdate,
// unitnum: sale_order[row_num].initsendnum,
// price: sale_order[row_num].dispatchprice,
// sendnum: sale_order[row_num].sendnum === undefined?'未出库':sale_order[row_num].sendnum,
// checkprice: sale_order[row_num].checkprice === undefined?'未验收':sale_order[row_num].checkprice,
// };
// list_order.push(user)
// }
// }
// list_order.sort(function(a,b){
// // Turn your strings into dates, and then subtract them
// // to get a value that is either negative, positive, or zero.
// return new Date(a.date)-new Date(b.date);
// });
//console.log(list_order)
//console.log(Object.keys(list_order).length === 0)
let tr_html = '';
let x = 1; //用x取余来做斑马格
for (let row_num in list_order){
tr_html = tr_html+`
${list_order[row_num].goodsid} |
${list_order[row_num].date} |
${list_order[row_num].unitnum} |
${list_order[row_num].price} |
`;
x=++x;
}
if (Object.keys(list_order).length === 0){tr_html=`${products}无销售`}
let table_html = `
'
let div = $('.panel-body-noborder.layout-body.'+year);
$(div).html(table_html);
countunitnum(list_order)
}
// module 根据出入库流水账查询销售退货单数据
function showCustomerSalesFlowList(customer,products,year){
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
let query_date = getIntervalDate(year);
// let url = new URL(`http://${window.test}:8888/report/finance/showCustomerSalesFlowList.do`);
let url = new URL(`http://${window.test}:8888/report/storage/showInOutFlowListData.do`);
url.searchParams.set("businessdate1", query_date.start_date);
url.searchParams.set("businessdate2", query_date.end_date);
url.searchParams.set("id", "");
url.searchParams.set("brandid", "");
url.searchParams.set("goodsid", products);
url.searchParams.set("billtype", ["1","5"]);
url.searchParams.set("supplierid", "");
url.searchParams.set("customerid", customer);
url.searchParams.set("storageid", "");
url.searchParams.set("customersort","");
url.searchParams.set("audituserid", "");
url.searchParams.set("page", "1");
url.searchParams.set("rows", "1000");
url.searchParams.set("sort", "businessdate");
url.searchParams.set("order", "desc");
// 2. 配置它:从 URL /article/.../load GET-request
xhr.open('post', url);
// 3. 通过网络发送请求
xhr.send();
// 4. 当接收到响应后,将调用此函数
xhr.onload = function() {
if (xhr.status != 200) { // 分析响应的 HTTP 状态
alert(`Error ${xhr.status}: ${xhr.statusText}`); // 例如 404: Not Found
} else { // 显示结果
let xhrString = JSON.parse(xhr.response)
// console.log("2");
resolve(xhrString.rows)
// alert(`Done, got ${xhr.response.length} bytes`); // response 是服务器响应
}
};
xhr.onerror = function() {
alert("Request failed");
};
})
}
// 通过查询订单追踪明细表获取订单数据
function showSalesOrderTrackReportData(customer,products,year){
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
let url = new URL(`http://${window.test}:8888/report/sales/showSalesOrderTrackReportData.do`);
let query_date = getIntervalDate(year);
url.searchParams.set("businessdate1", query_date.start_date);
url.searchParams.set("businessdate2", query_date.end_date);
url.searchParams.set("id","");
url.searchParams.set("brandid","");
url.searchParams.set("goodsid", products);
url.searchParams.set("customerid",customer);
url.searchParams.set("checkstatus","");
url.searchParams.set("salesuser","");
url.searchParams.set("pcustomerid","");
url.searchParams.set("indooruserid","");
url.searchParams.set("sourceid","");
url.searchParams.set("goodssort","");
// url.searchParams.set("oldFromData", {"businessdate1":query_date.start_date,"businessdate2":query_date.end_date,"id":"","brandid":"","goodsid":"","customerid":"","checkstatus":"","salesuser":"","pcustomerid":"","indooruserid":"","sourceid":"","goodssort":""});
url.searchParams.set("page", "1");
url.searchParams.set("rows", "1000");
url.searchParams.set("sort", "businessdate");
url.searchParams.set("order", "asc");
// 2. 配置它:从 URL /article/.../load GET-request
xhr.open('post', url);
// 3. 通过网络发送请求
xhr.send();
// 4. 当接收到响应后,将调用此函数
xhr.onload = function() {
if (xhr.status != 200) { // 分析响应的 HTTP 状态
alert(`Error ${xhr.status}: ${xhr.statusText}`); // 例如 404: Not Found
} else { // 显示结果
let xhrString = JSON.parse(xhr.response)
// console.log("1");
resolve(xhrString.rows)
// alert(`Done, got ${xhr.response.length} bytes`); // response 是服务器响应
}
};
xhr.onerror = function() {
alert("Request failed");
};
})
}
function checkKey(e) {
if (e.key == '*') {
e.preventDefault();
let price = prompt("请输入价格", ""); //输入价格
let price_number = Number(price);
if (price != '' && price_number){
console.log('ok')
add(true,-1)
add(true,price_number)
}
}
}
function countTotal() { //计算合计
var checkrows = $("#sales-datagrid-swapOrderAddPage").datagrid('getChecked');
var usablenum = 0;
var unitnum = 0;
var taxamount = 0;
var notaxamount = 0;
var tax = 0;
var totalbox = 0;
var totalboxweight = 0;
var totalboxvolume = 0;
for (var i = 0; i < checkrows.length; i++) {
usablenum += Number(checkrows[i].usablenum == undefined ? 0 : checkrows[i].usablenum);
unitnum += Number(checkrows[i].unitnum == undefined ? 0 : checkrows[i].unitnum);
taxamount += Number(checkrows[i].taxamount == undefined ? 0 : checkrows[i].taxamount);
notaxamount += Number(checkrows[i].notaxamount == undefined ? 0 : checkrows[i].notaxamount);
tax += Number(checkrows[i].tax == undefined ? 0 : checkrows[i].tax);
totalbox += Number(checkrows[i].totalbox == undefined ? 0 : checkrows[i].totalbox);
totalboxweight += Number(checkrows[i].totalboxweight == undefined ? 0 : checkrows[i].totalboxweight);
totalboxvolume += Number(checkrows[i].totalboxvolume == undefined ? 0 : checkrows[i].totalboxvolume);
}
totalboxweight = formatterMoney(totalboxweight);
totalboxweight = formatterMoney(totalboxweight);
totalbox=totalbox.toFixed(2);
var foot = [{
goodsid: '选中合计',
usablenum: usablenum,
unitnum: unitnum,
taxamount: taxamount,
notaxamount: notaxamount,
tax: tax,
auxnumdetail: totalbox + "箱",
totalboxvolume: totalboxvolume,
totalboxweight: totalboxweight
}];
//合计
var rows = $("#sales-datagrid-swapOrderAddPage").datagrid('getRows');
var usablenumSum = 0;
var unitnumSum = 0;
var taxamountSum = 0;
var notaxamountSum = 0;
var taxSum = 0;
var totalboxSum = 0;
var totalboxweightSum = 0;
var totalboxvolumeSum = 0;
for (var i = 0; i < rows.length; i++) {
usablenumSum += Number(rows[i].usablenum == undefined ? 0 : rows[i].usablenum);
unitnumSum += Number(rows[i].unitnum == undefined ? 0 : rows[i].unitnum);
taxamountSum += Number(rows[i].taxamount == undefined ? 0 : rows[i].taxamount);
notaxamountSum += Number(rows[i].notaxamount == undefined ? 0 : rows[i].notaxamount);
taxSum += Number(rows[i].tax == undefined ? 0 : rows[i].tax);
totalboxSum += Number(rows[i].totalbox == undefined ? 0 : rows[i].totalbox);
totalboxweightSum += Number(rows[i].totalboxweight == undefined ? 0 : rows[i].totalboxweight);
totalboxvolumeSum += Number(rows[i].totalboxvolume == undefined ? 0 : rows[i].totalboxvolume);
}
totalboxSum = formatterMoney(totalboxSum);
var footSum = {
goodsid: '合计',
usablenum: usablenumSum,
unitnum: Number(unitnumSum.toFixed()),
taxamount: taxamountSum,
notaxamount: notaxamountSum,
tax: taxSum,
auxnumdetail: totalboxSum + "箱",
totalboxvolume: totalboxvolumeSum,
totalboxweight: totalboxweightSum
};
foot.push(footSum);
$("#sales-datagrid-swapOrderAddPage").datagrid('reloadFooter', foot);
}
function countunitnum(data){
const amountGroups = {};
// 2. 遍历所有行,计算金额并分组
data.forEach(item => {
// 假设item有price和quantity属性
const quantity = item.unitnum;
const amount = item.price;
// 按金额分组并累加数量
if (!amountGroups[amount]) {
amountGroups[amount] = 0;
}
amountGroups[amount] += quantity;
});
let result = "不同单价的数量总和:
";
for (const [amount, totalQuantity] of Object.entries(amountGroups)) {
result += `单价 ${amount}: 数量总和 = ${totalQuantity}
`;
}
$('#second_swp').html(result);
// 4. 显示结果
// console.log(result);
}