2173 lines
72 KiB
HTML
2173 lines
72 KiB
HTML
<!doctype html>
|
||
<html lang="ja">
|
||
<head>
|
||
<meta charset="UTF-8" />
|
||
<script src="js/auth.js"></script>
|
||
<title>仕訳入力</title>
|
||
<style>
|
||
body {
|
||
font-family: sans-serif;
|
||
margin: 24px;
|
||
}
|
||
h2 {
|
||
margin: 0 0 12px;
|
||
}
|
||
table {
|
||
border-collapse: collapse;
|
||
width: 100%;
|
||
margin-top: 12px;
|
||
}
|
||
th,
|
||
td {
|
||
border: 1px solid #ccc;
|
||
padding: 6px;
|
||
text-align: center;
|
||
}
|
||
th {
|
||
background: #f5f5f5;
|
||
}
|
||
input,
|
||
select,
|
||
button {
|
||
padding: 6px;
|
||
}
|
||
.right {
|
||
text-align: right;
|
||
}
|
||
.row {
|
||
margin: 8px 0;
|
||
display: flex;
|
||
gap: 16px;
|
||
align-items: center;
|
||
}
|
||
.row label {
|
||
min-width: 120px;
|
||
}
|
||
.search-form {
|
||
background: #f9f9f9;
|
||
border: 1px solid #e0e0e0;
|
||
border-radius: 6px;
|
||
padding: 20px;
|
||
margin: 16px 0;
|
||
}
|
||
.search-form-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(2, 1fr);
|
||
gap: 20px 30px;
|
||
margin-bottom: 16px;
|
||
}
|
||
.search-form-row {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
}
|
||
.search-form-row label {
|
||
min-width: 100px;
|
||
font-weight: 500;
|
||
color: #333;
|
||
}
|
||
.search-form-row input,
|
||
.search-form-row select {
|
||
flex: 1;
|
||
padding: 8px;
|
||
border: 1px solid #ccc;
|
||
border-radius: 4px;
|
||
font-size: 14px;
|
||
}
|
||
.search-form-row input:focus,
|
||
.search-form-row select:focus {
|
||
outline: none;
|
||
border-color: #4caf50;
|
||
box-shadow: 0 0 4px rgba(76, 175, 80, 0.3);
|
||
}
|
||
.search-form-row-full {
|
||
grid-column: 1 / -1;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
}
|
||
.search-buttons {
|
||
display: flex;
|
||
gap: 8px;
|
||
justify-content: flex-start;
|
||
margin-top: 8px;
|
||
}
|
||
.search-buttons button {
|
||
padding: 8px 20px;
|
||
border: none;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
font-weight: 500;
|
||
}
|
||
.search-buttons button:first-child {
|
||
background: #4caf50;
|
||
color: white;
|
||
}
|
||
.search-buttons button:first-child:hover {
|
||
background: #45a049;
|
||
}
|
||
.search-buttons button:last-child {
|
||
background: white;
|
||
color: #2196f3;
|
||
border: 1px solid #2196f3;
|
||
}
|
||
.search-buttons button:last-child:hover {
|
||
background: #f0f8ff;
|
||
}
|
||
.tax-row {
|
||
background: #f0f8ff;
|
||
}
|
||
.print-header {
|
||
display: none;
|
||
}
|
||
.page-break {
|
||
page-break-before: always;
|
||
}
|
||
.page-number {
|
||
display: none;
|
||
}
|
||
@media print {
|
||
@page {
|
||
margin: 20mm 20mm 25mm 20mm;
|
||
@bottom-center {
|
||
content: "ページ " counter(page);
|
||
font-size: 0.75em;
|
||
}
|
||
}
|
||
body * {
|
||
visibility: hidden;
|
||
}
|
||
#printArea,
|
||
#printArea * {
|
||
visibility: visible;
|
||
}
|
||
#printArea {
|
||
position: absolute;
|
||
left: 0;
|
||
top: 0;
|
||
width: 100%;
|
||
}
|
||
button,
|
||
.no-print {
|
||
display: none !important;
|
||
}
|
||
.print-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
margin-bottom: 8px;
|
||
font-size: 0.9em;
|
||
padding-bottom: 4px;
|
||
}
|
||
.print-header-left {
|
||
text-align: left;
|
||
}
|
||
.print-header-right {
|
||
text-align: right;
|
||
}
|
||
.page-number {
|
||
display: none !important;
|
||
}
|
||
#printArea table {
|
||
font-size: 0.85em;
|
||
}
|
||
#printArea th,
|
||
#printArea td {
|
||
padding: 3px 4px;
|
||
}
|
||
#printArea h3 {
|
||
font-size: 1.1em;
|
||
margin-bottom: 6px;
|
||
}
|
||
thead {
|
||
display: table-header-group;
|
||
}
|
||
}
|
||
|
||
/* 账户搜索下拉框相关样式 */
|
||
.account-search-container {
|
||
position: relative;
|
||
width: 100%;
|
||
}
|
||
|
||
.account-search-input {
|
||
width: 100%;
|
||
padding: 6px !important;
|
||
border: 1px solid #ccc;
|
||
border-radius: 4px;
|
||
font-size: 14px;
|
||
box-sizing: border-box;
|
||
}
|
||
|
||
.account-search-input:focus {
|
||
outline: none;
|
||
border-color: #4caf50;
|
||
box-shadow: 0 0 4px rgba(76, 175, 80, 0.3);
|
||
}
|
||
|
||
.account-dropdown {
|
||
position: absolute;
|
||
top: 100%;
|
||
left: 0;
|
||
right: 0;
|
||
background: white;
|
||
border: 1px solid #ccc;
|
||
border-top: none;
|
||
border-radius: 0 0 4px 4px;
|
||
max-height: 200px;
|
||
overflow-y: auto;
|
||
z-index: 1000;
|
||
display: none;
|
||
}
|
||
|
||
.account-dropdown.active {
|
||
display: block;
|
||
}
|
||
|
||
.account-option {
|
||
padding: 8px 12px;
|
||
cursor: pointer;
|
||
border-bottom: 1px solid #f0f0f0;
|
||
font-size: 14px;
|
||
text-align: left;
|
||
display: block;
|
||
width: 100%;
|
||
}
|
||
|
||
.account-option:hover,
|
||
.account-option.selected {
|
||
background-color: #e3f2fd;
|
||
}
|
||
|
||
.account-option-strong {
|
||
font-weight: bold;
|
||
color: #333;
|
||
display: block;
|
||
}
|
||
|
||
.account-option-light {
|
||
color: #999;
|
||
font-size: 12px;
|
||
display: block;
|
||
}
|
||
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<button
|
||
onclick="location.href = 'index.html'"
|
||
class="back-button"
|
||
style="
|
||
margin: 0 0 20px 0;
|
||
padding: 8px 16px;
|
||
background: #007bff;
|
||
color: white;
|
||
border: none;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
"
|
||
>
|
||
← 首ページに戻る
|
||
</button>
|
||
<h2>仕訳入力</h2>
|
||
|
||
<div class="row">
|
||
<label>仕訳日</label>
|
||
<input
|
||
type="date"
|
||
id="entryDate"
|
||
min="1900-01-01"
|
||
max="2099-12-31"
|
||
onchange="onEntryDateChanged()"
|
||
/>
|
||
</div>
|
||
|
||
<div class="row">
|
||
<label>摘要</label>
|
||
<input
|
||
type="text"
|
||
id="description"
|
||
list="descriptionHistory"
|
||
style="flex: 3; min-width: 600px"
|
||
placeholder="例:売上入金/経費支払 など"
|
||
/>
|
||
<datalist id="descriptionHistory"></datalist>
|
||
</div>
|
||
|
||
<div class="row">
|
||
<label>仮払消費税等 勘定</label>
|
||
<select id="taxPaidSelect"></select>
|
||
|
||
<label>仮受消費税等 勘定</label>
|
||
<select id="taxReceivedSelect"></select>
|
||
</div>
|
||
<div style="margin-bottom: 10px">
|
||
<label>消費税 端数処理:</label>
|
||
<select id="roundingMode">
|
||
<option value="floor">切捨て</option>
|
||
<option value="round">四捨五入</option>
|
||
<option value="ceil">切上げ</option>
|
||
</select>
|
||
</div>
|
||
|
||
<table id="linesTable">
|
||
<thead>
|
||
<tr>
|
||
<th>科目</th>
|
||
<th>借方</th>
|
||
<th>貸方</th>
|
||
<th>税区分</th>
|
||
<th>税方向</th>
|
||
<th>操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody></tbody>
|
||
</table>
|
||
|
||
<div
|
||
style="
|
||
margin-top: 10px;
|
||
padding: 10px;
|
||
background: #f9f9f9;
|
||
border: 1px solid #ddd;
|
||
display: flex;
|
||
gap: 40px;
|
||
font-weight: bold;
|
||
"
|
||
>
|
||
<div>
|
||
<label>借方合計:</label>
|
||
<span id="totalDebit" style="color: #0066cc; font-size: 16px">0</span>
|
||
円
|
||
</div>
|
||
<div>
|
||
<label>貸方合計:</label>
|
||
<span id="totalCredit" style="color: #cc0000; font-size: 16px">0</span>
|
||
円
|
||
</div>
|
||
<div
|
||
id="balanceStatus"
|
||
style="margin-left: auto; padding: 4px 12px; border-radius: 4px"
|
||
></div>
|
||
</div>
|
||
|
||
<div style="margin-top: 10px; display: flex; gap: 8px; align-items: center">
|
||
<button onclick="addRow()">+ 行追加</button>
|
||
<button onclick="submitJournal()">登録</button>
|
||
<label
|
||
style="
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
margin-left: 20px;
|
||
cursor: pointer;
|
||
"
|
||
>
|
||
<input type="checkbox" id="keepDetailsAfterSubmit" />
|
||
<span style="font-size: 14px">登録後に明細を保持する</span>
|
||
</label>
|
||
</div>
|
||
|
||
<hr style="margin: 40px 0; border: none; border-top: 2px solid #ddd" />
|
||
|
||
<!-- 月次锁定管理(折叠式) -->
|
||
<details style="margin: 16px 0">
|
||
<summary
|
||
style="
|
||
cursor: pointer;
|
||
font-size: 18px;
|
||
font-weight: bold;
|
||
padding: 12px;
|
||
background: #f5f5f5;
|
||
border-radius: 4px;
|
||
user-select: none;
|
||
"
|
||
>
|
||
▶ 月次锁定管理
|
||
</summary>
|
||
|
||
<div
|
||
style="
|
||
padding: 16px;
|
||
background: #fafafa;
|
||
border-radius: 4px;
|
||
margin-top: 8px;
|
||
"
|
||
>
|
||
<div style="margin-bottom: 8px">
|
||
<label>年度:</label>
|
||
<input
|
||
type="number"
|
||
id="lockYear"
|
||
value="2025"
|
||
min="1900"
|
||
max="2999"
|
||
style="width: 80px"
|
||
/>
|
||
|
||
<label>月份:</label>
|
||
<input
|
||
type="number"
|
||
id="lockMonth"
|
||
min="1"
|
||
max="12"
|
||
value="6"
|
||
style="width: 60px"
|
||
/>
|
||
</div>
|
||
|
||
<button onclick="lockMonth()">🔒 锁定</button>
|
||
<button onclick="unlockMonth()">🔓 解锁</button>
|
||
|
||
<div id="lockResult" style="margin-top: 10px; color: #333"></div>
|
||
|
||
<div style="margin-top: 12px">
|
||
<button onclick="refreshMonthLocks()">🔄 刷新锁定列表</button>
|
||
<pre id="lockList" style="background: #f7f7f7; padding: 8px"></pre>
|
||
</div>
|
||
</div>
|
||
</details>
|
||
|
||
<div
|
||
id="monthLockBanner"
|
||
style="
|
||
display: none;
|
||
margin: 8px 0;
|
||
padding: 6px 10px;
|
||
background: #ffecec;
|
||
border: 1px solid #ffaaaa;
|
||
color: #a00000;
|
||
"
|
||
>
|
||
🔒 该月份已锁定,不能编辑仕訳
|
||
</div>
|
||
|
||
<!-- ========================================
|
||
仕訳検索セクション(journal-list.htmlから統合)
|
||
======================================== -->
|
||
<hr style="margin: 40px 0; border: none; border-top: 2px solid #ddd" />
|
||
|
||
<h2>仕訳検索</h2>
|
||
|
||
<div class="search-form">
|
||
<div class="search-form-grid">
|
||
<div class="search-form-row">
|
||
<label>期間</label>
|
||
<div style="display: flex; gap: 8px; align-items: center; flex: 1">
|
||
<input
|
||
type="date"
|
||
id="searchFromDate"
|
||
min="1900-01-01"
|
||
max="2099-12-31"
|
||
/>
|
||
<span style="color: #999">~</span>
|
||
<input
|
||
type="date"
|
||
id="searchToDate"
|
||
min="1900-01-01"
|
||
max="2099-12-31"
|
||
/>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="search-form-row">
|
||
<label>科目</label>
|
||
<div class="account-search-container">
|
||
<input
|
||
type="text"
|
||
id="searchAccountInput"
|
||
class="account-search-input"
|
||
placeholder="科目を入力・検索"
|
||
autocomplete="off" />
|
||
<div class="account-dropdown"></div>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="search-form-row" style="grid-column: 1 / -1">
|
||
<label>摘要</label>
|
||
<input type="text" id="searchKeyword" />
|
||
</div>
|
||
|
||
<div class="search-form-row">
|
||
<label>方向</label>
|
||
<select id="searchAccountSide">
|
||
<option value="">-- すべて --</option>
|
||
<option value="debit">借方</option>
|
||
<option value="credit">貸方</option>
|
||
</select>
|
||
</div>
|
||
|
||
<div class="search-form-row">
|
||
<label style="min-width: auto">
|
||
<input
|
||
type="checkbox"
|
||
id="searchIncludeHistory"
|
||
style="margin-right: 6px"
|
||
/>
|
||
修正履歴を含む
|
||
</label>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="search-buttons">
|
||
<button onclick="searchJournals()">🔍 検索</button>
|
||
<button onclick="printSearchResults()">🖨️ 印刷</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="printArea"></div>
|
||
|
||
<script>
|
||
const API = "";
|
||
|
||
// 千分位カンマフォーマット関数
|
||
function formatNumberInput(input) {
|
||
let value = input.value.replace(/,/g, ""); // 既存のカンマを削除
|
||
if (value === "" || isNaN(value)) {
|
||
input.value = "";
|
||
return;
|
||
}
|
||
// 数値をカンマ区切りに変換
|
||
input.value = Number(value).toLocaleString();
|
||
}
|
||
|
||
let accounts = [];
|
||
|
||
const ACCOUNT_GROUPS = [
|
||
// 資産の部
|
||
{
|
||
label: "現金・預金",
|
||
codes: ["101", "102", "103", "104", "105"],
|
||
},
|
||
{
|
||
label: "売上債権",
|
||
codes: ["201", "202"],
|
||
},
|
||
{
|
||
label: "有価証券",
|
||
codes: ["301"],
|
||
},
|
||
{
|
||
label: "棚卸資産",
|
||
codes: ["210"],
|
||
},
|
||
{
|
||
label: "他流動資産",
|
||
codes: ["203", "204", "205", "206", "207", "208"],
|
||
},
|
||
{
|
||
label: "有形固定資産",
|
||
codes: ["401", "402", "403", "404", "405", "406", "407"],
|
||
},
|
||
{
|
||
label: "無形固定資産",
|
||
codes: ["408"],
|
||
},
|
||
{
|
||
label: "投資その他資産",
|
||
codes: ["410"],
|
||
},
|
||
// 負債の部
|
||
{
|
||
label: "仕入債務",
|
||
codes: ["501"],
|
||
},
|
||
{
|
||
label: "その他流動負債",
|
||
codes: ["502", "503", "504", "505", "506", "507", "508"],
|
||
},
|
||
{
|
||
label: "固定負債",
|
||
codes: ["509"],
|
||
},
|
||
// 資本の部
|
||
{
|
||
label: "資本金",
|
||
codes: ["601"],
|
||
},
|
||
{
|
||
label: "利益剰余金",
|
||
codes: ["602"],
|
||
},
|
||
// 収益・費用
|
||
{
|
||
label: "収益",
|
||
codes: ["701", "702", "703", "704", "705"],
|
||
},
|
||
{
|
||
label: "費用",
|
||
codes: [
|
||
"801",
|
||
"802",
|
||
"803",
|
||
"804",
|
||
"805",
|
||
"806",
|
||
"807",
|
||
"808",
|
||
"809",
|
||
"810",
|
||
"811",
|
||
"812",
|
||
"813",
|
||
"814",
|
||
"815",
|
||
"816",
|
||
"817",
|
||
"818",
|
||
"819",
|
||
"820",
|
||
],
|
||
},
|
||
];
|
||
|
||
let taxPaidAccounts = [];
|
||
let taxReceivedAccounts = [];
|
||
let rowSeq = 0; // 行ID計数器
|
||
|
||
// ========================================
|
||
// 账户搜索功能
|
||
// ========================================
|
||
function setupAccountSearch(inputElement, row) {
|
||
const container = inputElement.closest(".account-search-container");
|
||
const dropdown = container.querySelector(".account-dropdown");
|
||
|
||
inputElement.addEventListener("input", (e) => {
|
||
const searchText = e.target.value.toLowerCase().trim();
|
||
|
||
if (!searchText) {
|
||
dropdown.classList.remove("active");
|
||
return;
|
||
}
|
||
|
||
// 过滤账户
|
||
const filtered = accounts.filter((acc) => {
|
||
const code = acc.account_code.toLowerCase();
|
||
const name = acc.account_name.toLowerCase();
|
||
return code.includes(searchText) || name.includes(searchText);
|
||
});
|
||
|
||
// 生成下拉建议
|
||
dropdown.innerHTML = "";
|
||
if (filtered.length === 0) {
|
||
dropdown.innerHTML = `<div style="padding: 8px 12px; color: #999;">該当する科目がありません</div>`;
|
||
} else {
|
||
filtered.slice(0, 20).forEach((acc) => {
|
||
const option = document.createElement("div");
|
||
option.className = "account-option";
|
||
option.innerHTML = `
|
||
<span class="account-option-strong">${acc.account_code}</span>
|
||
<span class="account-option-light">${acc.account_name}</span>
|
||
`;
|
||
option.addEventListener("click", () => {
|
||
inputElement.value = `${acc.account_code} ${acc.account_name}`;
|
||
inputElement.dataset.accountId = acc.account_id;
|
||
dropdown.classList.remove("active");
|
||
saveAccountToRecent(acc.account_id);
|
||
});
|
||
dropdown.appendChild(option);
|
||
});
|
||
}
|
||
|
||
dropdown.classList.add("active");
|
||
});
|
||
|
||
// クリック以外の場所のドロップダウンを非表示
|
||
document.addEventListener("click", (e) => {
|
||
if (!container.contains(e.target)) {
|
||
dropdown.classList.remove("active");
|
||
}
|
||
});
|
||
|
||
// フォーカス時にドロップダウンを表示(既存値がある場合)
|
||
inputElement.addEventListener("focus", () => {
|
||
if (inputElement.value) {
|
||
dropdown.classList.add("active");
|
||
}
|
||
});
|
||
}
|
||
|
||
// getSelectedAccountId 用来获取当前行选中的账户ID
|
||
function getSelectedAccountIdFromInput(inputElement) {
|
||
return inputElement.dataset.accountId || null;
|
||
}
|
||
|
||
// 建立一个全局函数来获取行中的账户ID
|
||
window.getAccountIdFromRow = function(row) {
|
||
const input = row.querySelector(".account-search-input");
|
||
return input.dataset.accountId || null;
|
||
};
|
||
|
||
// 建立一个全局函数来获取行中的账户文本
|
||
window.getAccountTextFromRow = function(row) {
|
||
const input = row.querySelector(".account-search-input");
|
||
return input.value || "";
|
||
};
|
||
|
||
// ========================================
|
||
// 初期化
|
||
// ========================================
|
||
async function init() {
|
||
console.log("🔧 init() 开始...");
|
||
const res = await fetch(`${API}/accounts`);
|
||
if (!res.ok) {
|
||
console.error("❌ API 错误:", res.status);
|
||
alert("科目一覧の取得に失敗しました");
|
||
return;
|
||
}
|
||
|
||
const data = await res.json();
|
||
console.log("✓ 获取到科目数据:", data);
|
||
|
||
// 🔴 ここ重要:items がある場合と無い場合の両対応
|
||
accounts = data.items ?? data;
|
||
console.log("✓ accounts 已赋值,共", accounts.length, "个科目");
|
||
|
||
// 仮払消費税等(あなたの DB では 505 は「未払消費税等」)
|
||
taxPaidAccounts = accounts.filter((a) =>
|
||
a.account_name.includes("仮払"),
|
||
);
|
||
|
||
// 仮受消費税等
|
||
taxReceivedAccounts = accounts.filter((a) =>
|
||
a.account_name.includes("仮受"),
|
||
);
|
||
|
||
setupTaxSelectors();
|
||
setupSearchAccountSelector();
|
||
console.log("🔧 执行 addRow()...");
|
||
addRow();
|
||
console.log("✓ addRow() 完成");
|
||
|
||
document.getElementById("entryDate").value = new Date()
|
||
.toISOString()
|
||
.slice(0, 10);
|
||
|
||
await onEntryDateChanged();
|
||
|
||
// 摘要履歴を読み込み
|
||
loadDescriptionHistory();
|
||
|
||
// 各フィールドの変更時に合計を更新
|
||
document
|
||
.getElementById("entryDate")
|
||
.addEventListener("change", updateTotals);
|
||
document
|
||
.getElementById("description")
|
||
.addEventListener("input", updateTotals);
|
||
document
|
||
.getElementById("taxPaidSelect")
|
||
.addEventListener("change", updateTotals);
|
||
document
|
||
.getElementById("taxReceivedSelect")
|
||
.addEventListener("change", updateTotals);
|
||
document
|
||
.getElementById("roundingMode")
|
||
.addEventListener("change", () => {
|
||
// 端数処理変更時は全ての税行を再計算
|
||
const rows = document.querySelectorAll(
|
||
"#linesTable tbody tr:not(.tax-row)",
|
||
);
|
||
rows.forEach((row) => handleTax(row));
|
||
});
|
||
console.log("✓ init() 完成");
|
||
}
|
||
|
||
init();
|
||
|
||
// -----------------------------
|
||
// 検索用科目セレクタ
|
||
// -----------------------------
|
||
function setupSearchAccountSelector() {
|
||
// 新的可搜索输入框实现
|
||
const inputElement = document.getElementById("searchAccountInput");
|
||
if (!inputElement) {
|
||
console.log("searchAccountInput 不存在");
|
||
return;
|
||
}
|
||
|
||
const container = inputElement.closest(".account-search-container");
|
||
if (!container) return;
|
||
|
||
const dropdown = container.querySelector(".account-dropdown");
|
||
|
||
inputElement.addEventListener("input", (e) => {
|
||
const searchText = e.target.value.toLowerCase().trim();
|
||
if (!searchText) {
|
||
dropdown.classList.remove("active");
|
||
inputElement.dataset.accountId = "";
|
||
return;
|
||
}
|
||
|
||
const filtered = accounts.filter((acc) => {
|
||
const code = acc.account_code.toLowerCase();
|
||
const name = acc.account_name.toLowerCase();
|
||
return code.includes(searchText) || name.includes(searchText);
|
||
});
|
||
|
||
dropdown.innerHTML = "";
|
||
const all = document.createElement("div");
|
||
all.className = "account-option";
|
||
all.innerHTML = `<span class="account-option-strong">-- すべて --</span>`;
|
||
all.addEventListener("click", () => {
|
||
inputElement.value = "";
|
||
inputElement.dataset.accountId = "";
|
||
dropdown.classList.remove("active");
|
||
performSearch();
|
||
});
|
||
dropdown.appendChild(all);
|
||
|
||
if (filtered.length === 0) {
|
||
const none = document.createElement("div");
|
||
none.style.padding = "8px 12px";
|
||
none.style.color = "#999";
|
||
none.textContent = "該当する科目がありません";
|
||
dropdown.appendChild(none);
|
||
} else {
|
||
filtered.slice(0, 20).forEach((acc) => {
|
||
const opt = document.createElement("div");
|
||
opt.className = "account-option";
|
||
opt.innerHTML = `<span class="account-option-strong">${acc.account_code}</span><span class="account-option-light">${acc.account_name}</span>`;
|
||
opt.addEventListener("click", () => {
|
||
inputElement.value = `${acc.account_code} ${acc.account_name}`;
|
||
inputElement.dataset.accountId = acc.account_id;
|
||
dropdown.classList.remove("active");
|
||
performSearch();
|
||
});
|
||
dropdown.appendChild(opt);
|
||
});
|
||
}
|
||
dropdown.classList.add("active");
|
||
});
|
||
|
||
document.addEventListener("click", (e) => {
|
||
if (!container.contains(e.target)) {
|
||
dropdown.classList.remove("active");
|
||
}
|
||
});
|
||
|
||
inputElement.addEventListener("focus", () => {
|
||
if (inputElement.value) {
|
||
inputElement.dispatchEvent(new Event("input"));
|
||
}
|
||
});
|
||
}
|
||
|
||
// -----------------------------
|
||
// 摘要履歴管理
|
||
// -----------------------------
|
||
function loadDescriptionHistory() {
|
||
const history = JSON.parse(
|
||
localStorage.getItem("descriptionHistory") || "[]",
|
||
);
|
||
const datalist = document.getElementById("descriptionHistory");
|
||
datalist.innerHTML = "";
|
||
|
||
history.forEach((desc) => {
|
||
const option = document.createElement("option");
|
||
option.value = desc;
|
||
datalist.appendChild(option);
|
||
});
|
||
}
|
||
|
||
function saveDescriptionToHistory(description) {
|
||
if (!description || description.trim() === "") return;
|
||
|
||
let history = JSON.parse(
|
||
localStorage.getItem("descriptionHistory") || "[]",
|
||
);
|
||
|
||
// 重複を避け、先頭に追加
|
||
history = history.filter((d) => d !== description);
|
||
history.unshift(description);
|
||
|
||
// 最大100件まで保存
|
||
if (history.length > 100) {
|
||
history = history.slice(0, 100);
|
||
}
|
||
|
||
localStorage.setItem("descriptionHistory", JSON.stringify(history));
|
||
loadDescriptionHistory();
|
||
}
|
||
|
||
// -----------------------------
|
||
// 仮払/仮受 セレクタ
|
||
// -----------------------------
|
||
function setupTaxSelectors() {
|
||
document.getElementById("taxPaidSelect").innerHTML =
|
||
`<option value="">-- 選択してください --</option>` +
|
||
taxPaidAccounts
|
||
.map(
|
||
(a) =>
|
||
`<option value="${a.account_id}">${a.account_code} ${a.account_name}</option>`,
|
||
)
|
||
.join("");
|
||
|
||
document.getElementById("taxReceivedSelect").innerHTML =
|
||
`<option value="">-- 選択してください --</option>` +
|
||
taxReceivedAccounts
|
||
.map(
|
||
(a) =>
|
||
`<option value="${a.account_id}">${a.account_code} ${a.account_name}</option>`,
|
||
)
|
||
.join("");
|
||
}
|
||
|
||
// -----------------------------
|
||
// 行追加
|
||
// -----------------------------
|
||
function addRow(isTaxRow = false, taxInfo = null, parentId = null) {
|
||
console.log("📍 addRow() 调用,isTaxRow=" + isTaxRow);
|
||
const tbody = document.querySelector("#linesTable tbody");
|
||
if (!tbody) {
|
||
console.error("❌ 无法找到 tbody 元素!");
|
||
return;
|
||
}
|
||
console.log("✓ 找到 tbody,当前行数:", tbody.children.length);
|
||
|
||
const tr = document.createElement("tr");
|
||
|
||
if (!isTaxRow) {
|
||
tr.dataset.rowId = String(++rowSeq);
|
||
} else {
|
||
tr.classList.add("tax-row");
|
||
tr.dataset.parentId = parentId;
|
||
}
|
||
|
||
tr.innerHTML = `
|
||
<td>
|
||
<div class="account-search-container">
|
||
<input
|
||
type="text"
|
||
class="account-search-input account"
|
||
placeholder="科目を入力・検索"
|
||
autocomplete="off"
|
||
${isTaxRow ? "readonly" : ""} />
|
||
<div class="account-dropdown"></div>
|
||
</div>
|
||
</td>
|
||
<td><input type="text" class="debit right" inputmode="numeric" style="ime-mode: inactive;" ${
|
||
isTaxRow ? "readonly" : ""
|
||
} oninput="formatNumberInput(this)"></td>
|
||
<td><input type="text" class="credit right" inputmode="numeric" style="ime-mode: inactive;" ${
|
||
isTaxRow ? "readonly" : ""
|
||
} oninput="formatNumberInput(this)"></td>
|
||
<td>
|
||
<select class="taxType" ${isTaxRow ? "disabled" : ""}>
|
||
<option value="none">対象外</option>
|
||
<option value="10">10%</option>
|
||
<option value="8">8%</option>
|
||
</select>
|
||
</td>
|
||
<td>
|
||
<select class="taxDirection" ${isTaxRow ? "disabled" : ""}>
|
||
<option value="none">対象外</option>
|
||
<option value="paid">仮払(仕入・経費)</option>
|
||
<option value="received">仮受(売上)</option>
|
||
</select>
|
||
</td>
|
||
<td>${
|
||
isTaxRow ? "" : `<button onclick="removeRow(this)">削除</button>`
|
||
}</td>
|
||
`;
|
||
|
||
tbody.appendChild(tr);
|
||
console.log("✓ 已添加行,现在共有", tbody.children.length, "行");
|
||
|
||
// 税行の場合,填值
|
||
if (isTaxRow && taxInfo) {
|
||
const accountInput = tr.querySelector(".account-search-input");
|
||
const account = accounts.find(a => a.account_id === taxInfo.accountId);
|
||
if (account) {
|
||
accountInput.value = `${account.account_code} ${account.account_name}`;
|
||
accountInput.dataset.accountId = account.account_id;
|
||
}
|
||
if (taxInfo.side === "debit")
|
||
tr.querySelector(".debit").value = taxInfo.amount;
|
||
if (taxInfo.side === "credit")
|
||
tr.querySelector(".credit").value = taxInfo.amount;
|
||
}
|
||
|
||
// 普通行:绑定事件
|
||
if (!isTaxRow) {
|
||
const recalc = () => handleTax(tr);
|
||
const debitInput = tr.querySelector(".debit");
|
||
const creditInput = tr.querySelector(".credit");
|
||
const accountInput = tr.querySelector(".account-search-input");
|
||
|
||
debitInput.addEventListener("input", recalc);
|
||
creditInput.addEventListener("input", recalc);
|
||
|
||
// blur(フォーカス離脱)時に合計を更新
|
||
debitInput.addEventListener("blur", updateTotals);
|
||
creditInput.addEventListener("blur", updateTotals);
|
||
|
||
// 科目検索入力の処理
|
||
setupAccountSearch(accountInput, tr);
|
||
|
||
tr.querySelector(".taxType").addEventListener("change", recalc);
|
||
tr.querySelector(".taxDirection").addEventListener("change", recalc);
|
||
}
|
||
|
||
return tr;
|
||
}
|
||
|
||
// 删除该行的所有税行
|
||
function removeTaxRowsOf(row) {
|
||
const id = row.dataset.rowId;
|
||
if (!id) return;
|
||
document
|
||
.querySelectorAll(`tr.tax-row[data-parent-id="${id}"]`)
|
||
.forEach((r) => r.remove());
|
||
}
|
||
|
||
function removeRow(btn) {
|
||
const row = btn.closest("tr");
|
||
removeTaxRowsOf(row);
|
||
row.remove();
|
||
updateTotals(); // 削除後に合計を更新
|
||
}
|
||
|
||
// -----------------------------
|
||
// 借方・貸方合計を計算して表示
|
||
// -----------------------------
|
||
function updateTotals() {
|
||
let totalDebit = 0;
|
||
let totalCredit = 0;
|
||
|
||
const rows = document.querySelectorAll("#linesTable tbody tr");
|
||
rows.forEach((row) => {
|
||
const debitValue =
|
||
row.querySelector(".debit")?.value.replace(/,/g, "") || "0";
|
||
const creditValue =
|
||
row.querySelector(".credit")?.value.replace(/,/g, "") || "0";
|
||
|
||
totalDebit += Number(debitValue) || 0;
|
||
totalCredit += Number(creditValue) || 0;
|
||
});
|
||
|
||
// 表示を更新
|
||
document.getElementById("totalDebit").textContent =
|
||
totalDebit.toLocaleString();
|
||
document.getElementById("totalCredit").textContent =
|
||
totalCredit.toLocaleString();
|
||
|
||
// 貸借一致チェック
|
||
const balanceStatus = document.getElementById("balanceStatus");
|
||
if (totalDebit === totalCredit && totalDebit > 0) {
|
||
balanceStatus.textContent = "✓ 貸借一致";
|
||
balanceStatus.style.background = "#d4edda";
|
||
balanceStatus.style.color = "#155724";
|
||
} else if (totalDebit === 0 && totalCredit === 0) {
|
||
balanceStatus.textContent = "";
|
||
balanceStatus.style.background = "";
|
||
} else {
|
||
balanceStatus.textContent = `✗ 差額: ${Math.abs(
|
||
totalDebit - totalCredit,
|
||
).toLocaleString()}`;
|
||
balanceStatus.style.background = "#f8d7da";
|
||
balanceStatus.style.color = "#721c24";
|
||
}
|
||
}
|
||
|
||
// -----------------------------
|
||
// 税行 自動生成/更新(10%/8%のみ、四捨五入)
|
||
// -----------------------------
|
||
function handleTax(row) {
|
||
// 清理旧税行
|
||
removeTaxRowsOf(row);
|
||
|
||
const taxType = row.querySelector(".taxType").value;
|
||
const taxDir = row.querySelector(".taxDirection").value;
|
||
const debit = Number(
|
||
row.querySelector(".debit").value.replace(/,/g, "") || 0,
|
||
);
|
||
const credit = Number(
|
||
row.querySelector(".credit").value.replace(/,/g, "") || 0,
|
||
);
|
||
|
||
if (taxType === "none" || taxDir === "none") {
|
||
updateTotals(); // 税なしでも合計更新
|
||
return;
|
||
}
|
||
|
||
const totalAmount = debit || credit;
|
||
if (!totalAmount) {
|
||
updateTotals();
|
||
return;
|
||
}
|
||
|
||
const rate = taxType === "8" ? 0.08 : 0.1;
|
||
const roundingMode = document.getElementById("roundingMode").value;
|
||
|
||
// 税抜額 × 税率 = 税額
|
||
const rawTax = totalAmount * rate;
|
||
let taxAmount;
|
||
switch (roundingMode) {
|
||
case "floor":
|
||
taxAmount = Math.floor(rawTax);
|
||
break;
|
||
case "ceil":
|
||
taxAmount = Math.ceil(rawTax);
|
||
break;
|
||
default:
|
||
taxAmount = Math.round(rawTax);
|
||
}
|
||
|
||
const parentId = row.dataset.rowId;
|
||
|
||
if (taxDir === "paid") {
|
||
const taxAcc = document.getElementById("taxPaidSelect").value;
|
||
if (!taxAcc) {
|
||
updateTotals();
|
||
return alert("仮払消費税等 勘定を選択してください");
|
||
}
|
||
addRow(
|
||
true,
|
||
{ accountId: taxAcc, amount: taxAmount, side: "debit" },
|
||
parentId,
|
||
);
|
||
}
|
||
if (taxDir === "received") {
|
||
const taxAcc = document.getElementById("taxReceivedSelect").value;
|
||
if (!taxAcc) {
|
||
updateTotals();
|
||
return alert("仮受消費税等 勘定を選択してください");
|
||
}
|
||
addRow(
|
||
true,
|
||
{ accountId: taxAcc, amount: taxAmount, side: "credit" },
|
||
parentId,
|
||
);
|
||
}
|
||
|
||
updateTotals(); // 税行追加後に合計更新
|
||
}
|
||
|
||
// 税行は常に「直後の1行」を使う
|
||
function removeTaxRow(row) {
|
||
const id = row.dataset.rowId;
|
||
if (!id) return;
|
||
|
||
document
|
||
.querySelectorAll(`tr.tax-row[data-parent-id="${id}"]`)
|
||
.forEach((tr) => tr.remove());
|
||
}
|
||
|
||
function removeRow(btn) {
|
||
const row = btn.closest("tr");
|
||
removeTaxRow(row);
|
||
row.remove();
|
||
}
|
||
|
||
// -----------------------------
|
||
// 登録(税行自動生成版)
|
||
// -----------------------------
|
||
async function submitJournal() {
|
||
try {
|
||
const entryDate = document.getElementById("entryDate").value;
|
||
const description = document
|
||
.getElementById("description")
|
||
.value.trim();
|
||
|
||
if (!entryDate) {
|
||
alert("仕訳日を入力してください");
|
||
return;
|
||
}
|
||
|
||
// 明細収集(税情報も含む)
|
||
const rows = document.querySelectorAll("#linesTable tbody tr");
|
||
const lines = [];
|
||
|
||
rows.forEach((row) => {
|
||
if (row.classList.contains("tax-row")) return; // 税行は無視
|
||
|
||
const accountInput = row.querySelector(".account-search-input");
|
||
const accountId = Number(accountInput.dataset.accountId || 0);
|
||
const debit = Number(
|
||
row.querySelector(".debit").value.replace(/,/g, "") || 0,
|
||
);
|
||
const credit = Number(
|
||
row.querySelector(".credit").value.replace(/,/g, "") || 0,
|
||
);
|
||
const taxType = row.querySelector(".taxType").value;
|
||
const taxDirection = row.querySelector(".taxDirection").value;
|
||
|
||
if (debit > 0 && credit > 0) {
|
||
alert("同一行不能同时填写借方和贷方");
|
||
throw new Error("invalid line");
|
||
}
|
||
if (debit === 0 && credit === 0) return;
|
||
|
||
const lineData = {
|
||
account_id: accountId,
|
||
debit: debit,
|
||
credit: credit,
|
||
};
|
||
|
||
// 税情報を追加
|
||
if (taxType !== "none" && taxDirection !== "none") {
|
||
lineData.tax_rate = parseInt(taxType);
|
||
lineData.tax_direction = taxDirection;
|
||
}
|
||
|
||
lines.push(lineData);
|
||
});
|
||
|
||
if (lines.length === 0) {
|
||
alert("仕訳明細がありません");
|
||
return;
|
||
}
|
||
|
||
// 税科目(仮払消費税等・仮受消費税等)が存在するかチェック
|
||
const hasTaxAccount = lines.some((line) => {
|
||
const account = accounts.find(
|
||
(a) => a.account_id === line.account_id,
|
||
);
|
||
return (
|
||
account &&
|
||
(account.account_name.includes("仮払消費税") ||
|
||
account.account_name.includes("仮受消費税"))
|
||
);
|
||
});
|
||
|
||
// 税科目が存在し、かつ税情報を持つ行がある場合は警告
|
||
const hasTaxInfo = lines.some(
|
||
(line) => line.tax_rate != null && line.tax_direction != null,
|
||
);
|
||
|
||
if (hasTaxAccount && hasTaxInfo) {
|
||
if (
|
||
!confirm(
|
||
"警告:仮払消費税等・仮受消費税等の行がすでに存在していますが、他の行に税区分・税方向が設定されています。\n" +
|
||
"このまま登録すると税が二重計算され、借貸不平衡になります。\n\n" +
|
||
"税区分・税方向をすべて「対象外」に設定してから登録することをお勧めします。\n\n" +
|
||
"このまま登録しますか?",
|
||
)
|
||
) {
|
||
return;
|
||
}
|
||
}
|
||
|
||
const payload = {
|
||
entry_date: entryDate,
|
||
description,
|
||
lines,
|
||
tax_paid_account_id:
|
||
Number(document.getElementById("taxPaidSelect").value) || null,
|
||
tax_received_account_id:
|
||
Number(document.getElementById("taxReceivedSelect").value) ||
|
||
null,
|
||
rounding_mode: document.getElementById("roundingMode").value,
|
||
};
|
||
|
||
console.log("送信するデータ:", JSON.stringify(payload, null, 2));
|
||
console.log("明細行数:", lines.length);
|
||
lines.forEach((line, index) => {
|
||
console.log(`行${index + 1}:`, line);
|
||
});
|
||
|
||
const res = await fetch(`${API}/journal-entries`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify(payload),
|
||
});
|
||
|
||
if (!res.ok) {
|
||
const errorData = await res.json().catch(() => ({}));
|
||
const errorMsg =
|
||
errorData.detail || `登録に失敗しました (HTTP ${res.status})`;
|
||
console.error("Error:", errorData);
|
||
alert(errorMsg);
|
||
return;
|
||
}
|
||
|
||
const result = await res.json();
|
||
|
||
// 摘要を履歴に保存
|
||
saveDescriptionToHistory(description);
|
||
|
||
alert(`登録完了(ID=${result.journal_entry_id})`);
|
||
|
||
// 「登録後に明細を保持する」チェックボックスを確認
|
||
const keepDetails = document.getElementById(
|
||
"keepDetailsAfterSubmit",
|
||
).checked;
|
||
|
||
if (!keepDetails) {
|
||
// チェックボックスが未選中の場合、フォームをクリア(従来の挙動)
|
||
document.getElementById("description").value = "";
|
||
const tbody = document.querySelector("#linesTable tbody");
|
||
tbody.innerHTML = "";
|
||
rowSeq = 0;
|
||
addRow();
|
||
|
||
// 借方合計・貸方合計を0にリセット
|
||
document.getElementById("totalDebit").textContent = "0";
|
||
document.getElementById("totalCredit").textContent = "0";
|
||
document.getElementById("balanceStatus").textContent = "";
|
||
document.getElementById("balanceStatus").style.background = "";
|
||
} else {
|
||
// チェックボックスが選中の場合、何もクリアしない(日付、摘要、明細をすべて保持)
|
||
// ユーザーは日付だけを修正してから次の仕訳を登録する
|
||
}
|
||
|
||
// 仕訳検索を自動実行して最新の登録状況を表示
|
||
searchJournals();
|
||
} catch (error) {
|
||
console.error("送信エラー:", error);
|
||
alert(
|
||
`エラーが発生しました: ${error.message}\n\nサーバーが起動しているか確認してください。`,
|
||
);
|
||
}
|
||
}
|
||
|
||
const API_BASE = "";
|
||
|
||
async function callApi(path) {
|
||
try {
|
||
const res = await fetch(`${API_BASE}${path}`, { method: "POST" });
|
||
const text = await res.text();
|
||
let data = {};
|
||
try {
|
||
data = text ? JSON.parse(text) : {};
|
||
} catch {
|
||
data = { detail: text };
|
||
}
|
||
|
||
if (!res.ok) {
|
||
throw new Error(data.detail || `HTTP ${res.status}`);
|
||
}
|
||
return data;
|
||
} catch (e) {
|
||
throw new Error(e.message || "请求失败");
|
||
}
|
||
}
|
||
|
||
async function lockMonth() {
|
||
const year = document.getElementById("lockYear").value;
|
||
const month = document.getElementById("lockMonth").value;
|
||
|
||
const el = document.getElementById("lockResult");
|
||
el.innerText = "处理中...";
|
||
|
||
try {
|
||
await callApi(`/month-locks/lock?fiscal_year=${year}&month=${month}`);
|
||
el.innerText = `✅ ${year}年${month}月 已锁定`;
|
||
await refreshMonthLocks(); // 可选:自动刷新列表
|
||
} catch (e) {
|
||
el.innerText = `❌ 错误:${e.message}`;
|
||
}
|
||
}
|
||
|
||
async function unlockMonth() {
|
||
const year = document.getElementById("lockYear").value;
|
||
const month = document.getElementById("lockMonth").value;
|
||
|
||
const el = document.getElementById("lockResult");
|
||
el.innerText = "处理中...";
|
||
|
||
try {
|
||
await callApi(
|
||
`/month-locks/unlock?fiscal_year=${year}&month=${month}`,
|
||
);
|
||
el.innerText = `✅ ${year}年${month}月 已解锁`;
|
||
await refreshMonthLocks(); // 可选:自动刷新列表
|
||
} catch (e) {
|
||
el.innerText = `❌ 错误:${e.message}`;
|
||
}
|
||
}
|
||
|
||
async function refreshMonthLocks() {
|
||
const el = document.getElementById("lockList");
|
||
el.textContent = "读取中...";
|
||
|
||
try {
|
||
const res = await fetch(`${API_BASE}/month-locks`);
|
||
const data = await res.json();
|
||
|
||
// 只显示 locked 的,避免太长
|
||
const locked = (data || []).filter((x) => x.is_locked);
|
||
|
||
if (locked.length === 0) {
|
||
el.textContent = "(当前没有锁定月份)";
|
||
return;
|
||
}
|
||
|
||
el.textContent = locked
|
||
.map(
|
||
(x) =>
|
||
`${x.fiscal_year}-${String(x.month).padStart(
|
||
2,
|
||
"0",
|
||
)} locked_by=${x.locked_by ?? ""}`,
|
||
)
|
||
.join("\n");
|
||
} catch (e) {
|
||
el.textContent = `读取失败:${e.message || e}`;
|
||
}
|
||
}
|
||
|
||
async function checkMonthLockByDate(dateStr) {
|
||
if (!dateStr) return false;
|
||
|
||
const d = new Date(dateStr);
|
||
const year = d.getFullYear();
|
||
const month = d.getMonth() + 1;
|
||
|
||
const res = await fetch(`${API_BASE}/month-locks`);
|
||
const data = await res.json();
|
||
|
||
return (data || []).some(
|
||
(x) => x.fiscal_year === year && x.month === month && x.is_locked,
|
||
);
|
||
}
|
||
|
||
async function onEntryDateChanged() {
|
||
const dateStr = document.getElementById("entryDate").value;
|
||
const locked = await checkMonthLockByDate(dateStr);
|
||
|
||
const banner = document.getElementById("monthLockBanner");
|
||
|
||
if (locked) {
|
||
banner.style.display = "block";
|
||
setJournalReadonly(true);
|
||
} else {
|
||
banner.style.display = "none";
|
||
setJournalReadonly(false);
|
||
}
|
||
}
|
||
|
||
function setJournalReadonly(readonly) {
|
||
// 保存按钮
|
||
const saveBtn = document.getElementById("saveButton");
|
||
if (saveBtn) saveBtn.disabled = readonly;
|
||
|
||
// 行追加按钮
|
||
const addRowBtn = document.getElementById("addRowButton");
|
||
if (addRowBtn) addRowBtn.disabled = readonly;
|
||
|
||
// 所有“删除行”按钮
|
||
document.querySelectorAll(".delete-row-btn").forEach((btn) => {
|
||
btn.disabled = readonly;
|
||
});
|
||
|
||
// 所有仕訳输入项(金额 / 科目等)
|
||
document.querySelectorAll(".journal-input").forEach((input) => {
|
||
input.disabled = readonly;
|
||
});
|
||
}
|
||
|
||
function buildAccountOptions() {
|
||
let html = "";
|
||
|
||
// 最近使った科目を表示
|
||
const recentAccountIds = JSON.parse(
|
||
localStorage.getItem("recentAccounts") || "[]",
|
||
);
|
||
if (recentAccountIds.length > 0) {
|
||
html += `<optgroup label="⭐ 最近使った科目">`;
|
||
recentAccountIds.forEach((accountId) => {
|
||
const account = accounts.find((a) => a.account_id === accountId);
|
||
if (account) {
|
||
html += `<option value="${account.account_id}">
|
||
${account.account_code} ${account.account_name}
|
||
</option>`;
|
||
}
|
||
});
|
||
html += `</optgroup>`;
|
||
}
|
||
|
||
// 已分组的科目
|
||
ACCOUNT_GROUPS.forEach((group) => {
|
||
html += `<optgroup label="${group.label}">`;
|
||
accounts
|
||
.filter((a) => group.codes.includes(a.account_code))
|
||
.forEach((a) => {
|
||
html += `<option value="${a.account_id}">
|
||
${a.account_code} ${a.account_name}
|
||
</option>`;
|
||
});
|
||
html += `</optgroup>`;
|
||
});
|
||
|
||
// 未分组的其他科目
|
||
const groupedCodes = ACCOUNT_GROUPS.flatMap((g) => g.codes);
|
||
const others = accounts.filter(
|
||
(a) => !groupedCodes.includes(a.account_code),
|
||
);
|
||
|
||
if (others.length > 0) {
|
||
html += `<optgroup label="📚 その他">`;
|
||
others.forEach((a) => {
|
||
html += `<option value="${a.account_id}">
|
||
${a.account_code} ${a.account_name}
|
||
</option>`;
|
||
});
|
||
html += `</optgroup>`;
|
||
}
|
||
|
||
return html;
|
||
}
|
||
|
||
// 科目選択履歴を保存
|
||
function saveAccountToRecent(accountId) {
|
||
if (!accountId) return;
|
||
|
||
let recentAccounts = JSON.parse(
|
||
localStorage.getItem("recentAccounts") || "[]",
|
||
);
|
||
|
||
// 重複を除去して先頭に追加
|
||
recentAccounts = recentAccounts.filter((id) => id !== accountId);
|
||
recentAccounts.unshift(accountId);
|
||
|
||
// 最大20件まで保持
|
||
if (recentAccounts.length > 20) {
|
||
recentAccounts = recentAccounts.slice(0, 20);
|
||
}
|
||
|
||
localStorage.setItem("recentAccounts", JSON.stringify(recentAccounts));
|
||
}
|
||
|
||
// ========================================
|
||
// 仕訳検索機能(journal-list.htmlから統合)
|
||
// ========================================
|
||
// 検索結果を印刷(検索を実行してから印刷)
|
||
async function printSearchResults() {
|
||
try {
|
||
// まず検索を実行
|
||
const from = document.getElementById("searchFromDate").value;
|
||
const to = document.getElementById("searchToDate").value;
|
||
const key = document.getElementById("searchKeyword").value;
|
||
const accountId = document.getElementById("searchAccountId").value;
|
||
const accountSide =
|
||
document.getElementById("searchAccountSide").value;
|
||
const includeHistory = document.getElementById(
|
||
"searchIncludeHistory",
|
||
).checked;
|
||
|
||
const qs = new URLSearchParams();
|
||
if (from) qs.append("from_date", from);
|
||
if (to) qs.append("to_date", to);
|
||
if (key) qs.append("keyword", key);
|
||
if (accountId) qs.append("account_id", accountId);
|
||
if (accountSide) qs.append("account_side", accountSide);
|
||
if (includeHistory) qs.append("include_history", "true");
|
||
|
||
const res = await fetch(`${API}/journal-entries?${qs.toString()}`);
|
||
if (!res.ok) {
|
||
throw new Error(`API error: ${res.status} ${res.statusText}`);
|
||
}
|
||
let data = await res.json();
|
||
if (!Array.isArray(data)) {
|
||
console.warn("⚠️ API返り値は配列ではありません:", data);
|
||
data = [];
|
||
}
|
||
|
||
// 印刷用に昇順でソート
|
||
const printData = [...data].sort((a, b) => {
|
||
if (a.entry_date !== b.entry_date) {
|
||
return a.entry_date.localeCompare(b.entry_date);
|
||
}
|
||
return a.journal_entry_id - b.journal_entry_id;
|
||
});
|
||
|
||
const printArea = document.getElementById("printArea");
|
||
printArea.innerHTML = "";
|
||
|
||
// 月ごとにデータをグループ化
|
||
const monthGroups = {};
|
||
printData.forEach((e) => {
|
||
const entryMonth = e.entry_date.substring(0, 7);
|
||
if (!monthGroups[entryMonth]) {
|
||
monthGroups[entryMonth] = [];
|
||
}
|
||
monthGroups[entryMonth].push(e);
|
||
});
|
||
|
||
// 検索条件を生成
|
||
const accountSelect = document.getElementById("searchAccountId");
|
||
const accountName =
|
||
accountSelect.options[accountSelect.selectedIndex]?.text || "";
|
||
const sideSelect = document.getElementById("searchAccountSide");
|
||
const sideName =
|
||
sideSelect.options[sideSelect.selectedIndex]?.text || "";
|
||
let conditions = [];
|
||
if (from || to) {
|
||
conditions.push(`期間: ${from || ""} ~ ${to || ""}`);
|
||
}
|
||
if (key) {
|
||
conditions.push(`摘要: ${key}`);
|
||
}
|
||
if (accountName && accountName !== "-- すべて --") {
|
||
conditions.push(`科目: ${accountName}`);
|
||
}
|
||
if (sideName && sideName !== "-- すべて --") {
|
||
conditions.push(`方向: ${sideName}`);
|
||
}
|
||
if (includeHistory) {
|
||
conditions.push(`修正履歴を含む`);
|
||
}
|
||
const conditionsText =
|
||
conditions.length > 0 ? conditions.join(" | ") : "検索条件: すべて";
|
||
|
||
// 月ごとにテーブルを生成(印刷用)
|
||
Object.keys(monthGroups)
|
||
.sort()
|
||
.forEach((month, index) => {
|
||
const monthData = monthGroups[month];
|
||
const monthDisplay = new Date(month + "-01").toLocaleDateString(
|
||
"ja-JP",
|
||
{
|
||
year: "numeric",
|
||
month: "long",
|
||
},
|
||
);
|
||
|
||
const section = document.createElement("div");
|
||
if (index > 0) {
|
||
section.className = "page-break";
|
||
}
|
||
|
||
section.innerHTML = `
|
||
<table style="margin-bottom: 20px;">
|
||
<thead>
|
||
<tr>
|
||
<th colspan="6" style="text-align: center; font-size: 1.2em; padding: 8px; border: none; background: transparent;">仕訳検索結果</th>
|
||
</tr>
|
||
<tr>
|
||
<th colspan="3" style="text-align: left; font-weight: normal; font-size: 0.9em; padding: 4px; border: none; background: transparent;">${conditionsText}</th>
|
||
<th colspan="3" style="text-align: right; font-weight: normal; font-size: 0.9em; padding: 4px; border: none; background: transparent;">${monthDisplay}</th>
|
||
</tr>
|
||
<tr>
|
||
<th style="white-space: nowrap;">日付</th>
|
||
<th>摘要</th>
|
||
<th style="white-space: nowrap;">借方合計</th>
|
||
<th style="white-space: nowrap;">貸方合計</th>
|
||
<th>税率</th>
|
||
<th style="white-space: nowrap;">操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody></tbody>
|
||
</table>
|
||
<div class="page-number">ページ ${index + 1}</div>
|
||
`;
|
||
|
||
const tbody = section.querySelector("tbody");
|
||
let monthDebitTotal = 0;
|
||
let monthCreditTotal = 0;
|
||
|
||
monthData.forEach((e) => {
|
||
monthDebitTotal += e.debit_total;
|
||
monthCreditTotal += e.credit_total;
|
||
|
||
// 修正版本の表示(revised_count を使用)
|
||
// includeHistory に関係なく、修正版本は常に表示
|
||
const versionInfo =
|
||
e.revision_count && e.revision_count > 1
|
||
? ` (v${e.revision_count})`
|
||
: "";
|
||
const tr = document.createElement("tr");
|
||
tr.innerHTML = `
|
||
<td style="white-space: nowrap;">${e.entry_date}</td>
|
||
<td style="text-align:left">${e.description}${versionInfo}</td>
|
||
<td style="text-align:right; white-space: nowrap;">${e.debit_total.toLocaleString()}</td>
|
||
<td style="text-align:right; white-space: nowrap;">${e.credit_total.toLocaleString()}</td>
|
||
<td style="text-align:center">${
|
||
e.tax_rates ? e.tax_rates + "%" : ""
|
||
}</td>
|
||
<td style="white-space: nowrap;">
|
||
<button onclick="viewJournal(${
|
||
e.journal_entry_id
|
||
})">表示</button>
|
||
<button onclick="copyJournal(${
|
||
e.journal_entry_id
|
||
})" style="color: green;">複製</button>
|
||
<button onclick="reverseAndEdit(${
|
||
e.journal_entry_id
|
||
})">修正</button>
|
||
<button onclick="deleteJournalEntry(${
|
||
e.journal_entry_id
|
||
})" style="color: red;">削除</button>
|
||
</td>
|
||
`;
|
||
tbody.appendChild(tr);
|
||
});
|
||
|
||
// 月合計行を追加
|
||
const totalRow = document.createElement("tr");
|
||
totalRow.style.fontWeight = "bold";
|
||
totalRow.style.backgroundColor = "#f0f0f0";
|
||
totalRow.innerHTML = `
|
||
<td colspan="2" style="text-align:right; white-space: nowrap;">合計:</td>
|
||
<td style="text-align:right; white-space: nowrap;">${monthDebitTotal.toLocaleString()}</td>
|
||
<td style="text-align:right; white-space: nowrap;">${monthCreditTotal.toLocaleString()}</td>
|
||
<td colspan="2"></td>
|
||
`;
|
||
tbody.appendChild(totalRow);
|
||
|
||
printArea.appendChild(section);
|
||
});
|
||
// 少し待ってから印刷(データの表示を待つ)
|
||
setTimeout(() => {
|
||
window.print();
|
||
}, 100);
|
||
} catch (err) {
|
||
console.error("❌ 印刷用検索エラー:", err);
|
||
const printArea = document.getElementById("printArea");
|
||
if (printArea) {
|
||
printArea.innerHTML = `
|
||
<div style="padding: 20px; color: red; border: 2px solid red;">
|
||
<h3>❌ 検索に失敗しました</h3>
|
||
<p><strong>エラー内容:</strong> ${err.message}</p>
|
||
<p style="font-size: 0.9em; color: #666;">
|
||
F12 で開発者ツールを確認して、コンソールログを確認してください。
|
||
</p>
|
||
</div>
|
||
`;
|
||
}
|
||
alert(`検索に失敗しました: ${err.message}`);
|
||
}
|
||
}
|
||
|
||
// 搜索函数(在选择搜索科目时被触发)
|
||
function performSearch() {
|
||
searchJournals();
|
||
}
|
||
|
||
// 检索结果を表に表示
|
||
async function searchJournals() {
|
||
try {
|
||
const from = document.getElementById("searchFromDate").value;
|
||
const to = document.getElementById("searchToDate").value;
|
||
const key = document.getElementById("searchKeyword").value;
|
||
const accountInput = document.getElementById("searchAccountInput");
|
||
const accountId = accountInput ? accountInput.dataset.accountId : "";
|
||
const accountSide =
|
||
document.getElementById("searchAccountSide").value;
|
||
const includeHistory = document.getElementById(
|
||
"searchIncludeHistory",
|
||
).checked;
|
||
|
||
// 検索条件を保存
|
||
localStorage.setItem(
|
||
"journalSearchConditions",
|
||
JSON.stringify({
|
||
fromDate: from,
|
||
toDate: to,
|
||
keyword: key,
|
||
accountId: accountId,
|
||
accountSide: accountSide,
|
||
includeHistory: includeHistory,
|
||
}),
|
||
);
|
||
|
||
const qs = new URLSearchParams();
|
||
if (from) qs.append("from_date", from);
|
||
if (to) qs.append("to_date", to);
|
||
if (key) qs.append("keyword", key);
|
||
if (accountId) qs.append("account_id", accountId);
|
||
if (accountSide) qs.append("account_side", accountSide);
|
||
if (includeHistory) qs.append("include_history", "true");
|
||
|
||
console.log(
|
||
"🔍 検索 URL:",
|
||
`${API}/journal-entries?${qs.toString()}`,
|
||
);
|
||
|
||
const res = await fetch(`${API}/journal-entries?${qs.toString()}`);
|
||
|
||
// ❌ API レスポンス確認
|
||
if (!res.ok) {
|
||
throw new Error(`API error: ${res.status} ${res.statusText}`);
|
||
}
|
||
|
||
let data = await res.json();
|
||
|
||
// 返されたデータが配列か確認
|
||
if (!Array.isArray(data)) {
|
||
console.warn("⚠️ API返り値は配列ではありません:", data);
|
||
data = [];
|
||
}
|
||
|
||
console.log("✓ 検索結果:", data.length, "件");
|
||
|
||
const printArea = document.getElementById("printArea");
|
||
printArea.innerHTML = "";
|
||
|
||
// 月ごとにデータをグループ化
|
||
const monthGroups = {};
|
||
data.forEach((e) => {
|
||
const entryMonth = e.entry_date.substring(0, 7); // YYYY-MM
|
||
if (!monthGroups[entryMonth]) {
|
||
monthGroups[entryMonth] = [];
|
||
}
|
||
monthGroups[entryMonth].push(e);
|
||
});
|
||
|
||
// 検索条件を生成
|
||
const conditionsText = (() => {
|
||
let conditions = [];
|
||
if (from || to) {
|
||
conditions.push(`期間: ${from || ""} ~ ${to || ""}`);
|
||
}
|
||
if (key) {
|
||
conditions.push(`摘要: ${key}`);
|
||
}
|
||
const accountInput = document.getElementById("searchAccountInput");
|
||
const accountName = accountInput ? accountInput.value : "";
|
||
if (accountName && accountName.trim() !== "") {
|
||
conditions.push(`科目: ${accountName}`);
|
||
}
|
||
const sideSelect = document.getElementById("searchAccountSide");
|
||
const sideName =
|
||
sideSelect ? sideSelect.options[sideSelect.selectedIndex]?.text : "";
|
||
if (sideName && sideName !== "-- すべて --") {
|
||
conditions.push(`方向: ${sideName}`);
|
||
}
|
||
if (includeHistory) {
|
||
conditions.push(`修正履歴を含む`);
|
||
}
|
||
return conditions.length > 0
|
||
? conditions.join(" | ")
|
||
: "検索条件: すべて";
|
||
})();
|
||
|
||
// 月ごとにテーブルを生成(画面表示は降順)
|
||
Object.keys(monthGroups)
|
||
.sort((a, b) => b.localeCompare(a)) // 月を降順で表示
|
||
.forEach((month, index) => {
|
||
const monthData = monthGroups[month];
|
||
const monthDisplay = new Date(month + "-01").toLocaleDateString(
|
||
"ja-JP",
|
||
{
|
||
year: "numeric",
|
||
month: "long",
|
||
},
|
||
);
|
||
|
||
const section = document.createElement("div");
|
||
if (index > 0) {
|
||
section.className = "page-break";
|
||
}
|
||
|
||
section.innerHTML = `
|
||
<table style="margin-bottom: 20px;">
|
||
<thead>
|
||
<tr>
|
||
<th colspan="6" style="text-align: center; font-size: 1.2em; padding: 8px; border: none; background: transparent;">仕訳検索結果</th>
|
||
</tr>
|
||
<tr>
|
||
<th colspan="3" style="text-align: left; font-weight: normal; font-size: 0.9em; padding: 4px; border: none; background: transparent;">${conditionsText}</th>
|
||
<th colspan="3" style="text-align: right; font-weight: normal; font-size: 0.9em; padding: 4px; border: none; background: transparent;">${monthDisplay}</th>
|
||
</tr>
|
||
<tr>
|
||
<th style="white-space: nowrap;">日付</th>
|
||
<th>摘要</th>
|
||
<th style="white-space: nowrap;">借方合計</th>
|
||
<th style="white-space: nowrap;">貸方合計</th>
|
||
<th>税率</th>
|
||
<th style="white-space: nowrap;">操作</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody></tbody>
|
||
</table>
|
||
<div class="page-number">ページ ${index + 1}</div>
|
||
`;
|
||
|
||
const tbody = section.querySelector("tbody");
|
||
let monthDebitTotal = 0;
|
||
let monthCreditTotal = 0;
|
||
|
||
// 月内のデータも降順で表示(画面表示用)
|
||
monthData.forEach((e) => {
|
||
monthDebitTotal += e.debit_total;
|
||
monthCreditTotal += e.credit_total;
|
||
|
||
// 修正版本の表示(revision_count を使用)
|
||
// includeHistory に関係なく、修正版本は常に表示
|
||
const versionInfo =
|
||
e.revision_count && e.revision_count > 1
|
||
? ` (v${e.revision_count})`
|
||
: "";
|
||
const tr = document.createElement("tr");
|
||
tr.innerHTML = `
|
||
<td style="white-space: nowrap;">${e.entry_date}</td>
|
||
<td style="text-align:left">${e.description}${versionInfo}</td>
|
||
<td style="text-align:right; white-space: nowrap;">${e.debit_total.toLocaleString()}</td>
|
||
<td style="text-align:right; white-space: nowrap;">${e.credit_total.toLocaleString()}</td>
|
||
<td style="text-align:center">${
|
||
e.tax_rates ? e.tax_rates + "%" : ""
|
||
}</td>
|
||
<td style="white-space: nowrap;">
|
||
<button onclick="viewJournal(${
|
||
e.journal_entry_id
|
||
})">表示</button>
|
||
<button onclick="copyJournal(${
|
||
e.journal_entry_id
|
||
})" style="color: green;">複製</button>
|
||
<button onclick="reverseAndEdit(${
|
||
e.journal_entry_id
|
||
})">修正</button>
|
||
<button onclick="deleteJournalEntry(${
|
||
e.journal_entry_id
|
||
})" style="color: red;">削除</button>
|
||
</td>
|
||
`;
|
||
tbody.appendChild(tr);
|
||
});
|
||
|
||
// 月合計行を追加
|
||
const totalRow = document.createElement("tr");
|
||
totalRow.style.fontWeight = "bold";
|
||
totalRow.style.backgroundColor = "#f0f0f0";
|
||
totalRow.innerHTML = `
|
||
<td colspan="2" style="text-align:right; white-space: nowrap;">合計:</td>
|
||
<td style="text-align:right; white-space: nowrap;">${monthDebitTotal.toLocaleString()}</td>
|
||
<td style="text-align:right; white-space: nowrap;">${monthCreditTotal.toLocaleString()}</td>
|
||
<td colspan="2"></td>
|
||
`;
|
||
tbody.appendChild(totalRow);
|
||
|
||
printArea.appendChild(section);
|
||
});
|
||
} catch (err) {
|
||
console.error("❌ 検索エラー:", err);
|
||
const printArea = document.getElementById("printArea");
|
||
if (printArea) {
|
||
printArea.innerHTML = `
|
||
<div style="padding: 20px; color: red; border: 2px solid red;">
|
||
<h3>❌ 検索に失敗しました</h3>
|
||
<p><strong>エラー内容:</strong> ${err.message}</p>
|
||
<p style="font-size: 0.9em; color: #666;">
|
||
F12 で開発者ツールを確認して、コンソールログを確認してください。
|
||
</p>
|
||
</div>
|
||
`;
|
||
}
|
||
alert(`検索に失敗しました: ${err.message}`);
|
||
}
|
||
}
|
||
|
||
function viewJournal(id) {
|
||
window.open(`journal-view.html?id=${id}`, "_blank");
|
||
}
|
||
|
||
// --------------------------------------------------
|
||
// 仕訳複製:既存の仕訳を入力フォームにコピー
|
||
// --------------------------------------------------
|
||
async function copyJournal(id) {
|
||
try {
|
||
const res = await fetch(`${API}/journal-entries/${id}`);
|
||
if (!res.ok) {
|
||
alert("仕訳の取得に失敗しました");
|
||
return;
|
||
}
|
||
|
||
const data = await res.json();
|
||
|
||
// 日付をコピー元の仕訳日に設定(ユーザーが修正することを期待)
|
||
document.getElementById("entryDate").value = data.entry_date;
|
||
|
||
// 摘要をコピー
|
||
document.getElementById("description").value = data.description || "";
|
||
|
||
// 既存の行をすべてクリア(税行も含む)
|
||
const tbody = document.querySelector("#linesTable tbody");
|
||
tbody.innerHTML = "";
|
||
rowSeq = 0;
|
||
|
||
// 仕訳明細をすべてコピー(税行も含む)
|
||
// 税の自動計算機能は実行しない(税区分・税方向を「対象外」に設定)
|
||
if (data.lines && data.lines.length > 0) {
|
||
data.lines.forEach((line) => {
|
||
const tr = addRow();
|
||
|
||
// 科目を設定
|
||
const accountInput = tr.querySelector(".account-search-input");
|
||
const account = accounts.find(a => a.account_id === line.account_id);
|
||
if (accountInput && account) {
|
||
accountInput.value = `${account.account_code} ${account.account_name}`;
|
||
accountInput.dataset.accountId = account.account_id;
|
||
}
|
||
|
||
// 借方・貸方金額を設定(カンマフォーマット付き)
|
||
const debitInput = tr.querySelector(".debit");
|
||
const creditInput = tr.querySelector(".credit");
|
||
if (debitInput && line.debit) {
|
||
debitInput.value = Number(line.debit).toLocaleString();
|
||
}
|
||
if (creditInput && line.credit) {
|
||
creditInput.value = Number(line.credit).toLocaleString();
|
||
}
|
||
|
||
// 税区分・税方向は「対象外」に設定(自動計算を防ぐため)
|
||
const taxTypeSelect = tr.querySelector(".taxType");
|
||
const taxDirSelect = tr.querySelector(".taxDirection");
|
||
|
||
if (taxTypeSelect) {
|
||
taxTypeSelect.value = "none"; // 対象外
|
||
}
|
||
if (taxDirSelect) {
|
||
taxDirSelect.value = "none"; // 対象外
|
||
}
|
||
});
|
||
}
|
||
|
||
// ページ上部の仕訳入力フォームにスクロール
|
||
window.scrollTo({ top: 0, behavior: "smooth" });
|
||
|
||
// ユーザーに日付修正を促す
|
||
const dateInput = document.getElementById("entryDate");
|
||
dateInput.focus();
|
||
|
||
console.log("コピーされたデータ:", data); // デバッグ用
|
||
console.log(
|
||
`${data.lines.length}行をコピーしました。税区分・税方向はすべて「対象外」に設定されています。`,
|
||
);
|
||
alert(
|
||
`仕訳を複製しました(${data.lines.length}行)。\n\n` +
|
||
`※ このコピーは新規仕訳として独立した記録になります。\n` +
|
||
`※ 日付と摘要を必要に応じて修正してから登録してください。\n` +
|
||
`※ 税区分・税方向はすべて「対象外」に設定されています。`,
|
||
);
|
||
} catch (error) {
|
||
console.error("Error:", error);
|
||
alert(`エラーが発生しました: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
// --------------------------------------------------
|
||
// 修正仕訳:逆仕訳を作って修正画面へ遷移
|
||
// --------------------------------------------------
|
||
async function reverseAndEdit(id) {
|
||
try {
|
||
// 获取元仕訳内容
|
||
const srcRes = await fetch(`${API}/journal-entries/${id}`);
|
||
if (!srcRes.ok) {
|
||
return;
|
||
}
|
||
|
||
const srcData = await srcRes.json();
|
||
localStorage.setItem("editSource", JSON.stringify(srcData));
|
||
|
||
// 打开修正画面
|
||
window.open("journal-edit.html", "_blank");
|
||
} catch (error) {
|
||
console.error("Error:", error);
|
||
}
|
||
}
|
||
|
||
// --------------------------------------------------
|
||
// 仕訳削除
|
||
// --------------------------------------------------
|
||
async function deleteJournalEntry(id) {
|
||
const reason = prompt("削除理由を入力してください:");
|
||
if (!reason || reason.trim() === "") {
|
||
alert("削除理由の入力が必要です");
|
||
return;
|
||
}
|
||
|
||
if (!confirm("この仕訳を削除してもよろしいですか?")) {
|
||
return;
|
||
}
|
||
|
||
const res = await fetch(`${API}/journal-entries/${id}`, {
|
||
method: "DELETE",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ deleted_reason: reason }),
|
||
});
|
||
|
||
const data = await res.json();
|
||
if (!res.ok) {
|
||
alert(data.detail || "削除に失敗しました");
|
||
return;
|
||
}
|
||
|
||
alert("削除しました");
|
||
searchJournals(); // リストを再読み込み
|
||
}
|
||
|
||
// ページロード後に検索条件を設定
|
||
window.addEventListener("DOMContentLoaded", async () => {
|
||
// デフォルト期間を設定(5/31決算:6月1日~現在)
|
||
const today = new Date();
|
||
const currentYear = today.getFullYear();
|
||
const currentMonth = today.getMonth() + 1; // 1-12
|
||
|
||
let fiscalStartYear;
|
||
if (currentMonth >= 6) {
|
||
// 6月以降:当年6月1日から
|
||
fiscalStartYear = currentYear;
|
||
} else {
|
||
// 1-5月:前年6月1日から
|
||
fiscalStartYear = currentYear - 1;
|
||
}
|
||
|
||
const defaultFromDate = `${fiscalStartYear}-06-01`;
|
||
const defaultToDate = today.toISOString().slice(0, 10);
|
||
|
||
// 前回の検索条件を復元
|
||
const savedConditions = localStorage.getItem("journalSearchConditions");
|
||
if (savedConditions) {
|
||
try {
|
||
const conditions = JSON.parse(savedConditions);
|
||
// 期間を復元
|
||
document.getElementById("searchFromDate").value =
|
||
conditions.fromDate || defaultFromDate;
|
||
document.getElementById("searchToDate").value =
|
||
conditions.toDate || defaultToDate;
|
||
|
||
// 摘要、科目、方向を復元
|
||
if (conditions.keyword !== undefined && conditions.keyword !== null)
|
||
document.getElementById("searchKeyword").value =
|
||
conditions.keyword;
|
||
if (
|
||
conditions.accountId !== undefined &&
|
||
conditions.accountId !== null
|
||
) {
|
||
const accountInput = document.getElementById("searchAccountInput");
|
||
if (accountInput && accounts && accounts.length > 0) {
|
||
const account = accounts.find(
|
||
(a) => a.account_id === conditions.accountId,
|
||
);
|
||
if (account) {
|
||
accountInput.value = `${account.account_code} ${account.account_name}`;
|
||
accountInput.dataset.accountId = account.account_id;
|
||
}
|
||
}
|
||
}
|
||
if (
|
||
conditions.accountSide !== undefined &&
|
||
conditions.accountSide !== null
|
||
)
|
||
document.getElementById("searchAccountSide").value =
|
||
conditions.accountSide;
|
||
if (
|
||
conditions.includeHistory !== undefined &&
|
||
conditions.includeHistory !== null
|
||
)
|
||
document.getElementById("searchIncludeHistory").checked =
|
||
conditions.includeHistory;
|
||
} catch (e) {
|
||
// パース失敗時はデフォルト期間を設定
|
||
document.getElementById("searchFromDate").value = defaultFromDate;
|
||
document.getElementById("searchToDate").value = defaultToDate;
|
||
}
|
||
} else {
|
||
// 保存された条件がない場合はデフォルト期間を設定
|
||
document.getElementById("searchFromDate").value = defaultFromDate;
|
||
document.getElementById("searchToDate").value = defaultToDate;
|
||
}
|
||
|
||
// 検索条件が復元されたので、自動的に検索を実行
|
||
console.log("🔍 自動検索を実行します...");
|
||
await searchJournals();
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|