Compare commits
2 Commits
c6969d7afa
...
exdb-2
| Author | SHA1 | Date | |
|---|---|---|---|
| e01d2e7ea6 | |||
| d017da17d4 |
@ -48,6 +48,7 @@ INSTALLED_APPS = [
|
||||
'django.contrib.staticfiles',
|
||||
'django.contrib.gis',
|
||||
'rest_framework',
|
||||
'rest_framework.authtoken',
|
||||
'rest_framework_gis',
|
||||
'knox',
|
||||
'leaflet',
|
||||
@ -215,7 +216,10 @@ LEAFLET_CONFIG = {
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ),
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': ['knox.auth.TokenAuthentication','rest_framework.authentication.TokenAuthentication', ],
|
||||
'DEFAULT_PERMISSION_CLASSES': [
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
|
||||
BIN
rog/.DS_Store
vendored
BIN
rog/.DS_Store
vendored
Binary file not shown.
@ -522,11 +522,6 @@ 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)
|
||||
@ -537,7 +532,6 @@ 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="チェックポイントの順序番号"
|
||||
@ -643,7 +637,7 @@ class GpsCheckin(models.Model):
|
||||
]
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.event_code}-{self.zekken_number}-{self.path_order}-buy:{self.buy_flag}-valid:{self.validate_location}-point:{self.points}"
|
||||
return f"{self.event_code}-{self.zekken_number}-{self.path_order}"
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
# 作成時・更新時のタイムスタンプを自動設定
|
||||
|
||||
@ -124,9 +124,6 @@ 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:
|
||||
|
||||
334
rog/views.py
334
rog/views.py
@ -40,6 +40,7 @@ from rest_framework.response import Response
|
||||
from rest_framework.parsers import JSONParser, MultiPartParser
|
||||
from .serializers import LocationSerializer
|
||||
from django.http import JsonResponse
|
||||
from rest_framework.authentication import TokenAuthentication
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from django.contrib.gis.db.models import Extent, Union
|
||||
|
||||
@ -52,7 +53,7 @@ from django.db.models import Q
|
||||
|
||||
from rest_framework import permissions
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.decorators import api_view, permission_classes
|
||||
from rest_framework.decorators import api_view, permission_classes, authentication_classes
|
||||
from rest_framework.parsers import JSONParser, MultiPartParser
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from django.shortcuts import render
|
||||
@ -89,7 +90,6 @@ from io import BytesIO
|
||||
|
||||
from django.urls import get_resolver
|
||||
import os
|
||||
import json
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@ -228,43 +228,6 @@ 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()
|
||||
@ -2356,6 +2319,8 @@ class UserLastGoalTimeView(APIView):
|
||||
# ----- for Supervisor -----
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def debug_urls(request):
|
||||
"""デバッグ用:利用可能なURLパターンを表示"""
|
||||
resolver = get_resolver()
|
||||
@ -2368,6 +2333,8 @@ def debug_urls(request):
|
||||
return JsonResponse({'urls': urls})
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def get_events(request):
|
||||
logger.debug(f"get_events was called. Path: {request.path}")
|
||||
try:
|
||||
@ -2378,6 +2345,7 @@ def get_events(request):
|
||||
'name': event.event_name,
|
||||
'start_datetime': event.start_datetime,
|
||||
'end_datetime': event.end_datetime,
|
||||
'self_rogaining': event.self_rogaining,
|
||||
} for event in events])
|
||||
logger.debug(f"Returning data: {data}") # デバッグ用ログ
|
||||
return JsonResponse(data, safe=False)
|
||||
@ -2387,7 +2355,10 @@ def get_events(request):
|
||||
{"error": "Failed to retrieve events"},
|
||||
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
)
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def get_zekken_numbers(request, event_code):
|
||||
entries = Entry.objects.filter(
|
||||
event__event_name=event_code,
|
||||
@ -2396,49 +2367,25 @@ def get_zekken_numbers(request, event_code):
|
||||
return Response([entry.zekken_number for entry in entries])
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def get_team_info(request, zekken_number):
|
||||
entry = Entry.objects.select_related('team','event').get(zekken_number=zekken_number)
|
||||
members = Member.objects.filter(team=entry.team)
|
||||
|
||||
start_datetime = entry.event.start_datetime #イベントの規定スタート時刻
|
||||
if entry.event.self_rogaining:
|
||||
#get_checkinsの中で、
|
||||
# start_datetime = -1(ロゲ開始)のcreate_at
|
||||
logger.debug(f"self.rogaining={entry.event.self_rogaining} => start_datetime = -1(ロゲ開始)のcreate_at")
|
||||
|
||||
# チームのゴール時間を取得
|
||||
goal_record = GoalImages.objects.filter(
|
||||
team_name=entry.team.team_name,
|
||||
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': 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()
|
||||
'end_datetime': goal_record.goaltime if goal_record else None,
|
||||
'self_rogaining': entry.event.self_rogaining,
|
||||
})
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
@ -2461,6 +2408,8 @@ def get_image_url(image_path):
|
||||
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def get_checkins(request, *args, **kwargs):
|
||||
#def get_checkins(request, zekken_number, event_code):
|
||||
try:
|
||||
@ -2507,20 +2456,19 @@ def get_checkins(request, *args, **kwargs):
|
||||
|
||||
data.append({
|
||||
'id': c.id,
|
||||
'path_order': c.path_order,
|
||||
'cp_number': c.cp_number,
|
||||
'sub_loc_id': location.sub_loc_id if location else f"#{c.cp_number}",
|
||||
'location_name': location.location_name if location else None,
|
||||
'create_at': formatted_time, #(c.create_at + timedelta(hours=9)).strftime('%H:%M:%S') if c.create_at else None,
|
||||
'validate_location': c.validate_location,
|
||||
'points': c.points or 0,
|
||||
'buy_flag': c.buy_flag,
|
||||
'photos': location.photos if location else None,
|
||||
'image_address': get_image_url(c.image_address),
|
||||
'receipt_address': get_image_url(c.image_receipt),
|
||||
'location_name': location.location_name if location else None,
|
||||
'checkin_point': location.checkin_point if location else None,
|
||||
'buy_point': location.buy_point
|
||||
'path_order': c.path_order, # 通過順序
|
||||
'cp_number': c.cp_number, # 通過ポイント
|
||||
'sub_loc_id': location.sub_loc_id if location else f"#{c.cp_number}", # アプリ上のチェックポイント番号+点数
|
||||
'location_name': location.location_name if location else None, # アプリ上のチェックポイント名
|
||||
'create_at': formatted_time, # 通過時刻
|
||||
'validate_location': c.validate_location, # 通過審査結果
|
||||
'points': c.points or 0, # 審査後の公式得点
|
||||
'buy_flag': c.buy_flag, # お買い物撮影で TRUE
|
||||
'photos': location.photos if location else None, # アプリ上の規定写真
|
||||
'image_address': get_image_url(c.image_address), # 撮影写真
|
||||
'receipt_address': get_image_url(c.image_receipt), # まだ使われていない
|
||||
'checkin_point': location.checkin_point if location else None, # アプリ上の規定ポイント
|
||||
'buy_point': location.buy_point if location else None, # アプリ上の規定買い物ポイント
|
||||
})
|
||||
|
||||
#logger.debug(f"data={data}")
|
||||
@ -2533,80 +2481,24 @@ def get_checkins(request, *args, **kwargs):
|
||||
status=status.HTTP_500_INTERNAL_SERVER_ERROR
|
||||
)
|
||||
|
||||
|
||||
@api_view(['POST'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def update_checkins(request):
|
||||
try:
|
||||
with transaction.atomic():
|
||||
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'])
|
||||
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()
|
||||
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
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
for update in request.data:
|
||||
checkin = GpsCheckin.objects.get(id=update['id'])
|
||||
checkin.path_order = update['path_order']
|
||||
checkin.validate_location = update['validate_location']
|
||||
checkin.save()
|
||||
return Response({'status': 'success'})
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
def export_excel(request, zekken_number):
|
||||
# エントリー情報の取得
|
||||
entry = Entry.objects.select_related('team','event').get(zekken_number=zekken_number)
|
||||
entry = Entry.objects.select_related('team').get(zekken_number=zekken_number)
|
||||
checkins = GpsCheckin.objects.filter(zekken_number=zekken_number).order_by('path_order')
|
||||
|
||||
# Excelファイルの生成
|
||||
@ -2653,149 +2545,9 @@ def export_excel(request, zekken_number):
|
||||
# ----- for Supervisor -----
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes([TokenAuthentication])
|
||||
@permission_classes([IsAuthenticated])
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
111
supervisor/html/index.html.new
Normal file
111
supervisor/html/index.html.new
Normal file
@ -0,0 +1,111 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ja">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="csrf-token" content="${csrfToken}">
|
||||
<title>スーパーバイザーパネル</title>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-gray-50">
|
||||
<div id="app" class="container mx-auto p-4"></div>
|
||||
|
||||
<!-- テンプレート -->
|
||||
<template id="supervisor-panel-template">
|
||||
<div class="bg-white rounded-lg shadow-lg p-6 mb-6">
|
||||
<h1 class="text-2xl font-bold mb-6" role="heading" aria-level="1">スーパーバイザーパネル</h1>
|
||||
|
||||
<!-- 選択フォーム -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
|
||||
<div>
|
||||
<label for="eventCode" class="block text-sm font-medium text-gray-700 mb-2">イベントコード</label>
|
||||
<select id="eventCode" class="w-full border border-gray-300 rounded-md px-3 py-2" aria-label="イベントを選択">
|
||||
<option value="">イベントを選択</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="zekkenNumber" class="block text-sm font-medium text-gray-700 mb-2">ゼッケン番号</label>
|
||||
<select id="zekkenNumber" class="w-full border border-gray-300 rounded-md px-3 py-2" aria-label="ゼッケン番号を選択">
|
||||
<option value="">ゼッケン番号を選択</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="bg-gray-50 p-4 rounded-lg">
|
||||
<div class="text-sm text-gray-500">チーム名</div>
|
||||
<div id="teamName" class="font-semibold" aria-live="polite">-</div>
|
||||
</div>
|
||||
<div class="bg-gray-50 p-4 rounded-lg">
|
||||
<div class="text-sm text-gray-500">メンバー</div>
|
||||
<div id="members" class="font-semibold" aria-live="polite">-</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- チーム情報サマリー -->
|
||||
<div id="team-summary" class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
|
||||
<!-- スタート時刻 -->
|
||||
<div class="bg-gray-50 p-4 rounded-lg">
|
||||
<div class="text-sm text-gray-500">スタート時刻</div>
|
||||
<div id="startTime" class="font-semibold" aria-live="polite">-</div>
|
||||
</div>
|
||||
<!-- ゴール時刻 -->
|
||||
<div class="bg-gray-50 p-4 rounded-lg">
|
||||
<div class="text-sm text-gray-500">ゴール時刻</div>
|
||||
<div class="goal-time-container">
|
||||
<span id="goalTimeDisplay" class="goal-time-display cursor-pointer" role="button" tabindex="0" aria-label="ゴール時刻を編集">-</span>
|
||||
<input type="datetime-local" id="goalTimeInput" class="goal-time-input hidden border rounded px-2 py-1" aria-label="ゴール時刻入力">
|
||||
</div>
|
||||
</div>
|
||||
<!-- ゴール判定 -->
|
||||
<div class="bg-gray-50 p-4 rounded-lg">
|
||||
<div class="text-sm text-gray-500">判定</div>
|
||||
<div id="validate" class="font-semibold text-blue-600" aria-live="polite">-</div>
|
||||
</div>
|
||||
<!-- 得点サマリー -->
|
||||
<div class="bg-gray-50 p-4 rounded-lg">
|
||||
<div class="text-sm text-gray-500">総合得点</div>
|
||||
<div id="totalScore" class="font-semibold text-blue-600" aria-live="polite">-</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- チェックインデータテーブル -->
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full divide-y divide-gray-200" role="grid">
|
||||
<thead class="bg-gray-50">
|
||||
<tr>
|
||||
<th class="w-8" scope="col"></th>
|
||||
<th class="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">走行順</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">規定写真</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">撮影写真</th>
|
||||
<th class="px-5 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">CP名称</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">通過時刻</th>
|
||||
<th class="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">通過審査</th>
|
||||
<th class="px-2 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">買物</th>
|
||||
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase" scope="col">獲得点数</th>
|
||||
<th class="w-8" scope="col"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="checkinList" class="bg-white divide-y divide-gray-200">
|
||||
<!-- JavaScript で動的に生成 -->
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- アクションボタン -->
|
||||
<div class="mt-6 flex justify-end space-x-4">
|
||||
<button id="addCpButton" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2" aria-label="新規CP追加">
|
||||
新規CP追加
|
||||
</button>
|
||||
<button id="saveButton" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2" aria-label="変更を保存">
|
||||
保存
|
||||
</button>
|
||||
<button id="exportButton" class="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2" aria-label="通過証明書を出力">
|
||||
通過証明書出力
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script src="js/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
72
supervisor/html/js/ApiClient.js
Normal file
72
supervisor/html/js/ApiClient.js
Normal file
@ -0,0 +1,72 @@
|
||||
// js/ApiClient.js
|
||||
export class ApiClient {
|
||||
constructor({ baseUrl, authToken, csrfToken }) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.authToken = authToken;
|
||||
this.csrfToken = csrfToken;
|
||||
}
|
||||
|
||||
async request(endpoint, options = {}) {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Token ${this.authToken}`,
|
||||
'X-CSRF-Token': this.csrfToken
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...headers,
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
console.error('API request failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// イベント関連のAPI
|
||||
async getEvents() {
|
||||
return this.request('/new-events/');
|
||||
}
|
||||
|
||||
async getZekkenNumbers(eventCode) {
|
||||
return this.request(`/zekken_numbers/${eventCode}`);
|
||||
}
|
||||
|
||||
// チーム関連のAPI
|
||||
async getTeamInfo(zekkenNumber) {
|
||||
return this.request(`/team_info/${zekkenNumber}/`);
|
||||
}
|
||||
|
||||
async getCheckins(zekkenNumber, eventCode) {
|
||||
return this.request(`/checkins/${zekkenNumber}/${eventCode}/`);
|
||||
}
|
||||
|
||||
async updateCheckin(checkinId, data) {
|
||||
return this.request(`/checkins/${checkinId}`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
}
|
||||
|
||||
async deleteCheckin(checkinId) {
|
||||
return this.request(`/checkins/${checkinId}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
}
|
||||
}
|
||||
276
supervisor/html/js/SupervisorPanel.js
Normal file
276
supervisor/html/js/SupervisorPanel.js
Normal file
@ -0,0 +1,276 @@
|
||||
// js/SupervisorPanel.js
|
||||
import { CheckinList } from './components/CheckinList.js';
|
||||
import { TeamSummary } from './components/TeamSummary.js';
|
||||
import { PointsCalculator } from './utils/PointsCalculator.js';
|
||||
import { DateFormatter } from './utils/DateFormatter.js';
|
||||
import { NotificationService } from './services/NotificationService.js';
|
||||
|
||||
export class SupervisorPanel {
|
||||
constructor({ element, template, apiClient, eventBus }) {
|
||||
this.element = element;
|
||||
this.template = template;
|
||||
this.apiClient = apiClient;
|
||||
this.eventBus = eventBus;
|
||||
this.notification = new NotificationService();
|
||||
this.pointsCalculator = new PointsCalculator();
|
||||
|
||||
this.state = {
|
||||
currentEvent: null,
|
||||
currentZekken: null,
|
||||
teamData: null,
|
||||
checkins: []
|
||||
};
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
this.render();
|
||||
this.initializeComponents();
|
||||
this.bindEvents();
|
||||
await this.loadInitialData();
|
||||
}
|
||||
|
||||
render() {
|
||||
this.element.innerHTML = this.template.innerHTML;
|
||||
|
||||
// コンポーネントの初期化
|
||||
this.checkinList = new CheckinList({
|
||||
element: document.getElementById('checkinList'),
|
||||
onUpdate: this.handleCheckinUpdate.bind(this)
|
||||
});
|
||||
|
||||
this.teamSummary = new TeamSummary({
|
||||
element: document.getElementById('team-summary'),
|
||||
onGoalTimeUpdate: this.handleGoalTimeUpdate.bind(this)
|
||||
});
|
||||
}
|
||||
|
||||
initializeComponents() {
|
||||
// Sortable.jsの初期化
|
||||
new Sortable(document.getElementById('checkinList'), {
|
||||
animation: 150,
|
||||
onEnd: this.handlePathOrderChange.bind(this)
|
||||
});
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
// イベント選択
|
||||
document.getElementById('eventCode').addEventListener('change',
|
||||
this.handleEventChange.bind(this));
|
||||
|
||||
// ゼッケン番号選択
|
||||
document.getElementById('zekkenNumber').addEventListener('change',
|
||||
this.handleZekkenChange.bind(this));
|
||||
|
||||
// ボタンのイベントハンドラ
|
||||
document.getElementById('addCpButton').addEventListener('click',
|
||||
this.handleAddCP.bind(this));
|
||||
document.getElementById('saveButton').addEventListener('click',
|
||||
this.handleSave.bind(this));
|
||||
document.getElementById('exportButton').addEventListener('click',
|
||||
this.handleExport.bind(this));
|
||||
}
|
||||
|
||||
async loadInitialData() {
|
||||
try {
|
||||
const events = await this.apiClient.getEvents();
|
||||
this.populateEventSelect(events);
|
||||
} catch (error) {
|
||||
this.notification.showError('イベントの読み込みに失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handleEventChange(event) {
|
||||
const eventCode = event.target.value;
|
||||
if (!eventCode) return;
|
||||
|
||||
try {
|
||||
const zekkenNumbers = await this.apiClient.getZekkenNumbers(eventCode);
|
||||
this.populateZekkenSelect(zekkenNumbers);
|
||||
this.state.currentEvent = eventCode;
|
||||
} catch (error) {
|
||||
this.notification.showError('ゼッケン番号の読み込みに失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handleZekkenChange(event) {
|
||||
const zekkenNumber = event.target.value;
|
||||
if (!zekkenNumber || !this.state.currentEvent) return;
|
||||
|
||||
try {
|
||||
const [teamData, checkins] = await Promise.all([
|
||||
this.apiClient.getTeamInfo(zekkenNumber),
|
||||
this.apiClient.getCheckins(zekkenNumber, this.state.currentEvent)
|
||||
]);
|
||||
|
||||
this.state.currentZekken = zekkenNumber;
|
||||
this.state.teamData = teamData;
|
||||
this.state.checkins = checkins;
|
||||
|
||||
this.updateUI();
|
||||
} catch (error) {
|
||||
this.notification.showError('チームデータの読み込みに失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handleGoalTimeUpdate(newTime) {
|
||||
if (!this.state.teamData) return;
|
||||
|
||||
try {
|
||||
const response = await this.apiClient.updateTeamGoalTime(
|
||||
this.state.currentZekken,
|
||||
newTime
|
||||
);
|
||||
|
||||
this.state.teamData.end_datetime = newTime;
|
||||
this.validateGoalTime();
|
||||
this.teamSummary.update(this.state.teamData);
|
||||
} catch (error) {
|
||||
this.notification.showError('ゴール時刻の更新に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handleCheckinUpdate(checkinId, updates) {
|
||||
try {
|
||||
const response = await this.apiClient.updateCheckin(checkinId, updates);
|
||||
const index = this.state.checkins.findIndex(c => c.id === checkinId);
|
||||
if (index !== -1) {
|
||||
this.state.checkins[index] = { ...this.state.checkins[index], ...updates };
|
||||
this.calculatePoints();
|
||||
this.updateUI();
|
||||
}
|
||||
} catch (error) {
|
||||
this.notification.showError('チェックインの更新に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handlePathOrderChange(event) {
|
||||
const newOrder = Array.from(event.to.children).map((element, index) => ({
|
||||
id: element.dataset.id,
|
||||
path_order: index + 1
|
||||
}));
|
||||
|
||||
try {
|
||||
await this.apiClient.updatePathOrders(newOrder);
|
||||
this.state.checkins = this.state.checkins.map(checkin => {
|
||||
const orderUpdate = newOrder.find(update => update.id === checkin.id);
|
||||
return orderUpdate ? { ...checkin, path_order: orderUpdate.path_order } : checkin;
|
||||
});
|
||||
} catch (error) {
|
||||
this.notification.showError('走行順の更新に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handleAddCP() {
|
||||
try {
|
||||
const newCP = await this.showAddCPModal();
|
||||
if (!newCP) return;
|
||||
|
||||
const response = await this.apiClient.addCheckin(
|
||||
this.state.currentZekken,
|
||||
newCP
|
||||
);
|
||||
|
||||
this.state.checkins.push(response);
|
||||
this.updateUI();
|
||||
} catch (error) {
|
||||
this.notification.showError('CPの追加に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
async handleSave() {
|
||||
try {
|
||||
await this.apiClient.saveAllChanges({
|
||||
zekkenNumber: this.state.currentZekken,
|
||||
checkins: this.state.checkins,
|
||||
teamData: this.state.teamData
|
||||
});
|
||||
|
||||
this.notification.showSuccess('保存が完了しました');
|
||||
} catch (error) {
|
||||
this.notification.showError('保存に失敗しました');
|
||||
}
|
||||
}
|
||||
|
||||
handleExport() {
|
||||
if (!this.state.currentZekken) {
|
||||
this.notification.showError('ゼッケン番号を選択してください');
|
||||
return;
|
||||
}
|
||||
|
||||
const exportUrl = `${this.apiClient.baseUrl}/export-excel/${this.state.currentZekken}`;
|
||||
window.open(exportUrl, '_blank');
|
||||
}
|
||||
|
||||
validateGoalTime() {
|
||||
if (!this.state.teamData || !this.state.teamData.end_datetime) return;
|
||||
|
||||
const endTime = new Date(this.state.teamData.end_datetime);
|
||||
const eventEndTime = new Date(this.state.teamData.event_end_time);
|
||||
const timeDiff = (endTime - eventEndTime) / (1000 * 60);
|
||||
|
||||
this.state.teamData.validation = {
|
||||
status: timeDiff <= 15 ? '合格' : '失格',
|
||||
latePoints: timeDiff > 15 ? Math.floor(timeDiff - 15) * -50 : 0
|
||||
};
|
||||
}
|
||||
|
||||
calculatePoints() {
|
||||
const points = this.pointsCalculator.calculate({
|
||||
checkins: this.state.checkins,
|
||||
latePoints: this.state.teamData?.validation?.latePoints || 0
|
||||
});
|
||||
|
||||
this.state.points = points;
|
||||
}
|
||||
|
||||
updateUI() {
|
||||
// チーム情報の更新
|
||||
this.teamSummary.update(this.state.teamData);
|
||||
|
||||
// チェックインリストの更新
|
||||
this.checkinList.update(this.state.checkins);
|
||||
|
||||
// ポイントの再計算と表示
|
||||
this.calculatePoints();
|
||||
this.updatePointsDisplay();
|
||||
}
|
||||
|
||||
updatePointsDisplay() {
|
||||
const { totalPoints, buyPoints, latePoints, finalPoints } = this.state.points;
|
||||
|
||||
document.getElementById('totalPoints').textContent = totalPoints;
|
||||
document.getElementById('buyPoints').textContent = buyPoints;
|
||||
document.getElementById('latePoints').textContent = latePoints;
|
||||
document.getElementById('finalPoints').textContent = finalPoints;
|
||||
}
|
||||
|
||||
populateEventSelect(events) {
|
||||
const select = document.getElementById('eventCode');
|
||||
select.innerHTML = '<option value="">イベントを選択</option>';
|
||||
|
||||
events.forEach(event => {
|
||||
const option = document.createElement('option');
|
||||
option.value = event.code;
|
||||
option.textContent = this.escapeHtml(event.name);
|
||||
select.appendChild(option);
|
||||
});
|
||||
}
|
||||
|
||||
populateZekkenSelect(numbers) {
|
||||
const select = document.getElementById('zekkenNumber');
|
||||
select.innerHTML = '<option value="">ゼッケン番号を選択</option>';
|
||||
|
||||
numbers.forEach(number => {
|
||||
const option = document.createElement('option');
|
||||
option.value = number;
|
||||
option.textContent = this.escapeHtml(number.toString());
|
||||
select.appendChild(option);
|
||||
});
|
||||
}
|
||||
|
||||
escapeHtml(str) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
}
|
||||
171
supervisor/html/js/main.js
Normal file
171
supervisor/html/js/main.js
Normal file
@ -0,0 +1,171 @@
|
||||
// js/main.js
|
||||
|
||||
// EventBus
|
||||
const EventBus = {
|
||||
listeners: {},
|
||||
|
||||
on(event, callback) {
|
||||
if (!this.listeners[event]) {
|
||||
this.listeners[event] = [];
|
||||
}
|
||||
this.listeners[event].push(callback);
|
||||
},
|
||||
|
||||
emit(event, data) {
|
||||
if (this.listeners[event]) {
|
||||
this.listeners[event].forEach(callback => callback(data));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// NotificationService
|
||||
class NotificationService {
|
||||
constructor() {
|
||||
this.toastElement = document.getElementById('toast');
|
||||
}
|
||||
|
||||
showMessage(message, type = 'info') {
|
||||
this.toastElement.textContent = message;
|
||||
this.toastElement.className = `fixed bottom-4 right-4 px-6 py-3 rounded shadow-lg ${
|
||||
type === 'error' ? 'bg-red-500' : 'bg-green-500'
|
||||
} text-white`;
|
||||
|
||||
this.toastElement.classList.remove('hidden');
|
||||
|
||||
setTimeout(() => {
|
||||
this.toastElement.classList.add('hidden');
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
showError(message) {
|
||||
this.showMessage(message, 'error');
|
||||
}
|
||||
|
||||
showSuccess(message) {
|
||||
this.showMessage(message, 'success');
|
||||
}
|
||||
}
|
||||
|
||||
// ApiClient
|
||||
class ApiClient {
|
||||
constructor({ baseUrl, authToken, csrfToken }) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.authToken = authToken;
|
||||
this.csrfToken = csrfToken;
|
||||
}
|
||||
|
||||
async request(endpoint, options = {}) {
|
||||
const url = `${this.baseUrl}${endpoint}`;
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Token ${this.authToken}`,
|
||||
'X-CSRF-Token': this.csrfToken
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers: {
|
||||
...headers,
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("content-type");
|
||||
if (contentType && contentType.includes("application/json")) {
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
return await response.text();
|
||||
} catch (error) {
|
||||
console.error('API request failed:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// API methods
|
||||
async getEvents() {
|
||||
return this.request('/new-events/');
|
||||
}
|
||||
|
||||
async getZekkenNumbers(eventCode) {
|
||||
return this.request(`/zekken_numbers/${eventCode}`);
|
||||
}
|
||||
|
||||
async getTeamInfo(zekkenNumber) {
|
||||
return this.request(`/team_info/${zekkenNumber}/`);
|
||||
}
|
||||
|
||||
// ... その他のAPI methods
|
||||
}
|
||||
|
||||
// PointsCalculator
|
||||
class PointsCalculator {
|
||||
calculate({ checkins, latePoints = 0 }) {
|
||||
const totalPoints = this.calculateTotalPoints(checkins);
|
||||
const buyPoints = this.calculateBuyPoints(checkins);
|
||||
|
||||
return {
|
||||
totalPoints,
|
||||
buyPoints,
|
||||
latePoints,
|
||||
finalPoints: totalPoints + buyPoints + latePoints
|
||||
};
|
||||
}
|
||||
|
||||
calculateTotalPoints(checkins) {
|
||||
return checkins.reduce((total, checkin) => {
|
||||
if (checkin.validate_location && !checkin.buy_flag) {
|
||||
return total + (checkin.checkin_point || 0);
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
calculateBuyPoints(checkins) {
|
||||
return checkins.reduce((total, checkin) => {
|
||||
if (checkin.validate_location && checkin.buy_flag) {
|
||||
return total + (checkin.buy_point || 0);
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// SupervisorPanel - メインアプリケーションクラス
|
||||
class SupervisorPanel {
|
||||
constructor(options) {
|
||||
this.element = options.element;
|
||||
this.apiClient = new ApiClient(options.apiConfig);
|
||||
this.notification = new NotificationService();
|
||||
this.pointsCalculator = new PointsCalculator();
|
||||
this.eventBus = EventBus;
|
||||
|
||||
this.state = {
|
||||
currentEvent: null,
|
||||
currentZekken: null,
|
||||
teamData: null,
|
||||
checkins: []
|
||||
};
|
||||
}
|
||||
|
||||
// ... SupervisorPanelの実装 ...
|
||||
}
|
||||
|
||||
// アプリケーションの初期化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const app = new SupervisorPanel({
|
||||
element: document.getElementById('app'),
|
||||
apiConfig: {
|
||||
baseUrl: '/api',
|
||||
authToken: localStorage.getItem('authToken'),
|
||||
csrfToken: document.querySelector('meta[name="csrf-token"]').content
|
||||
}
|
||||
});
|
||||
|
||||
app.initialize();
|
||||
});
|
||||
32
supervisor/html/js/utils/PointsCalculator.js
Normal file
32
supervisor/html/js/utils/PointsCalculator.js
Normal file
@ -0,0 +1,32 @@
|
||||
// js/utils/PointsCalculator.js
|
||||
export class PointsCalculator {
|
||||
calculate({ checkins, latePoints = 0 }) {
|
||||
const totalPoints = this.calculateTotalPoints(checkins);
|
||||
const buyPoints = this.calculateBuyPoints(checkins);
|
||||
|
||||
return {
|
||||
totalPoints,
|
||||
buyPoints,
|
||||
latePoints,
|
||||
finalPoints: totalPoints + buyPoints + latePoints
|
||||
};
|
||||
}
|
||||
|
||||
calculateTotalPoints(checkins) {
|
||||
return checkins.reduce((total, checkin) => {
|
||||
if (checkin.validate_location && !checkin.buy_flag) {
|
||||
return total + (checkin.checkin_point || 0);
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
}
|
||||
|
||||
calculateBuyPoints(checkins) {
|
||||
return checkins.reduce((total, checkin) => {
|
||||
if (checkin.validate_location && checkin.buy_flag) {
|
||||
return total + (checkin.buy_point || 0);
|
||||
}
|
||||
return total;
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
27
supervisor/html/js/vi
Normal file
27
supervisor/html/js/vi
Normal file
@ -0,0 +1,27 @@
|
||||
// js/services/NotificationService.js
|
||||
export class NotificationService {
|
||||
constructor() {
|
||||
this.toastElement = document.getElementById('toast');
|
||||
}
|
||||
|
||||
showMessage(message, type = 'info') {
|
||||
this.toastElement.textContent = message;
|
||||
this.toastElement.className = `fixed bottom-4 right-4 px-6 py-3 rounded shadow-lg ${
|
||||
type === 'error' ? 'bg-red-500' : 'bg-green-500'
|
||||
} text-white`;
|
||||
|
||||
this.toastElement.classList.remove('hidden');
|
||||
|
||||
setTimeout(() => {
|
||||
this.toastElement.classList.add('hidden');
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
showError(message) {
|
||||
this.showMessage(message, 'error');
|
||||
}
|
||||
|
||||
showSuccess(message) {
|
||||
this.showMessage(message, 'success');
|
||||
}
|
||||
}
|
||||
26
supervisor/html/login.html
Normal file
26
supervisor/html/login.html
Normal file
@ -0,0 +1,26 @@
|
||||
<!-- login.html -->
|
||||
<form id="loginForm" class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700">メールアドレス</label>
|
||||
<input type="email" id="email" required
|
||||
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700">パスワード</label>
|
||||
<input type="password" id="password" required
|
||||
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm">
|
||||
</div>
|
||||
<button type="submit"
|
||||
class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700">
|
||||
ログイン
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
document.getElementById('loginForm').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const email = document.getElementById('email').value;
|
||||
const password = document.getElementById('password').value;
|
||||
await login(email, password);
|
||||
});
|
||||
</script>
|
||||
Reference in New Issue
Block a user