✅ 出勤状況の判定ロジック(改良版)
条件:
- **最新の記録が「出勤」**で
- その時刻が「当日中(同日23:59:59まで)」
→ 「出勤中」と表示。
それ以外(出勤記録が前日以前 or 最終記録が「退勤」)
→ 「退勤済み」と表示。
🔧 修正対象箇所
以下の部分を修正します:
if (!attendanceSnapshot.empty) {
const last = attendanceSnapshot.docs[0].data();
status = last.type === "出勤" ? "出勤中" : "退勤済み";
}
✅ 修正後コード
if (!attendanceSnapshot.empty) {
const last = attendanceSnapshot.docs[0].data();
const lastTimestamp = last.timestamp.toDate();
const now = new Date();
const isSameDay = lastTimestamp.getFullYear() === now.getFullYear()
&& lastTimestamp.getMonth() === now.getMonth()
&& lastTimestamp.getDate() === now.getDate();
if (last.type === "出勤" && isSameDay) {
status = "出勤中";
} else {
status = "退勤済み";
}
}
✅ 説明
last.type === "出勤"
:直近の記録が「出勤」であるisSameDay
:その出勤記録が「今日のもの」である- 両方満たせば「出勤中」
- どちらかを満たさなければ「退勤済み」
✅ 出退勤状況+履歴表示(完成版HTML)
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<title>出退勤履歴一覧</title>
</head>
<body>
<h1>管理者ページ</h1>
<table border="1">
<thead>
<tr>
<th>名前</th>
<th>メールアドレス</th>
<th>出勤状況</th>
</tr>
</thead>
<tbody id="userList"></tbody>
</table>
<div id="historyContainer" style="margin-top: 40px; display:none;">
<h2 id="historyTitle"></h2>
<div>
<label for="yearSelect">年:</label>
<select id="yearSelect"></select>
<label for="monthSelect">月:</label>
<select id="monthSelect"></select>
</div>
<table border="1" id="historyTable" style="margin-top: 10px;">
<thead>
<tr>
<th>日付</th>
<th>時刻</th>
<th>種類</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.11.0/firebase-app.js";
import {
getFirestore,
collection,
getDocs,
query,
where,
orderBy,
limit
} from "https://www.gstatic.com/firebasejs/10.11.0/firebase-firestore.js";
const firebaseConfig = {
apiKey: "あなたのAPIキー",
authDomain: "あなたのプロジェクトID.firebaseapp.com",
projectId: "あなたのプロジェクトID",
storageBucket: "あなたのプロジェクトID.appspot.com",
messagingSenderId: "送信者ID",
appId: "アプリID"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
async function loadUsers() {
const userList = document.getElementById("userList");
userList.innerHTML = "";
try {
const usersSnapshot = await getDocs(collection(db, "users"));
for (const doc of usersSnapshot.docs) {
const user = doc.data();
const uid = doc.id;
let status = "不明";
try {
const attendanceQuery = query(
collection(db, "attendance"),
where("uid", "==", uid),
orderBy("timestamp", "desc"),
limit(1)
);
const attendanceSnapshot = await getDocs(attendanceQuery);
if (!attendanceSnapshot.empty) {
const last = attendanceSnapshot.docs[0].data();
const lastTimestamp = last.timestamp.toDate();
const now = new Date();
const isSameDay =
lastTimestamp.getFullYear() === now.getFullYear() &&
lastTimestamp.getMonth() === now.getMonth() &&
lastTimestamp.getDate() === now.getDate();
if (last.type === "出勤" && isSameDay) {
status = "出勤中";
} else {
status = "退勤済み";
}
}
} catch (e) {
console.warn("出退勤データ取得エラー:", e);
}
const row = `
<tr>
<td><a href="#" onclick="loadHistory('${uid}', '${user.name}'); return false;">${user.name}</a></td>
<td>${user.email}</td>
<td>${status}</td>
</tr>
`;
userList.innerHTML += row;
}
} catch (error) {
console.error("ユーザーデータ取得エラー:", error);
}
}
window.loadHistory = async function(uid, name) {
const historyContainer = document.getElementById("historyContainer");
const historyTitle = document.getElementById("historyTitle");
historyTitle.innerText = `${name} さんの出退勤履歴`;
historyContainer.style.display = "block";
await populateYearMonthSelects(uid);
};
async function populateYearMonthSelects(uid) {
const attendanceRef = collection(db, "attendance");
const q = query(attendanceRef, where("uid", "==", uid), orderBy("timestamp", "desc"));
const snapshot = await getDocs(q);
const dates = snapshot.docs.map(doc => doc.data().timestamp.toDate());
const years = [...new Set(dates.map(d => d.getFullYear()))];
const yearSelect = document.getElementById("yearSelect");
const monthSelect = document.getElementById("monthSelect");
yearSelect.innerHTML = years.map(y => `<option value="${y}">${y}</option>`).join("");
yearSelect.onchange = () => {
const selectedYear = parseInt(yearSelect.value);
const months = [...new Set(dates
.filter(d => d.getFullYear() === selectedYear)
.map(d => d.getMonth() + 1))];
monthSelect.innerHTML = months.map(m => `<option value="${m}">${m}</option>`).join("");
displayHistory(uid, selectedYear, parseInt(monthSelect.value));
};
monthSelect.onchange = () => {
displayHistory(uid, parseInt(yearSelect.value), parseInt(monthSelect.value));
};
yearSelect.dispatchEvent(new Event('change'));
}
async function displayHistory(uid, year, month) {
const attendanceRef = collection(db, "attendance");
const q = query(attendanceRef, where("uid", "==", uid), orderBy("timestamp", "desc"));
const snapshot = await getDocs(q);
const tbody = document.querySelector("#historyTable tbody");
tbody.innerHTML = "";
snapshot.docs.forEach(doc => {
const data = doc.data();
const ts = data.timestamp.toDate();
if (ts.getFullYear() === year && (ts.getMonth() + 1) === month) {
const row = `
<tr>
<td>${ts.getFullYear()}-${ts.getMonth() + 1}-${ts.getDate()}</td>
<td>${ts.getHours()}:${ts.getMinutes().toString().padStart(2, "0")}</td>
<td>${data.type}</td>
</tr>
`;
tbody.innerHTML += row;
}
});
}
window.onload = loadUsers;
</script>
</body>
</html>
🔍 補足(動作仕様)
機能 | 説明 |
---|---|
✅ 出勤状況判定 | 最新が「出勤」で、かつ「今日中」→「出勤中」 |
✅ 翌日以降 | 出勤記録が昨日以前 →「退勤済み」とみなす |
✅ 履歴表示 | 名前クリックで年・月ごとに履歴表示 |
✅ UI補助 | プルダウンで年月切り替え可 |