| | | @@ 変更前 1行目〜 / 変更後 1行目〜 @@ |
| 1 | 1 | | // 会計年度(第何期か)の計算。 |
| 2 | | − | // v1: よくある書き方(Date で日付を読み、期首を「決算月の翌月1日」として new Date で作る。文字列化は toISOString)。 |
| 2 | + | // v2: 月の通し番号(年×12+月−1)で数え、Date の繰り越しとタイムゾーンを通さない。 |
| 3 | + | // 存在しない日付は invalid_date にする(new Date(2025, 1, 30) は 3月2日に繰り越すので使わない)。 |
| 3 | 4 | | |
| 4 | | − | function fiscalStart(d, closingMonth) { |
| 5 | | − | // getMonth() は 0 始まり。決算月の翌月 = closingMonth(0 始まりの値として) |
| 6 | | − | if (d.getMonth() + 1 > closingMonth) return new Date(d.getFullYear(), closingMonth, 1); |
| 7 | | − | return new Date(d.getFullYear() - 1, closingMonth, 1); |
| 5 | + | const monthIndex = (y, m) => y * 12 + (m - 1); |
| 6 | + | const firstClosingAtOrAfter = (idx, closingMonth) => idx + ((((closingMonth - 1 - (idx % 12)) % 12) + 12) % 12); |
| 7 | + | // その月の日数。Date.UTC はタイムゾーンの影響を受けない |
| 8 | + | const daysInMonth = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate(); |
| 9 | + | const pad = (n, w) => String(n).padStart(w, "0"); |
| 10 | + | |
| 11 | + | function ymd(idx, last = false) { |
| 12 | + | const y = Math.floor(idx / 12); |
| 13 | + | const m = (idx % 12) + 1; |
| 14 | + | return `${pad(y, 4)}-${pad(m, 2)}-${pad(last ? daysInMonth(y, m) : 1, 2)}`; |
| 8 | 15 | | } |
| 9 | 16 | | |
| 10 | | − | const fmt = (d) => d.toISOString().slice(0, 10); |
| 11 | | − | |
| 12 | 17 | | export function calcFiscal({ closing_month, start, date }) { |
| 13 | | − | const [y, m, dd] = date.split("-").map(Number); |
| 14 | | − | const d = new Date(y, m - 1, dd); |
| 18 | + | const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date); |
| 19 | + | if (!m) return { error: "invalid_date" }; |
| 20 | + | const [y, mo, d] = m.slice(1).map(Number); |
| 21 | + | if (mo < 1 || mo > 12 || d < 1 || d > daysInMonth(y, mo)) return { error: "invalid_date" }; |
| 15 | 22 | | const [sy, sm] = start.split("-").map(Number); |
| 16 | | − | const s = new Date(sy, sm - 1, 1); |
| 17 | | − | if (d < s) return { error: "before_start" }; |
| 18 | | − | const fy = fiscalStart(d, closing_month); |
| 19 | | − | const first = fiscalStart(s, closing_month); |
| 20 | | − | const n = fy.getFullYear() - first.getFullYear() + 1; |
| 21 | | − | const next = new Date(fy.getFullYear() + 1, fy.getMonth(), 1); |
| 22 | | − | const end = new Date(next.getFullYear(), next.getMonth(), 0); |
| 23 | | − | return { period: n, start: fmt(n === 1 ? s : fy), end: fmt(end), next_start: fmt(next) }; |
| 23 | + | const s = monthIndex(sy, sm); |
| 24 | + | const t = monthIndex(y, mo); |
| 25 | + | if (t < s) return { error: "before_start" }; |
| 26 | + | const firstClose = firstClosingAtOrAfter(s, closing_month); |
| 27 | + | const close = firstClosingAtOrAfter(t, closing_month); |
| 28 | + | const n = (close - firstClose) / 12 + 1; |
| 29 | + | return { period: n, start: ymd(n === 1 ? s : close - 11), end: ymd(close, true), next_start: ymd(close + 1) }; |
| 24 | 30 | | } |