Untitled
Anonymous
Plain Text
11/04/2025 12:15 AM
16.3 KB
15
Indexable
Never
<template>
<v-container fluid class="kawara-bg">
<v-card class="control-card">
<v-card-text>
<v-row align="center" dense>
<v-col cols="12" md="4">
<v-file-input v-model="selectedFile" label="Select CSV file...." prepend-inner-icon="mdi-magnify"
append-inner-icon="mdi-folder-open" @click:append-inner="triggerFileSelect" variant="outlined"
hide-details class="search-field" multiple accept=".csv">
<template v-slot:selection="{ fileNames }">
<v-chip v-for="(fileName, index) in fileNames" :key="index" class="mr-2">
{{ fileName }}
</v-chip>
</template>
</v-file-input>
</v-col>
<v-col cols="12" md="8">
<v-btn color="#D4AF37" class="action-btn1" @click="getData">Get</v-btn>
</v-col>
</v-row>
</v-card-text>
</v-card>
<v-card class="data-table-card">
<v-card-title class="title" style="display: flex; justify-content: space-between; align-items: center;">
<span>Kawara Converter Data</span>
<div>
<v-btn color="#57B4BA" size="small" v-tooltip:top="'Import'" @click="importSelected" class="mr-2 action-btn">
<v-icon>mdi-import</v-icon>
</v-btn>
<v-btn color="#8ABB6C" size="small" v-tooltip:top="'Export'" @click="exportSelected" class="action-btn">
<v-icon>mdi-file-export</v-icon>
</v-btn>
</div>
</v-card-title>
<v-data-table show-select item-value="ConstructionCode" v-model="selected" :headers="headers" :items="items"
class="custom-table">
<template v-slot:item.hattyuu="{ item }">
<v-checkbox v-model="item.hattyuu" color="#754E1A"></v-checkbox>
</template>
<template v-slot:item.zairyou="{ item }">
<v-checkbox v-model="item.zairyou" color="#754E1A"></v-checkbox>
</template>
<template v-slot:item.actions="{ item }">
<v-btn icon size="small" v-tooltip:top="'Delete'" @click="deleteItem(item)" class="action-btn">
<v-icon color="#FB4141">mdi-trash-can-outline</v-icon>
</v-btn>
</template>
</v-data-table>
</v-card>
<input type="file" ref="fileInput" @change="handleFileChange" style="display: none" multiple accept=".csv" />
</v-container>
</template>
<script setup>
import { ref } from 'vue';
import Swal from 'sweetalert2';
import axios from 'axios';
const selectedFile = ref([]);
const fileInput = ref(null);
const selected = ref([]);
const headers = ref([
{ title: 'KAWARA CODE', key: 'KawaraConstCode', align: 'center' },
{ title: 'CONSTRUCTION CODE', key: 'ConstructionCode', align: 'center' },
{ title: 'HATTYUU', key: 'hattyuu', align: 'center' },
{ title: 'ZAIRYOU', key: 'zairyou', align: 'center' },
{ title: 'ACTIONS', key: 'actions', align: 'center' },
]);
const items = ref([]);
function parsedRoofSpecificationInfos(csvText) {
let rows = csvText.trim().split(/\r?\n/);
let headerRowIndex = -1;
for (let i = 0; i < rows.length; i++) {
const normalizedRow = rows[i].replace(/\s+/g, '');
if ((normalizedRow.includes('勾配') && normalizedRow.includes('軒の出') && normalizedRow.includes('袖の出'))
) {
headerRowIndex = i;
break;
}
}
if (headerRowIndex === -1) {
console.error('Header row with Japanese headers not found.');
return [];
}
let result = [];
for (let i = headerRowIndex + 1; i < rows.length; i++) {
let values = rows[i].split(',').map(v => v.trim()
.replace(/^"(.*)"$/, '$1') // remove surrounding quotes
.replace(/\\/g, '') // remove backslashes
.replace(/"\"/g, '') // remove backslashes
.replace(/^$/, '') // normalize empty strings (optional)
);
let entry = {};
for (let j = 0; j < rows[i].length; j++) {
entry.Floor = Number(zenkakuToAsciiNumber(values[0].slice(0, -1))) || 0;
entry.RoofConstructionArea = values[1];
entry.ConstructionAreaTsubo = values[2];
entry.RoofArea = values[3];
entry.KawaraArea = values[4];
entry.RoofSlope = values[5];
entry.Nokinode = values[6];
entry.Sodenode = values[7];
}
if (values[0].includes('合 計')) {
break;
}
result.push(entry);
}
return result;
}
function parsedKawaraPickingMaterials(csvText) {
let rows = csvText.trim().split(/\r?\n/);
let headerRowIndex = -1;
for (let i = 0; i < rows.length; i++) {
const normalizedRow = rows[i].replace(/\s+/g, '');
//* FOR ZAIRYOU
if ((normalizedRow.includes('コード') && normalizedRow.includes('項目名') &&
normalizedRow.includes('数量') && normalizedRow.includes('単位')) ||
//* FOR HATTTYUU
(normalizedRow.includes('コード') && normalizedRow.includes('工事名') &&
normalizedRow.includes('数量') && normalizedRow.includes('単位') &&
normalizedRow.includes('単価') && normalizedRow.includes('金額'))
) {
headerRowIndex = i;
break;
}
}
if (headerRowIndex === -1) {
console.error('Header row with Japanese headers not found.');
return [];
}
let result = [];
for (let i = headerRowIndex + 1; i < rows.length; i++) {
let values = rows[i].split(',').map(v => v.trim()
.replace(/^"(.*)"$/, '$1') // remove surrounding quotes
.replace(/\\/g, '') // remove backslashes
.replace(/"\"/g, '') // remove backslashes
.replace(/^$/, '') // normalize empty strings (optional)
);
let entry = {};
for (let j = 0; j < rows[i].length; j++) {
entry.KawaraMaterialCode = values[0];
entry.KawaraMaterialName = values[1];
entry.Quantity = values[2];
entry.UnitName = values[3];
}
result.push(entry);
}
return result;
}
function readCSVFile(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
let csv = e.target.result.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
resolve(csv);
} catch (error) {
reject(error);
}
};
reader.onerror = () => {
reject(new Error('Failed to read file'));
};
reader.readAsText(file, "Shift-JIS");
});
}
function zenkakuToAsciiNumber(str) {
if (typeof str !== 'string') str = String(str);
// Normalize full-width digits U+FF10..U+FF19 to 0..9
const normalized = str.replace(/[\uFF10-\uFF19]/g, ch =>
String(ch.charCodeAt(0) - 0xFF10)
)
// Optional: convert full-width minus/plus and full-width period
.replace(/\uFF0D/g, '-') // - → -
.replace(/\uFF0B/g, '+') // + → +
.replace(/\uFF0E/g, '.'); // . → .
return normalized;
}
async function getData() {
if (selectedFile.value.length === 0) {
console.warn('No file selected');
return;
}
items.value = [];
selected.value = [];
for (const file of selectedFile.value) {
try {
const fileName = file.name;
const [namePrefix, codePart] = fileName.split(/(\d{5}-\d{2})/).filter(Boolean);
if (!namePrefix || !codePart) {
console.error(`Invalid file name: ${fileName}`);
continue;
}
const isZairyou = namePrefix.toLowerCase().includes('zairyou');
const isHattyuu = namePrefix.toLowerCase().includes('hattyuu');
const kawaraCode = codePart;
if (!isZairyou && !isHattyuu) {
console.error(`Invalid file type: ${fileName}`);
continue;
}
const csvContent = await readCSVFile(file);
const parsedRoofSpecificationInfosData = parsedRoofSpecificationInfos(csvContent);
const parsedKawaraPickingMaterialsData = parsedKawaraPickingMaterials(csvContent);
let rows = csvContent.trim().split(/\r?\n/);
let constructionCode = rows.find(item => item.includes('工事名称') || item.includes('工事名'))
.split(',').map(v => v.trim()
.replace(/^"(.*)"$/, '$1')
.replace(/\\/g, '')
.replace(/"\"/g, '')
.replace(/^$/, ''));
//* KAWARA BASIC INFOS ***********************************************************************
let kawaraBasicInfos = rows.find(item => item.includes('品 名') || item.includes('品 名'))
.split(',').map(v => v.trim()
.replace(/^"(.*)"$/, '$1') // remove surrounding quotes
.replace(/\\/g, '') // remove backslashes
.replace(/"\"/g, '') // remove backslashes
.replace(/^$/, ''));
//* ROOF PARTS SPECIFICATION INFOS ***********************************************************
let roofPartsSpecificationInfosIndex = -1;
for (let i = 0; i < rows.length; i++) {
const normalizedRow = rows[i].replace(/\s+/g, '');
if (normalizedRow.includes('軒') && normalizedRow.includes('袖(左)') &&
normalizedRow.includes('袖(右)') && normalizedRow.includes('本棟') &&
normalizedRow.includes('下り棟') && normalizedRow.includes('隅棟')
) {
roofPartsSpecificationInfosIndex = i;
break;
}
}
let roofPartsSpecificationInfos = rows[roofPartsSpecificationInfosIndex + 1].split(',').map(v => v.trim()
.replace(/^"(.*)"$/, '$1') // remove surrounding quotes
.replace(/\\/g, '') // remove backslashes
.replace(/"\"/g, '') // remove backslashes
.replace(/^$/, '') // normalize empty strings (optional)
);
//* ROOF SPECIFICATION INFOS *****************************************************************
let roofSpecificationInfosIndex = -1;
for (let i = 0; i < rows.length; i++) {
const normalizedRow = rows[i].replace(/\s+/g, '');
if (normalizedRow.includes('勾配') && normalizedRow.includes('軒の出') && normalizedRow.includes('袖の出')
) {
roofSpecificationInfosIndex = i;
break;
}
}
let roofSpecificationInfos = rows[roofSpecificationInfosIndex + 1].split(',').map(v => v.trim()
.replace(/^"(.*)"$/, '$1') // remove surrounding quotes
.replace(/\\/g, '') // remove backslashes
.replace(/"\"/g, '') // remove backslashes
.replace(/^$/, '') // normalize empty strings (optional)
);
if (!constructionCode) {
console.error(`Missing construction code in file: ${fileName}`);
continue;
}
const csvType = isHattyuu ? 1 : 2;
const newRow = {
CSVType: csvType,
ConstructionCode: constructionCode[1],
//* KAWARA BASIC INFOS
KawaraConstCode: kawaraCode,
KawaraCategoryName: kawaraBasicInfos[1],
KawaraCategoryColor: kawaraBasicInfos[2],
ImportedFileName: fileName,
//* PICKING KAWARA MATERIALS
PickingKawaraMaterials: parsedKawaraPickingMaterialsData,
//* ROOF SPECIFICATION INFOS
RoofSpecificationInfos: parsedRoofSpecificationInfosData,
//* ROOF PARTS SPECIFICATION INFOS
Noki: roofPartsSpecificationInfos[0] || 0,
SodeLeft: roofPartsSpecificationInfos[1] || 0,
SodeRight: roofPartsSpecificationInfos[2] || 0,
HonMune: roofPartsSpecificationInfos[3] || 0,
KudariMune: roofPartsSpecificationInfos[4] || 0,
KudariMune: roofPartsSpecificationInfos[5] || 0,
SumiMune: roofPartsSpecificationInfos[6] || 0,
KaeshiMune: roofPartsSpecificationInfos[7] || 0,
KatanagareMune: roofPartsSpecificationInfos[8] || 0,
KetaKabe: roofPartsSpecificationInfos[9] || 0,
OriKabe: roofPartsSpecificationInfos[10] || 0,
Yukidome: roofPartsSpecificationInfos[11] || 0,
Tani: roofPartsSpecificationInfos[12] || 0,
MinokouLeft: roofPartsSpecificationInfos[13] || 0,
MinokouRight: roofPartsSpecificationInfos[14] || 0,
Tonemaru: roofPartsSpecificationInfos[15] || 0,
Sodemaru: roofPartsSpecificationInfos[16] || 0,
Kazekiri: roofPartsSpecificationInfos[17] || 0,
SumiMuneNagare: roofPartsSpecificationInfos[18] || 0,
Rokudani: roofPartsSpecificationInfos[19] || 0,
Yamaore: roofPartsSpecificationInfos[20] || 0,
TaniOre: roofPartsSpecificationInfos[21] || 0,
EnchouToi: roofPartsSpecificationInfos[22] || 0,
hattyuu: isHattyuu,
zairyou: isZairyou
};
items.value.push(newRow);
console.log('ITEMS: ', items.value);
} catch (error) {
console.error('Error processing file:', error);
Swal.fire({
icon: 'error',
title: 'File Processing Error',
text: `Could not process file ${file.name}. Check console for details.`
});
}
}
}
function deleteItem(item) {
const index = items.value.findIndex(i => i.ConstructionCode === item.ConstructionCode);
if (index !== -1) {
items.value.splice(index, 1);
const selectedIndex = selected.value.findIndex(s => s === item.ConstructionCode);
if (selectedIndex !== -1) {
selected.value.splice(selectedIndex, 1);
}
}
}
function triggerFileSelect() {
fileInput.value.click();
}
function handleFileChange(event) {
selectedFile.value = Array.from(event.target.files);
}
// *** MODIFIED: This function now only imports the KawaraMaterialCode ***
async function importSelected() {
if (selected.value.length === 0) {
Swal.fire({
icon: 'warning',
title: 'No Selection',
text: 'Please select at least one item to import.',
timer: 3000,
showConfirmButton: false
});
return;
}
try {
Swal.fire({
title: 'Importing...',
html: 'Please wait while we import your data.',
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});
const finalData = items.value.filter((item) => {
for (let code of selected.value) {
if (item.ConstructionCode == code) {
return item;
}
}
});
let importResponse;
try {
importResponse = await axios.post('/api/picking-kawara-materials/import', { data: finalData });
} catch (error) {
console.error('ERROR in STEP 3 (Axios POST):', error);
if (error.response) {
console.error('Server Validation Response Data:', error.response.data);
let errorMessage = `Server error: ${error.response.status} ${error.response.statusText}.`;
const validationErrors = error.response.data.errors;
if (validationErrors) {
errorMessage += `<br><br><strong>Validation Details:</strong><ul>`;
for (const field in validationErrors) {
errorMessage += `<li><strong>${field}</strong>: ${validationErrors[field][0]}</li>`;
}
errorMessage += `</ul>`;
}
throw new Error(errorMessage);
} else if (error.request) {
throw new Error('No response from server. Is it running?');
} else {
throw new Error(`Request setup failed: ${error.message}`);
}
}
if (importResponse.data.success) {
Swal.fire({
icon: 'success', title: 'Import Successful',
text: `${importResponse.data.recordsImported} records imported.`, timer: 3000, showConfirmButton: false
});
} else {
throw new Error(importResponse.data.message || 'Import failed on the server side.');
}
} catch (error) {
console.error('FINAL IMPORT ERROR:', error);
Swal.close();
Swal.fire({ icon: 'error', title: 'Import Failed', html: `<p><strong>${error.message}</strong></p>` });
}
}
function exportSelected() {
if (selected.value.length === 0) {
Swal.fire({
icon: 'warning',
title: 'No Selection',
text: 'Please select at least one item to export.',
timer: 3000,
showConfirmButton: false
});
return;
}
console.log(`Exporting ${selected.value.length} selected items`);
}
</script>
<style scoped>
.action-btn1 {
border-radius: 20px;
}
.kawara-bg {
background: linear-gradient(120deg, #f7f7f6, #e9ecef);
min-height: 100vh;
padding: 20px;
}
.control-card,
.data-table-card {
box-shadow: 0 4px 20px rgba(212, 175, 55, 0.2);
border-radius: 0;
margin-bottom: 20px;
background-color: rgba(255, 255, 255, 0.95);
}
.title {
font-size: 1.2rem;
font-weight: 500;
letter-spacing: 1px;
color: #212529;
text-transform: uppercase;
padding: 16px;
border-bottom: 1px solid rgba(212, 175, 55, 0.3);
}
.search-field {
max-width: 380px;
}
.action-btn {
border-radius: 20px;
}
</style>
Editor is loading...
Leave a Comment