Finish supervisor , 残りはExcelとセキュリティ.

This commit is contained in:
hayano
2024-11-02 23:53:34 +00:00
parent 82d0e55945
commit c6969d7afa
7 changed files with 742 additions and 82 deletions

BIN
.env.swp

Binary file not shown.

Binary file not shown.

View File

@ -522,6 +522,11 @@ class GoalImages(models.Model):
team_name = models.CharField(_("Team name"), max_length=255)
event_code = models.CharField(_("event code"), max_length=255)
cp_number = models.IntegerField(_("CP numner"))
zekken_number = models.TextField(
null=True, # False にする
blank=True, # False にする
help_text="ゼッケン番号"
)
class CheckinImages(models.Model):
user=models.ForeignKey(CustomUser, on_delete=models.DO_NOTHING)
@ -532,6 +537,7 @@ class CheckinImages(models.Model):
cp_number = models.IntegerField(_("CP numner"))
class GpsCheckin(models.Model):
id = models.AutoField(primary_key=True) # 明示的にidフィールドを追加
path_order = models.IntegerField(
null=False,
help_text="チェックポイントの順序番号"
@ -637,7 +643,7 @@ class GpsCheckin(models.Model):
]
def __str__(self):
return f"{self.event_code}-{self.zekken_number}-{self.path_order}"
return f"{self.event_code}-{self.zekken_number}-{self.path_order}-buy:{self.buy_flag}-valid:{self.validate_location}-point:{self.points}"
def save(self, *args, **kwargs):
# 作成時・更新時のタイムスタンプを自動設定

View File

@ -124,6 +124,9 @@ urlpatterns += [
path('export_excel/<int:zekken_number>/<str:event_code>/', views.export_excel, name='export_excel'),
# for Supervisor Web app
path('test/', views.test_api, name='test_api'),
path('update-goal-time/', views.update_goal_time, name='update-goal-time'),
path('get-goalimage/', views.get_goalimage, name='get-goalimage'),
]
if settings.DEBUG:

View File

@ -89,6 +89,7 @@ from io import BytesIO
from django.urls import get_resolver
import os
import json
logger = logging.getLogger(__name__)
@ -227,6 +228,43 @@ class LocationViewSet(viewsets.ModelViewSet):
serializer_class=LocationSerializer
filter_fields=["prefecture", "location_name"]
def get_queryset(self):
queryset = Location.objects.all()
logger.info("=== Location API Called ===")
# リクエストパラメータの確認
group_filter = self.request.query_params.get('group__contains')
logger.info(f"Request params: {dict(self.request.query_params)}")
logger.info(f"Group filter: {group_filter}")
if group_filter:
# フィルタ適用前のデータ数
total_count = queryset.count()
logger.info(f"Total locations before filter: {total_count}")
# フィルタの適用
queryset = queryset.filter(group__contains=group_filter)
# フィルタ適用後のデータ数
filtered_count = queryset.count()
logger.info(f"Filtered locations count: {filtered_count}")
# フィルタされたデータのサンプル最初の5件
sample_data = queryset[:5]
logger.info("Sample of filtered data:")
for loc in sample_data:
logger.info(f"ID: {loc.id}, Name: {loc.location_name}, Group: {loc.group}")
return queryset
def list(self, request, *args, **kwargs):
try:
response = super().list(request, *args, **kwargs)
logger.info(f"Response data count: {len(response.data['features'])}")
return response
except Exception as e:
logger.error(f"Error in list method: {str(e)}", exc_info=True)
raise
class Location_lineViewSet(viewsets.ModelViewSet):
queryset=Location_line.objects.all()
@ -2374,12 +2412,32 @@ def get_team_info(request, zekken_number):
event_code=entry.event.event_name
).order_by('-goaltime').first()
# Nullチェックを追加してからログ出力
goalimage_url = None
goaltime = None
if goal_record:
try:
goaltime = goal_record.goaltime
if goal_record.goalimage and hasattr(goal_record.goalimage, 'url'):
goalimage_url = request.build_absolute_uri(goal_record.goalimage.url)
logger.info(f"get_team_info record.goalimage_url={goalimage_url}")
else:
logger.info("Goal record exists but no image found")
except ValueError as e:
logger.warning(f"Error accessing goal image: {str(e)}")
else:
logger.info("No goal record found for team")
return Response({
'team_name': entry.team.team_name,
'members': ', '.join([f"{m.lastname} {m.firstname}" for m in members]),
'event_code': entry.event.event_name,
'start_datetime': entry.event.start_datetime,
'end_datetime': goal_record.goaltime if goal_record else None,
'end_datetime': goaltime, #goal_record.goaltime if goal_record else None,
'goal_photo': goalimage_url, #goal_record.goalimage if goal_record else None,
'duration': entry.category.duration.total_seconds()
})
@ -2475,20 +2533,80 @@ def get_checkins(request, *args, **kwargs):
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['POST'])
def update_checkins(request):
try:
with transaction.atomic():
for update in request.data:
update_base = request.data
logger.info(f"Processing update data: {update_base}")
zekken_number = update_base['zekken_number']
event_code = update_base['event_code']
for update in update_base['checkins']:
if 'id' in update and int(update['id'])>0:
# 既存レコードの更新
logger.info(f"Updating existing checkin : {update}")
try:
checkin = GpsCheckin.objects.get(id=update['id'])
checkin.path_order = update['path_order']
checkin.validate_location = update['validate_location']
logger.info(f"Updating existing checkin: {checkin}")
# 既存レコードの更新
checkin.path_order = update['order']
checkin.buy_flag = update.get('buy_flag', False)
checkin.validate_location = update.get('validation', False)
checkin.points = update.get('points', 0)
checkin.save()
return Response({'status': 'success'})
logger.info(f"Updated existing checkin result: {checkin}")
except GpsCheckin.DoesNotExist:
logger.error(f"Checkin with id {update['id']} not found")
return Response(
{"error": f"Checkin with id {update['id']} not found"},
status=status.HTTP_404_NOT_FOUND
)
for update in update_base['checkins']:
if 'id' in update and int(update['id'])==0:
# 新規レコードの作成
logger.info("Creating new checkin:{update}")
try:
checkin = GpsCheckin.objects.create(
zekken_number=update_base['zekken_number'],
event_code=update_base['event_code'],
path_order=update['order'],
cp_number=update['cp_number'],
validate_location=update.get('validation', False),
buy_flag=update.get('buy_flag', False),
points=update.get('points', 0),
create_at=timezone.now(),
update_at=timezone.now(),
create_user=request.user.email if request.user.is_authenticated else None,
update_user=request.user.email if request.user.is_authenticated else None
)
logger.info(f"Updated existing checkin result: {checkin}")
except KeyError as e:
logger.error(f"Missing required field: {str(e)}")
return Response(
{"error": f"Missing required field: {str(e)}"},
status=status.HTTP_400_BAD_REQUEST
)
return Response({'status': 'success', 'message': 'Checkins updated successfully'})
except Exception as e:
logger.error(f"Error in update_checkins: {str(e)}", exc_info=True)
return Response(
{"error": "Failed to update checkins", "detail": str(e)},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['GET'])
def export_excel(request, zekken_number):
# エントリー情報の取得
entry = Entry.objects.select_related('team').get(zekken_number=zekken_number)
entry = Entry.objects.select_related('team','event').get(zekken_number=zekken_number)
checkins = GpsCheckin.objects.filter(zekken_number=zekken_number).order_by('path_order')
# Excelファイルの生成
@ -2539,3 +2657,145 @@ def test_api(request):
logger.debug("Test API endpoint called")
return JsonResponse({"status": "API is working"})
@api_view(['GET'])
#@authentication_classes([TokenAuthentication])
#@permission_classes([IsAuthenticated])
def get_goalimage(request):
"""
ゼッケン番号とイベントコードに基づいてゴール画像情報を取得するエンドポイント
Parameters:
zekken_number (str): ゼッケン番号
event_code (str): イベントコード
Returns:
Response: ゴール画像情報を含むJSONレスポンス
"""
try:
logger.debug(f"get_goalimage called with params: {request.GET}")
# リクエストパラメータを取得
zekken_number = request.GET.get('zekken_number')
event_code = request.GET.get('event_code')
logger.debug(f"Searching for goal records with zekken_number={zekken_number}, event_code={event_code}")
# パラメータの検証
if not zekken_number or not event_code:
return Response(
{"error": "zekken_number and event_code are required"},
status=status.HTTP_400_BAD_REQUEST
)
# ゴール画像レコードを検索(最も早いゴール時間のレコードを取得)
goal_records = GoalImages.objects.filter(
zekken_number=zekken_number,
event_code=event_code
).order_by('goaltime')
logger.debug(f"Found {goal_records.count()} goal records")
if not goal_records.exists():
return Response(
{"message": "No goal records found"},
status=status.HTTP_404_NOT_FOUND
)
# 最も早いゴール時間のレコードcp_number = 0を探す
valid_goal = goal_records.filter(cp_number=0).first()
if not valid_goal:
return Response(
{"message": "No valid goal record found"},
status=status.HTTP_404_NOT_FOUND
)
# シリアライザでデータを整形
serializer = GolaImageSerializer(valid_goal)
# レスポンスデータの構築
response_data = {
"goal_record": serializer.data,
"total_records": goal_records.count(),
"has_multiple_records": goal_records.count() > 1
}
logger.info(f"Retrieved goal record for zekken_number {zekken_number} in event {event_code}")
return Response(response_data)
except Exception as e:
logger.error(f"Error retrieving goal record: {str(e)}", exc_info=True)
return Response(
{"error": f"Failed to retrieve goal record: {str(e)}"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
@api_view(['POST'])
#@authentication_classes([TokenAuthentication])
#@permission_classes([IsAuthenticated])
def update_goal_time(request):
try:
logger.info(f"update_goal_time:{request}")
# リクエストからデータを取得
zekken_number = request.data.get('zekken_number')
event_code = request.data.get('event_code')
team_name = request.data.get('team_name')
goal_time_str = request.data.get('goaltime')
logger.info(f"zekken_number={zekken_number},event_code={event_code},team_name={team_name},goal_time={goal_time_str}")
# 入力バリデーション
#if not all([zekken_number, event_code, team_name, goal_time_str]):
# return Response(
# {"error": "Missing required fields"},
# status=status.HTTP_400_BAD_REQUEST
# )
try:
# 文字列からdatetimeオブジェクトに変換
goal_time = datetime.strptime(goal_time_str, '%Y-%m-%dT%H:%M:%S')
except ValueError:
return Response(
{"error": "Invalid goal time format"},
status=status.HTTP_400_BAD_REQUEST
)
# 既存のゴール記録を探す
goal_record = GoalImages.objects.filter(
team_name=team_name,
event_code=event_code
).first()
if goal_record:
# 既存の記録を更新
goal_record.goaltime = goal_time
goal_record.save()
logger.info(f"Updated goal time for team {team_name} in event {event_code}")
else:
# 新しい記録を作成
entry = Entry.objects.get(zekken_number=zekken_number, event__event_name=event_code)
GoalImages.objects.create(
user=entry.owner,
goaltime=goal_time,
team_name=team_name,
event_code=event_code,
cp_number=0 # ゴール地点を表すCP番号
)
logger.info(f"Created new goal time record for team {team_name} in event {event_code}")
return Response({"message": "Goal time updated successfully"})
except Entry.DoesNotExist:
logger.error(f"Entry not found for zekken_number {zekken_number} in event {event_code}")
return Response(
{"error": "Entry not found"},
status=status.HTTP_404_NOT_FOUND
)
except Exception as e:
logger.error(f"Error updating goal time: {str(e)}")
return Response(
{"error": f"Failed to update goal time: {str(e)}"},
status=status.HTTP_500_INTERNAL_SERVER_ERROR
)

Binary file not shown.

View File

@ -94,6 +94,7 @@
<th class="px-1 py-3 text-left text-xs font-medium text-gray-500 uppercase">買物申請</th>
<th class="px-1 py-3 text-left text-xs font-medium text-gray-500 uppercase">通過審査</th>
<th class="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase">獲得点数</th>
<th class="w-8"></th> <!-- 削除ボタン用 -->
</tr>
</thead>
<tbody id="checkinList" class="bg-white divide-y divide-gray-200">
@ -104,7 +105,7 @@
<!-- アクションボタン -->
<div class="mt-6 flex justify-end space-x-4">
<button onclick="showAddCPModal()" class="px-4 py-2 bg-blue-500 text-white rounded">
<button onclick="showAddCPDialog()" class="px-4 py-2 bg-blue-500 text-white rounded">
新規CP追加
</button>
<button id="saveButton" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
@ -119,7 +120,9 @@
<script>
// APIのベースURLを環境に応じて設定
const API_BASE_URL = '/api';
const API_BASE_URL = 'http://rogaining.sumasen.net/api';
let original_goal_time = '';
let selected_event_code = '';
// イベントリスナーの設定
document.addEventListener('DOMContentLoaded', function() {
@ -143,12 +146,14 @@
alert('イベントコードを選択してください');
return;
}
selected_event_code = eventCode;
loadTeamData(e.target.value, eventCode);
});
// イベントコード変更時の処理
document.getElementById('eventCode').addEventListener('change', function(e) {
eventCodeSelect.addEventListener('change', function(e) {
loadZekkenNumbers(e.target.value);
handleEventSelect(e.target.value);
});
// チェックボックス変更時の処理
@ -158,6 +163,7 @@
// }
//});
// 保存ボタンの処理
document.getElementById('saveButton').addEventListener('click', saveChanges);
@ -335,7 +341,7 @@
validateElement.classList.add('text-red-600');
validateElement.classList.remove('text-green-600');
} else {
validateElement.textContent = '合格';
validateElement.textContent = '完走';
validateElement.classList.add('text-green-600');
validateElement.classList.remove('text-red-600');
}
@ -426,6 +432,7 @@
// ゴール時刻の表示を更新
updateGoalTimeDisplay(teamData.end_datetime);
original_goal_time = teamData.end_datetime;
// イベントコードに対応するイベントを検索
//const event = eventData.find(e => e.code === document.getElementById('eventCode').value);
@ -444,11 +451,35 @@
'未ゴール';
goalTimeDisplay.textContent = goalTime;
console.info('teamData.goal_photo = ',teamData.goal_photo );
if (goalTime === '-') {
goalTimeDisplay.classList.add('cursor-pointer');
goalTimeDisplay.onclick = () => editGoalTime(goalTimeDisplay);
}
console.info("step 0");
// ゴール時計の表示を更新
const goalTimeElement = document.getElementById('goalTime');
if (teamData.goal_photo) {
// 画像要素を作成
console.info("step 1");
const img = document.createElement('img');
img.src = teamData.goal_photo;
img.classList.add('h-32', 'w-auto', 'object-contain', 'cursor-pointer');
img.onclick = () => showLargeImage(teamData.goal_photo);
console.info("step 2");
// 既存の内容をクリアして画像を追加
goalTimeElement.innerHTML = '';
goalTimeElement.appendChild(img);
console.info("Goal photo displayed: ",teamData.goal_photo);
} else {
goalTimeElement.textContent = '画像なし';
console.info("No goal photo available");
}
// チェックインリストの更新
const tbody = document.getElementById('checkinList');
@ -460,23 +491,24 @@
checkinsData.forEach((checkin, index) => {
const tr = document.createElement('tr');
tr.dataset.id = checkin.id;
tr.dataset.local_id = index+1;
tr.dataset.cpNumber = checkin.cp_number;
tr.dataset.buyPoint = checkin.buy_point;
tr.dataset.checkinPoint = checkin.checkin_point;
tr.dataset.path_order = index+1;
const bgColor = checkin.buy_point > 0 ? 'bg-blue-100' : '';
tr.innerHTML = `
<td class="px-1 py-3 cursor-move">
<i class="fas fa-bars text-gray-400"></i>
</td>
<td class="px-2 py-3">${checkin.path_order}</td>
<td class="px-2 py-3">${tr.dataset.path_order}</td>
<td class="px-2 py-3">
${checkin.photos ?
`<img src="/media/compressed/${checkin.photos}" class="h-20 w-20 object-cover rounded" onclick="showLargeImage(this.src)">` : ''}
</td>
<td class="px-2 py-3">
${checkin.image_address ?
`<img src="${checkin.image_address}" class="h-20 w-20 object-cover rounded" onclick="showLargeImage(this.src)">` : ''}
${checkin.cp_number===-1 || checkin.image_address===null ? "" : `<img src="${checkin.image_address}" class="h-20 w-20 object-cover rounded" onclick="showLargeImage(this.src)">`}
</td>
<td class="px-2 py-3 ${bgColor}">
<div class="font-bold">${checkin.sub_loc_id}</div>
@ -498,6 +530,8 @@
onchange="updatePoints(this)">
</td>
<td class="px-2 py-3 point-value">${calculatePointsForCheckin(checkin)}</td>
<td class="px-2 py-4">
</td>
`;
tbody.appendChild(tr);
@ -603,54 +637,44 @@
document.getElementById('latePoints').textContent = teamInfo.late_points;
}
// 通過リストの表示...呼ばれていない
function nouse_updateCheckinList(checkins) {
const tbody = document.getElementById('checkinList');
tbody.innerHTML = '';
checkins.forEach((checkin, index) => {
const tr = document.createElement('tr');
tr.dataset.id = checkin.id;
tr.dataset.cpNumber = checkin.cp_number;
const bgColor = checkin.buy_point > 0 ? 'bg-blue-100' : 'bg-red-100';
tr.innerHTML = `
<td class="px-6 py-4">${checkin.path_order}</td>
<td class="px-6 py-4 ${bgColor}">
<div class="font-bold">${checkin.sub_loc_id}</div>
<div class="text-sm">${checkin.location_name}</div>
</td>
<td class="px-6 py-4">
${checkin.image_address ?
`<img src="${checkin.image_address}" class="h-20 w-20 object-cover rounded">` : ''}
${checkin.receipt_address && checkin.buy_flag ?
`<img src="${checkin.receipt_address}" class="h-20 w-20 object-cover rounded ml-2">` : ''}
</td>
<td class="px-6 py-4">${checkin.create_at || '不明'}</td>
<td class="px-6 py-4">
<input type="checkbox"
${checkin.validate_location ? 'checked' : ''}
class="h-4 w-4 text-blue-600 rounded validate-checkbox"
onchange="updatePoints(this)">
</td>
<td class="px-6 py-4">
${checkin.buy_point > 0 ? `
<input type="checkbox"
${checkin.buy_flag ? 'checked' : ''}
class="h-4 w-4 text-green-600 rounded buy-checkbox"
onchange="updateBuyPoints(this)">
` : ''}
</td>
<td class="px-6 py-4 point-value">${checkin.points}</td>
`;
tbody.appendChild(tr);
});
calculateTotalPoints();
function deleteRow(rowIndex) {
try {
if (!confirm(`このチェックインを削除してもよろしいですか?`)) {
return;
}
const tbody = document.getElementById('checkinList');
const rows = tbody.getElementsByTagName('tr');
let target = null;
for (const row of rows) {
if( Number(row.dataset.local_id) === Number(rowIndex) ) {
target = row;
break;
}
}
// 対象の行が見つからなかった場合
if (!target) {
throw new Error('Target row not found');
}
target.remove();
updatePathOrders();
// ポイントを再計算
calculatePoints();
} catch (error) {
console.error('Error deleting row:', error);
alert('行の削除に失敗しました');
}
}
// 削除機能
async function deleteCheckin(id) {
async function old_deleteCheckin(id) {
if (!confirm('このチェックインを削除してもよろしいですか?')) {
return;
}
@ -794,6 +818,52 @@
document.body.appendChild(modal);
}
// 新規CP追加のための関数
function showAddCPDialog() {
const cpInput = prompt('追加するCPをカンマ区切りで入力してくださいCP1,CP2,CP3');
if (!cpInput) return;
const cpList = cpInput.split(',').map(cp => cp.trim()).filter(cp => cp);
if (cpList.length === 0) {
alert('有効なCPを入力してください');
return;
}
// 既存のチェックインデータを取得
const existingCheckins = getCurrentCheckins(); // 現在の表示データを取得する関数
const newCheckins = [];
console.info('existingCheckins.length =',existingCheckins.length);
cpList.forEach((cp,index) => {
cploc = findLocationByCP(cp);
console.info('location=',cploc);
console.info('index = ',index);
newCheckins.push({
id: cploc.id,
order: existingCheckins.length + index + 1,
photos: cploc.photos,
actual_photo: '-',
subLocId: cploc.subLocId,
cp: cploc.cp,
location_name: cploc.name,
checkinPoint: Number(cploc.checkinPoint),
buyPoint: Number(cploc.buyPoint),
points: Number(cploc.checkinPoint),
buy_flag: false,
validate_location: true
});
});
console.info('newCheckins=',newCheckins);
// 新しいCPを表に追加
addCheckinsToTable(newCheckins);
updatePathOrders();
calculatePoints(); // 総合ポイントの計算
}
// 新規CP追加用のモーダル
function showAddCPModal() {
const modal = document.createElement('div');
@ -860,7 +930,9 @@
function updatePathOrders() {
const rows = Array.from(document.getElementById('checkinList').children);
rows.forEach((row, index) => {
console.info('row=',row);
row.children[1].textContent = index + 1;
row.dataset.path_order = index + 1;
});
}
@ -904,33 +976,352 @@
return new Date(dateString).toLocaleString('ja-JP');
}
function saveChanges() {
const rows = Array.from(document.getElementById('checkinList').children);
const updates = rows.map((row, index) => ({
id: row.dataset.id,
path_order: index + 1,
validate_location: row.querySelector('.validate-checkbox').checked
}));
// 保存機能の実装
async function saveChanges() {
const zekkenNumber = document.querySelector('#zekkenNumber').value;
const eventCode = document.querySelector('#eventCode').value;
fetch('${API_BASE_URL}/update_checkins', {
const display = document.getElementById('goalTimeDisplay');
if (!display) {
console.error('Goal time elements not found');
return;
}
let goalTime = display.textContent;
console.info('Goal time = ',goalTime);
try {
const checkins = getCurrentCheckins(); // 現在の表示データを取得
const response = await fetch(`${API_BASE_URL}/update_checkins/`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates)
}).then(response => {
if (response.ok) {
alert('保存しました');
} else {
alert('保存に失敗しました');
}
body: JSON.stringify({
zekken_number: zekkenNumber,
event_code: eventCode,
checkins: checkins
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
function exportExcel() {
const success = await saveGoalTime(goalTime, zekkenNumber, eventCode);
if (success) {
alert('ゴール時間を保存しました');
}
alert('保存が完了しました');
} catch (error) {
console.error('保存中にエラーが発生しました:', error);
alert('保存中にエラーが発生しました');
}
}
// ゴール時間の更新と新規作成を処理する関数
async function saveGoalTime(goalTimeStr, zekkenNumber, eventCode) {
try {
const [teamResponse, checkinsResponse] = await Promise.all([
fetch(`${API_BASE_URL}/team_info/${zekkenNumber}/`),
]);
// 各レスポンスのステータスを個別にチェック
if (!teamResponse.ok)
throw new Error(`Team info fetch failed with status ${teamResponse.status}`);
const teamData = await teamResponse.json();
const teamName = teamData.team_name;
// 日付と時刻を結合して完全な日時文字列を作成
//const currentDate = new Date().toISOString().split('T')[0];
//const fullGoalTime = `${currentDate}T${goalTimeStr}:00`;
const formattedDateTime = goalTimeStr
.replace(/\//g, '-') // スラッシュをハイフンに変換
.replace(' ', 'T'); // スペースをTに変換
console.log(formattedDateTime); // "2024-10-26T12:59:13"
console.info('goaltime=',formattedDateTime);
// 新規レコードを作成または既存レコードを更新
const createResponse = await fetch('/api/update-goal-time/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
//'Authorization': `Token ${localStorage.getItem('token')}`,
},
body: JSON.stringify({
goaltime: formattedDateTime, //fullGoalTime,
team_name: teamName,
event_code: eventCode,
zekken_number: zekkenNumber
})
});
if (!createResponse.ok) {
throw new Error('Failed to create new goal record');
}
return true;
} catch (error) {
console.error('Error processing goal time:', error);
alert(`ゴール時間の処理に失敗しました: ${error.message}`);
return false;
}
}
// 通過証明書出力機能の実装
async function exportExcel() {
const zekkenNumber = document.querySelector('#zekkenNumber').value;
const eventCode = document.querySelector('#eventCode').value;
try {
const response = await fetch(`${API_BASE_URL}/export_excel/${zekkenNumber}/${eventCode}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Blobとしてレスポンスを取得
const blob = await response.blob();
// ダウンロードリンクを作成
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `通過証明書_${zekkenNumber}_${eventCode}.xlsx`;
// リンクをクリックしてダウンロードを開始
document.body.appendChild(a);
a.click();
// クリーンアップ
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error('エクスポート中にエラーが発生しました:', error);
alert('エクスポート中にエラーが発生しました');
}
}
function old_exportExcel() {
const zekkenNumber = document.getElementById('zekkenNumber').value;
window.location.href = `/api/export-excel/${zekkenNumber}`;
}
// 現在の表示データを取得する補助関数
function getCurrentCheckins() {
const tbody = document.querySelector('table tbody');
const checkins = [];
// テーブルの行をループして現在のデータを収集
tbody.querySelectorAll('tr').forEach((row, index) => {
const cells = row.cells;
// チェックボックスの要素を正しく取得
const buyFlagCheckbox = cells[6].querySelector('input[type="checkbox"]');
const validationCheckbox = cells[7].querySelector('input[type="checkbox"]');
checkins.push({
id: row.dataset.id,
order: index + 1,
cp_number: row.dataset.cpNumber,
buy_flag: buyFlagCheckbox ? buyFlagCheckbox.checked : false,
validation: validationCheckbox ? validationCheckbox.checked : false,
points: parseInt(cells[8].textContent) || 0
});
});
return checkins;
}
// テーブルにチェックインを追加する補助関数
function addCheckinsToTable(checkins) {
const table = document.querySelector('table tbody');
checkins.forEach(checkin => {
const row = document.createElement('tr');
console.info('checkin=',checkin);
row.dataset.id = 0;
row.dataset.local_id = checkin.order; // Unique
row.dataset.cpNumber = checkin.cp;
row.dataset.checkinPoint = checkin.checkinPoint;
row.dataset.buyPoint = checkin.buyPoint;
row.dataset.path_order = checkin.order; // reorderable
const bgColor = checkin.buyPoint > 0 ? 'bg-blue-100' : '';
row.innerHTML = `
<td class="px-1 py-3 cursor-move">
<i class="fas fa-bars text-gray-400"></i>
</td>
<td class="px-2 py-3">${checkin.order}</td>
<td class="px-2 py-3">
${checkin.photos ?
`<img src="/media/compressed/${checkin.photos}" class="h-20 w-20 object-cover rounded" onclick="showLargeImage(this.src)">` : ''}
</td>
<td class="px-2 py-3">
${checkin.image_address ?
`<img src="${checkin.image_address}" class="h-20 w-20 object-cover rounded" onclick="showLargeImage(this.src)">` : '無し'}
</td>
<td class="px-2 py-3 ${bgColor}">
<div class="font-bold">${checkin.subLocId}</div>
<div class="text-sm">${checkin.location_name}</div>
</td>
<td class="px-2 py-3">不明</td>
<td class="px-1 py-3">
${checkin.buyPoint > 0 ? `
<input type="checkbox"
${checkin.buy_flag ? 'checked' : ''}
class="h-4 w-4 text-green-600 rounded buy-checkbox"
onchange="updatePoints(this)">
` : ''}
</td>
<td class="px-1 py-3">
<input type="checkbox"
${checkin.validate_location ? 'checked' : ''}
class="h-4 w-4 text-blue-600 rounded validate-checkbox"
onchange="updatePoints(this)">
</td>
<td class="px-2 py-3 point-value">${checkin.checkinPoint}</td>
<td class="px-2 py-4">
<button onclick="deleteRow(${row.dataset.local_id})"
class="text-red-600 hover:text-red-800">
<i class="fas fa-trash"></i>
</button>
</td>
`;
table.appendChild(row);
});
}
// グローバルな状態管理
let loadedLocations = [];
let currentEventCode = null;
// チェックポイントデータをロードする関数
async function loadLocations(eventCode) {
try {
console.info('loadLocations-1:',eventCode);
if (!eventCode) {
console.error('Event code is required');
return;
}
// 既に同じイベントのデータがロードされている場合はスキップ
if (currentEventCode === eventCode && loadedLocations.length > 0) {
console.log('Locations already loaded for this event');
return loadedLocations;
}
console.info('loadLocations-2:',eventCode);
// group__containsフィルターを使用してクエリパラメータを構築
const params = new URLSearchParams({
group__contains: eventCode
});
// Location APIを使用してデータを取得
const response = await fetch(`/api/location/?${params}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
});
// レスポンスをJSONとして解決
const data = await response.json();
console.info('loadLocations-3:', data);
if (!response.ok) {
console.info('loadLocations-3: Bad Response :',response);
throw new Error(`HTTP error! status: ${response.status}`);
}
console.info('loadLocations-4:',eventCode);
// 取得したデータを処理して保存
loadedLocations = data.features.map(feature => ({
cp: feature.properties.cp,
name: feature.properties.location_name,
subLocId: feature.properties.sub_loc_id,
checkinPoint: feature.properties.checkin_point,
buyPoint: feature.properties.buy_point,
photos: feature.properties.photos,
group: feature.properties.group,
coordinates: feature.geometry.coordinates[0],
latitude: feature.geometry.coordinates[0][1],
longitude: feature.geometry.coordinates[0][0]
})).filter(location => location.group && location.group.includes(eventCode));
currentEventCode = eventCode;
console.info(`Loaded ${loadedLocations.length} locations for event ${eventCode}`);
console.info('loadedLocation[0]=',loadedLocations[0]);
return loadedLocations;
} catch (error) {
console.error('Error loading locations:', error);
throw error;
}
}
// イベント選択時のハンドラー
async function handleEventSelect(eventCode) {
console.info('handleEventSelect : ',eventCode);
try {
//document.getElementById('loading').style.display = 'block';
await loadLocations(eventCode);
//document.getElementById('loading').style.display = 'none';
} catch (error) {
console.error('Error handling event selection:', error);
//document.getElementById('loading').style.display = 'none';
alert('チェックポイントの読み込みに失敗しました。');
}
}
// ロードされたロケーションデータを取得する関数
function getLoadedLocations() {
return loadedLocations;
}
// 指定されたCP番号のロケーションを取得する関数
function findLocationByCP(cpNumber) {
if (!loadedLocations.length) {
console.warn('Locations not loaded yet');
return null;
}
// cpプロパティを数値として比較
const found = loadedLocations.find(loc => Number(loc.cp) === Number(cpNumber));
if (!found) {
console.warn(`Location with CP number ${cpNumber} not found`);
return null;
}
console.info(`Found location with CP ${cpNumber}:`, found);
return found;
}
</script>
</body>
</html>