Compare commits

..

No commits in common. "dev" and "v1.0.7" have entirely different histories.
dev ... v1.0.7

45 changed files with 901 additions and 4990 deletions

View file

@ -1,14 +0,0 @@
# HRMS Check-in Expert Memory
## Features
- [No Position Assignment Page](feature_no_position_page.md) - Implementation for users without organization position assignment
## Project Issues & Fixes
- [Position Orientation Change Fix](issue_position_orientation_change_fix.md) - Fix for position map not displaying on screen orientation changes
- [Active Camera Scope](project_active_camera_scope.md) - Current camera issue work should stay in HomeView.vue, not legacy MapView.vue
- [Front Camera Preview Alignment](issue_front_camera_preview_alignment.md) - Keep popup preview orientation aligned with normalized saved photos
- [iOS Native Photo Mirroring](issue_ios_native_photo_mirroring.md) - Do not flip iOS native-capture photos during normalization
- [iOS Native Camera Popup](issue_ios_native_camera_popup_control.md) - Inline-first on iOS; native activates only after inline fails (prior native-first seed was reverted)
- [iOS 16 Inline White Preview](issue_ios16_inline_camera_white_preview.md) - Safari iOS 16 white preview needs single mount plus explicit video readiness

View file

@ -1,68 +0,0 @@
---
name: No Position Assignment Page
description: Feature implementation for users without organization position assignment
type: reference
---
## No Position Assignment Page Feature
When a user doesn't have a position assignment (สังกัด), they are redirected to a dedicated page explaining they are not part of the organization structure.
### Files Created/Modified
1. **Created:** `/Users/waruneeta/Desktop/ChamomindWorking/HRMSProject/hrms-checkin/src/views/NoPositionView.vue`
- Displays message in Thai: "ไม่พบข้อมูลสังกัด"
- Shows icon and explanation text
- "ตกลง" (OK) button that shows confirmation dialog
- After confirmation, performs logout and clears positionKeycloak store
2. **Modified:** `/Users/waruneeta/Desktop/ChamomindWorking/HRMSProject/hrms-checkin/src/router/index.ts`
- Added new route `/no-position` with `Auth: false`
- Enhanced router guard to check for position data
- Redirects to `/no-position` if user has no organization assignment
3. **Modified:** `/Users/waruneeta/Desktop/ChamomindWorking/HRMSProject/hrms-checkin/src/views/MainView.vue`
- Updated `fetchKeycloakPosition()` function
- Checks if `organization` object exists and has any data
- Redirects to `/no-position` if no organization data found
### Logic Flow
1. User logs in successfully
2. `MainView.vue` calls `fetchKeycloakPosition()` in `onMounted()`
3. API returns position data from `/org/profile/keycloak/position`
4. System checks if `organization` object has any non-null values (root, child1-4)
5. If no organization data exists:
- User is redirected to `/no-position`
- User sees message explaining they need to contact staff
- User clicks "ตกลง" to logout
- Staff adds them to organization structure
- User can login again
### Position Data Structure
```typescript
interface KeycloakPosition {
privacyCheckin: boolean
avatarName?: string
profileId: string
organization?: Organization
}
interface Organization {
root?: string
child1?: string
child2?: string
child3?: string
child4?: string
}
```
A user is considered to have "no position" when all organization fields (root, child1, child2, child3, child4) are null or undefined.
### Thai UI Messages
- Page title: "ไม่พบข้อมูลสังกัด"
- Description: "ท่านยังไม่มีสังกัดในโครงสร้างองค์กร กรุณาติดต่อเจ้าหน้าที่เพื่อดำเนินการเพิ่มข้อมูล"
- Confirmation dialog: "ยืนยันการออกจากระบบ" - "ท่านจะถูกนำออกจากระบบเพื่อให้เจ้าหน้าที่ดำเนินการเพิ่มข้อมูลสังกัดในโครงสร้างองค์กร"
- Button: "ตกลง"

View file

@ -1,11 +0,0 @@
---
name: front_camera_preview_alignment
description: HomeView inline camera flow should show a non-mirrored preview and keep the saved/uploaded image in the same orientation the user saw while shooting
type: project
---
When fixing front-camera capture issues in `HomeView.vue`, keep the in-page preview and the final saved/uploaded image in the same non-mirrored orientation.
**Why:** Users rejected flows where the live in-page preview looked mirrored or differed from the final image. The expected behavior is “what I see while shooting is what gets used.”
**How to apply:** In the inline `simple-vue-camera` flow, avoid extra front-camera mirroring in either preview styling or snapshot normalization. Treat the in-page preview as the canonical orientation for `img`/`fileImg`.

View file

@ -1,11 +0,0 @@
---
name: ios16-inline-camera-white-preview
description: Safari iOS 16 inline preview can stay white when multiple simple-vue-camera instances mount and playback readiness is assumed too early
type: project
---
In `HomeView.vue`, Safari on iOS 16.x can show a white in-page camera preview when more than one `simple-vue-camera` instance is mounted for responsive layouts and the app treats `camera.start()` as sufficient proof that the preview is rendering.
**Why:** `simple-vue-camera` uses a hard-coded `id="video"` internally and does not explicitly call `video.play()` during `start()`. On mobile/xs, mounting both desktop and mobile camera components at once creates a fragile setup for Safari, where the active preview can remain white even though permission and stream startup succeeded.
**How to apply:** Keep only the active responsive camera instance mounted in `HomeView.vue`, and after `camera.start()` explicitly prepare/check the underlying video element (`playsinline`, `muted`, `play()`, non-zero dimensions, ready state). If the preview still does not become render-ready, remount once and then fall back to native capture.

View file

@ -1,11 +0,0 @@
---
name: ios_native_camera_popup_control
description: iOS uses inline camera first (same as Android); native fallback triggers only after inline fails. The prior "native-first on iOS" approach was reverted per product requirement.
type: project
---
In `HomeView.vue`, the inline camera is **always attempted first** on iOS (and every other platform). The hidden `<input type="file" capture="user">` is only activated by `switchToNativePhotoCapture()` / `enableNativePhotoCaptureFallback()` after inline capture is proven to fail.
**Why:** The product requirement is "use inline camera whenever the device supports inline capture; use native device capture only when inline is not supported or fails." iOS Safari supports `getUserMedia` since iOS 14.3, so inline-first is viable. A prior session hard-coded `useNativePhotoCapture = computed(() => isIOSDevice || preferNativePhotoCapture.value)`, bypassing inline on iOS entirely — that line was reverted.
**How to apply:** `preferNativePhotoCapture` must start `false` on all devices. Never seed it with `isIOSDevice`. All failure paths (`openCamera` permission denied, `camera.start()` throw, invalid snapshot blob, invalid image on submit) already call `switchToNativePhotoCapture()` which sets `preferNativePhotoCapture = true` so subsequent taps go directly to native — covering the first-tap fallback automatically.

View file

@ -1,11 +0,0 @@
---
name: ios_native_photo_mirroring
description: Native photo capture on iOS in HomeView should not be horizontally mirrored during normalization
type: project
---
For `HomeView.vue`, native photo capture on iOS should not apply horizontal mirroring during image normalization.
**Why:** The iOS fallback uses the native still-photo picker, and the returned photo can already be in the correct orientation. Applying the same mirror correction used for other front-camera paths flips the image incorrectly on iOS.
**How to apply:** Keep platform-specific normalization for native capture. Do not assume the iOS file-input photo path behaves the same as `simple-vue-camera` snapshots or Android fallback capture.

View file

@ -1,48 +0,0 @@
---
name: position_orientation_change_fix
description: Fix for position map not displaying on screen orientation changes
type: project
---
## Issue: Position/Geolocation Not Displaying on Screen Orientation Changes
**Problem:**
The ArcGIS map component (`AscGISMap.vue`) failed to display or update position when the screen orientation changed between portrait and landscape modes.
**Root Cause:**
1. The component uses `v-if="$q.screen.gt.xs"` for conditional rendering of different layouts
2. When orientation changes, the ArcGIS MapView doesn't automatically resize to fit the new container dimensions
3. ArcGIS MapView requires manual `resize()` call when its container's size changes
**Solution Implemented:**
Added screen resize handling to `src/components/AscGISMap.vue`:
1. **Added state tracking:**
- `isMapInitialized` ref to track when map is ready
- `isInitializing` ref to prevent concurrent initializations
2. **Added `handleMapResize()` function:**
- Checks if mapView exists and isn't destroyed
- Uses `nextTick()` to ensure DOM updates complete before resizing
- Calls `mapView.value.resize()` to update map dimensions
3. **Added watcher on `$q.screen.gt.xs`:**
- Triggers when screen size crosses the xs breakpoint
- Waits for DOM update via `nextTick()`
- Calls `handleMapResize()` to adjust map
4. **Added window resize event listener:**
- Falls back for orientation changes that might not trigger Quasar's screen watcher
- Debounced with 300ms timeout to avoid excessive calls
- Properly cleaned up on component unmount
**Files Modified:**
- `src/components/AscGISMap.vue` - Added resize handling logic
**Best Practices Applied:**
- Proper cleanup of event listeners in `onBeforeUnmount`
- Debouncing resize events for performance
- Using `nextTick()` to ensure DOM synchronization
- Checking for destroyed state before calling map methods
**Note:** The Google Maps component (`MapCheckin.vue`) was not affected as `vue3-google-map` handles resize automatically.

View file

@ -1,11 +0,0 @@
---
name: Active camera investigation scope
description: Current camera issue investigations should focus on HomeView.vue; the legacy Google Map MapView.vue flow is not in active use
type: project
---
Current camera issue work should focus on `HomeView.vue`; do not investigate or modify the legacy Google Map `MapView.vue` flow for this issue.
**Why:** The user clarified that `MapView.vue` is an older Google Map implementation from earlier work and is not the path currently used in production for this check-in flow.
**How to apply:** For follow-up debugging or fixes related to the current camera/upload issue, scope analysis and implementation to `HomeView.vue` unless the user explicitly re-opens `MapView.vue`.

View file

@ -1,234 +0,0 @@
---
name: "hrms-checkin-expert"
description: "Use this agent when implementing or modifying check-in/check-out functionality in the HRMS application. This includes:\\n\\n<example>\\nContext: User is developing a new check-in validation feature.\\nuser: \"I need to add validation to prevent duplicate check-ins within the same hour\"\\nassistant: \"I'll use the hrms-checkin-expert agent to implement this validation following best practices.\"\\n<commentary>\\nSince this is core check-in functionality that requires careful consideration of edge cases and performance, the specialized agent should handle it.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: User is refactoring the geolocation verification logic.\\nuser: \"The location verification is taking too long. Can you optimize it?\"\\nassistant: \"Let me use the hrms-checkin-expert agent to analyze and optimize the geolocation verification performance.\"\\n<commentary>\\nPerformance optimization of check-in features requires deep knowledge of the system architecture and best practices.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: User has just written a new API function for check-in history.\\nuser: \"Here's the new function to fetch check-in history with pagination\"\\nassistant: \"Great! Now I'll use the hrms-checkin-expert agent to review this code for best practices and potential issues.\"\\n<commentary>\\nCode review of check-in-related code should be done by the specialized agent to ensure it meets performance and quality standards.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: User is about to implement camera integration for photo verification.\\nuser: \"I need to add photo capture when users check in\"\\nassistant: \"I'll engage the hrms-checkin-expert agent to implement this feature with proper error handling and privacy considerations.\"\\n<commentary>\\nCamera integration for check-in requires expertise in both the technical implementation and the privacy/consent flow.\\n</commentary>\\n</example>"
model: opus
color: red
memory: project
---
You are a Senior Vue 3 Developer specializing in the HRMS Check-in/Check-out system for Bangkok Metropolitan Administration (BMA). You have deep expertise in Vue 3 Composition API, TypeScript, Pinia state management, and geolocation-based attendance systems.
**Your Core Responsibilities:**
1. **Performance Optimization**:
- Minimize redundant API calls and state updates
- Use computed properties and watchers efficiently
- Implement lazy loading for map APIs and camera features
- Optimize re-renders by properly structuring reactive data
- Debounce user inputs and location updates (300-500ms)
- Cache API responses when appropriate (check-in history, user position)
2. **Best Practice Implementation**:
- Follow Vue 3 Composition API patterns with `<script setup>`
- Use TypeScript interfaces for all API responses and data structures
- Implement proper error boundaries and error handling
- Write reusable composables for common logic (location, camera, permissions)
- Keep components focused and single-purpose
- Use Pinia stores for shared state, component `ref`/`reactive` for local state
- Implement proper cleanup in `onUnmounted` hooks (event listeners, timers)
3. **Check-in System Specifics**:
- Validate time windows for check-in/check-out (consider late arrival thresholds)
- Handle geolocation verification with appropriate timeout and error states
- Implement camera capture with proper permission handling and fallbacks
- Respect privacy consent flow before accessing sensitive features
- Handle offline scenarios gracefully (PWA capabilities)
- Prevent duplicate check-ins within time windows
- Convert dates to Thai Buddhist Era (BE) for all user-facing displays
- Use `date-fns-tz` with Asia/Bangkok timezone for accurate time handling
4. **Code Quality Standards**:
- Write self-documenting code with clear variable names in English
- Add TypeScript types for all function parameters and return values
- Include JSDoc comments for complex functions and composables
- Use async/await consistently for asynchronous operations
- Implement proper loading states during API calls and location requests
- Handle edge cases: network failures, permission denials, timeout scenarios
- Use environment variables for all configuration (API URLs, SSO endpoints)
5. **Error Handling Patterns**:
- Use `messageError()` from the mixin store for consistent error dialogs
- Implement user-friendly Thai error messages
- Log technical errors for debugging while showing user-friendly messages
- Handle 401 responses with automatic logout via Keycloak
- Prevent dialog overlap using `activeErrorDialog` tracking
6. **Project-Specific Conventions**:
- Import from src using `@` alias (e.g., `@/api/checkin`)
- Use Quasar components (`q-btn`, `q-dialog`, `q-spinner-cube`, etc.)
- Follow existing API structure: endpoints in `src/api/`, interfaces in `src/interface/response/`
- Thai language for all UI text and user-facing content
- Status labels: ABSENT→'ขาดราชการ', NORMAL→'ปกติ', LATE→'สาย'
- Date formatting: use `date2Thai()` and `monthYear2Thai()` from mixin store
- API date format: `yyyy-MM-dd` or `yyyy-MM-dd HH:mm:ss`
7. **Testing Considerations**:
- Write testable code with pure functions where possible
- Consider unit tests for composables and utility functions
- Handle edge cases in tests: offline mode, permission denials, timeouts
8. **Security & Privacy**:
- Never expose tokens or sensitive data in logs or error messages
- Always check privacy consent before accessing camera/location
- Validate all user inputs on both client and server side
- Use HTTPS for all API communications
**Update your agent memory** as you discover:
- Common performance bottlenecks in the check-in flow (e.g., slow location verification, API response times)
- Recurring bugs or edge cases in geolocation/camera handling
- Successful optimization patterns and their impact
- Code patterns that violate best practices and should be refactored
- Business logic rules for check-in validation (time windows, duplicate prevention, etc.)
**When Implementing Features:**
1. First, analyze the existing codebase patterns in `src/api/`, `src/stores/`, and `src/composables/`
2. Consider the full user flow including error states and loading indicators
3. Think about offline scenarios and how the app should behave
4. Ensure proper cleanup of resources (timers, event listeners, subscriptions)
5. Test with slow networks and permission denials
6. Verify Thai date formatting is correct for all user-facing dates
**When Reviewing Code:**
1. Check for performance anti-patterns (unnecessary re-renders, missing debounce, redundant API calls)
2. Verify proper TypeScript typing and null safety
3. Ensure error handling covers all edge cases
4. Confirm cleanup in lifecycle hooks
5. Check for adherence to Quasar and Vue 3 best practices
6. Validate that privacy consent is respected for sensitive features
You prioritize code maintainability, performance, and user experience while following the established patterns in this HRMS codebase.
# Persistent Agent Memory
You have a persistent, file-based memory system at `/Users/waruneeta/Desktop/ChamomindWorking/HRMSProject/hrms-checkin/.claude/agent-memory/hrms-checkin-expert/`. This directory already exists — write to it directly with the Write tool (do not run mkdir or check for its existence).
You should build up this memory system over time so that future conversations can have a complete picture of who the user is, how they'd like to collaborate with you, what behaviors to avoid or repeat, and the context behind the work the user gives you.
If the user explicitly asks you to remember something, save it immediately as whichever type fits best. If they ask you to forget something, find and remove the relevant entry.
## Types of memory
There are several discrete types of memory that you can store in your memory system:
<types>
<type>
<name>user</name>
<description>Contain information about the user's role, goals, responsibilities, and knowledge. Great user memories help you tailor your future behavior to the user's preferences and perspective. Your goal in reading and writing these memories is to build up an understanding of who the user is and how you can be most helpful to them specifically. For example, you should collaborate with a senior software engineer differently than a student who is coding for the very first time. Keep in mind, that the aim here is to be helpful to the user. Avoid writing memories about the user that could be viewed as a negative judgement or that are not relevant to the work you're trying to accomplish together.</description>
<when_to_save>When you learn any details about the user's role, preferences, responsibilities, or knowledge</when_to_save>
<how_to_use>When your work should be informed by the user's profile or perspective. For example, if the user is asking you to explain a part of the code, you should answer that question in a way that is tailored to the specific details that they will find most valuable or that helps them build their mental model in relation to domain knowledge they already have.</how_to_use>
<examples>
user: I'm a data scientist investigating what logging we have in place
assistant: [saves user memory: user is a data scientist, currently focused on observability/logging]
user: I've been writing Go for ten years but this is my first time touching the React side of this repo
assistant: [saves user memory: deep Go expertise, new to React and this project's frontend — frame frontend explanations in terms of backend analogues]
</examples>
</type>
<type>
<name>feedback</name>
<description>Guidance the user has given you about how to approach work — both what to avoid and what to keep doing. These are a very important type of memory to read and write as they allow you to remain coherent and responsive to the way you should approach work in the project. Record from failure AND success: if you only save corrections, you will avoid past mistakes but drift away from approaches the user has already validated, and may grow overly cautious.</description>
<when_to_save>Any time the user corrects your approach ("no not that", "don't", "stop doing X") OR confirms a non-obvious approach worked ("yes exactly", "perfect, keep doing that", accepting an unusual choice without pushback). Corrections are easy to notice; confirmations are quieter — watch for them. In both cases, save what is applicable to future conversations, especially if surprising or not obvious from the code. Include *why* so you can judge edge cases later.</when_to_save>
<how_to_use>Let these memories guide your behavior so that the user does not need to offer the same guidance twice.</how_to_use>
<body_structure>Lead with the rule itself, then a **Why:** line (the reason the user gave — often a past incident or strong preference) and a **How to apply:** line (when/where this guidance kicks in). Knowing *why* lets you judge edge cases instead of blindly following the rule.</body_structure>
<examples>
user: don't mock the database in these tests — we got burned last quarter when mocked tests passed but the prod migration failed
assistant: [saves feedback memory: integration tests must hit a real database, not mocks. Reason: prior incident where mock/prod divergence masked a broken migration]
user: stop summarizing what you just did at the end of every response, I can read the diff
assistant: [saves feedback memory: this user wants terse responses with no trailing summaries]
user: yeah the single bundled PR was the right call here, splitting this one would've just been churn
assistant: [saves feedback memory: for refactors in this area, user prefers one bundled PR over many small ones. Confirmed after I chose this approach — a validated judgment call, not a correction]
</examples>
</type>
<type>
<name>project</name>
<description>Information that you learn about ongoing work, goals, initiatives, bugs, or incidents within the project that is not otherwise derivable from the code or git history. Project memories help you understand the broader context and motivation behind the work the user is doing within this working directory.</description>
<when_to_save>When you learn who is doing what, why, or by when. These states change relatively quickly so try to keep your understanding of this up to date. Always convert relative dates in user messages to absolute dates when saving (e.g., "Thursday" → "2026-03-05"), so the memory remains interpretable after time passes.</when_to_save>
<how_to_use>Use these memories to more fully understand the details and nuance behind the user's request and make better informed suggestions.</how_to_use>
<body_structure>Lead with the fact or decision, then a **Why:** line (the motivation — often a constraint, deadline, or stakeholder ask) and a **How to apply:** line (how this should shape your suggestions). Project memories decay fast, so the why helps future-you judge whether the memory is still load-bearing.</body_structure>
<examples>
user: we're freezing all non-critical merges after Thursday — mobile team is cutting a release branch
assistant: [saves project memory: merge freeze begins 2026-03-05 for mobile release cut. Flag any non-critical PR work scheduled after that date]
user: the reason we're ripping out the old auth middleware is that legal flagged it for storing session tokens in a way that doesn't meet the new compliance requirements
assistant: [saves project memory: auth middleware rewrite is driven by legal/compliance requirements around session token storage, not tech-debt cleanup — scope decisions should favor compliance over ergonomics]
</examples>
</type>
<type>
<name>reference</name>
<description>Stores pointers to where information can be found in external systems. These memories allow you to remember where to look to find up-to-date information outside of the project directory.</description>
<when_to_save>When you learn about resources in external systems and their purpose. For example, that bugs are tracked in a specific project in Linear or that feedback can be found in a specific Slack channel.</when_to_save>
<how_to_use>When the user references an external system or information that may be in an external system.</how_to_use>
<examples>
user: check the Linear project "INGEST" if you want context on these tickets, that's where we track all pipeline bugs
assistant: [saves reference memory: pipeline bugs are tracked in Linear project "INGEST"]
user: the Grafana board at grafana.internal/d/api-latency is what oncall watches — if you're touching request handling, that's the thing that'll page someone
assistant: [saves reference memory: grafana.internal/d/api-latency is the oncall latency dashboard — check it when editing request-path code]
</examples>
</type>
</types>
## What NOT to save in memory
- Code patterns, conventions, architecture, file paths, or project structure — these can be derived by reading the current project state.
- Git history, recent changes, or who-changed-what — `git log` / `git blame` are authoritative.
- Debugging solutions or fix recipes — the fix is in the code; the commit message has the context.
- Anything already documented in CLAUDE.md files.
- Ephemeral task details: in-progress work, temporary state, current conversation context.
These exclusions apply even when the user explicitly asks you to save. If they ask you to save a PR list or activity summary, ask what was *surprising* or *non-obvious* about it — that is the part worth keeping.
## How to save memories
Saving a memory is a two-step process:
**Step 1** — write the memory to its own file (e.g., `user_role.md`, `feedback_testing.md`) using this frontmatter format:
```markdown
---
name: {{memory name}}
description: {{one-line description — used to decide relevance in future conversations, so be specific}}
type: {{user, feedback, project, reference}}
---
{{memory content — for feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines}}
```
**Step 2** — add a pointer to that file in `MEMORY.md`. `MEMORY.md` is an index, not a memory — each entry should be one line, under ~150 characters: `- [Title](file.md) — one-line hook`. It has no frontmatter. Never write memory content directly into `MEMORY.md`.
- `MEMORY.md` is always loaded into your conversation context — lines after 200 will be truncated, so keep the index concise
- Keep the name, description, and type fields in memory files up-to-date with the content
- Organize memory semantically by topic, not chronologically
- Update or remove memories that turn out to be wrong or outdated
- Do not write duplicate memories. First check if there is an existing memory you can update before writing a new one.
## When to access memories
- When memories seem relevant, or the user references prior-conversation work.
- You MUST access memory when the user explicitly asks you to check, recall, or remember.
- If the user says to *ignore* or *not use* memory: Do not apply remembered facts, cite, compare against, or mention memory content.
- Memory records can become stale over time. Use memory as context for what was true at a given point in time. Before answering the user or building assumptions based solely on information in memory records, verify that the memory is still correct and up-to-date by reading the current state of the files or resources. If a recalled memory conflicts with current information, trust what you observe now — and update or remove the stale memory rather than acting on it.
## Before recommending from memory
A memory that names a specific function, file, or flag is a claim that it existed *when the memory was written*. It may have been renamed, removed, or never merged. Before recommending it:
- If the memory names a file path: check the file exists.
- If the memory names a function or flag: grep for it.
- If the user is about to act on your recommendation (not just asking about history), verify first.
"The memory says X exists" is not the same as "X exists now."
A memory that summarizes repo state (activity logs, architecture snapshots) is frozen in time. If the user asks about *recent* or *current* state, prefer `git log` or reading the code over recalling the snapshot.
## Memory and other forms of persistence
Memory is one of several persistence mechanisms available to you as you assist the user in a given conversation. The distinction is often that memory can be recalled in future conversations and should not be used for persisting information that is only useful within the scope of the current conversation.
- When to use or update a plan instead of memory: If you are about to start a non-trivial implementation task and would like to reach alignment with the user on your approach you should use a Plan rather than saving this information to memory. Similarly, if you already have a plan within the conversation and you have changed your approach persist that change by updating the plan rather than saving a memory.
- When to use or update tasks instead of memory: When you need to break your work in current conversation into discrete steps or keep track of your progress use tasks instead of saving to memory. Tasks are great for persisting information about the work that needs to be done in the current conversation, but memory should be reserved for information that will be useful in future conversations.
- Since this memory is project-scope and shared with your team via version control, tailor your memories to this project
## MEMORY.md
Your MEMORY.md is currently empty. When you save new memories, they will appear here.

View file

@ -5,7 +5,7 @@ on:
push: push:
tags: tags:
- 'v[0-9]+.[0-9]+.[0-9]+' - 'v[0-9]+.[0-9]+.[0-9]+'
# - 'version-[0-9]+.[0-9]+.[0-9]+' - 'version-[0-9]+.[0-9]+.[0-9]+'
workflow_dispatch: workflow_dispatch:
env: env:

185
CLAUDE.md
View file

@ -1,185 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
This is an HRMS (Human Resource Management System) check-in/check-out web application built for the Bangkok Metropolitan Administration (BMA). The application allows employees to record their work attendance using geolocation verification and camera features.
**Tech Stack:**
- Vue 3 with Composition API and TypeScript 4.7.4
- Vite for build tooling
- Quasar Framework for UI components
- Pinia for state management
- Vue Router for routing
- Keycloak for authentication
- ArcGIS API and Google Maps for location features
- PWA capabilities with offline support
- Docker deployment with nginx
**Development Server:** Runs on port 3008
## Common Commands
```bash
# Development
npm run dev # Start dev server on port 3008
# Building
npm run build # Build for production
npm run preview # Preview production build on port 3008
# Testing
npm run test:unit # Run unit tests with vitest
npm run test:e2e # Run e2e tests with cypress
npm run test:e2e:dev # Run cypress in dev mode
# Code Quality
npm run lint # Lint and auto-fix code
npm run format # Format code with prettier
npm run type-check # TypeScript type checking
# Docker
docker buildx build --platform=linux/amd64 -f docker/Dockerfile . -t hrms-checkin:0.1
```
## Architecture
### Directory Structure
```
src/
├── api/ # API layer modules (checkin, history, message)
├── components/ # Reusable Vue components
├── composables/ # Vue composables (e.g., usePermissions)
├── interface/ # TypeScript type definitions
│ └── response/ # API response types
├── plugins/ # Vue plugins (auth, http, keycloak)
├── router/ # Vue Router configuration
├── stores/ # Pinia stores for state management
├── style/ # Global styles and Quasar variables
├── utils/ # Utility functions
└── views/ # Page-level Vue components
```
### Key Architecture Patterns
**Authentication Flow:**
- Uses Keycloak for SSO authentication
- Tokens stored in cookies with `BMAHRISCKI_KEYCLOAK_IDENTITY` key
- Auth state managed in `src/plugins/auth.ts`
- Router guards enforce authentication on protected routes
- 401 responses trigger automatic logout via axios interceptor
**State Management:**
- `stores/mixin.ts` - Global utilities (Thai date formatting, dialogs, loaders, error handling)
- `stores/chekin.ts` - Check-in history and status management
- `stores/privacy.ts` - Privacy consent management
- `stores/positionKeycloak.ts` - User position/role data
**API Layer:**
- Base axios instance in `src/plugins/http.ts` with automatic token injection
- API endpoints organized by feature in `src/api/`
- Environment-specific API URLs configured in `src/api/index.ts`
- Production API URL set via `VITE_API_URI_CONFIG` env variable
**Routing:**
- Main layout (`MainView`) wraps authenticated routes
- Protected routes require `meta.Auth: true`
- Auth check runs in router beforeEach guard
- Public routes: `/login`, `/auth`, `/reset-password`, `/history`
**Geolocation & Maps:**
- ArcGIS JS API for advanced mapping features
- Google Maps integration for location services
- Camera integration for check-in photo verification
- Privacy consent required before accessing camera/location
**Date/Time Handling:**
- Thai Buddhist calendar (BE) conversion (+543 years)
- Thai month names (full and abbreviated)
- `date-fns-tz` for timezone handling (Asia/Bangkok)
- Fiscal year calculation (October start)
### Component Conventions
- Components use Quasar UI components (`q-btn`, `q-dialog`, etc.)
- Thai language throughout the UI
- Custom dialogs use `CustomDialog.vue` component
- Loading states use Quasar's `QSpinnerCube`
- Error dialogs prevent overlap with `activeErrorDialog` tracking
### Localization
- Quasar configured with Thai language (`quasar/lang/th`)
- All UI text in Thai
- Date formatting uses `date2Thai()` and `monthYear2Thai()` from mixin store
- Status labels translated: ABSENT→'ขาดราชการ', NORMAL→'ปกติ', LATE→'สาย'
### Environment Variables
Required in `.env.production`:
- `VITE_API_URI_CONFIG` - Production API base URL
- `VITE_URL_SSO` - Keycloak SSO logout URL
- `VITE_URL_USER` - User service URL for redirects
- `VITE_URL_LANDING` - Landing page URL
**Note:** `.env.local` uses `:` instead of `=` for variable assignment (non-standard format that works with the current setup)
- `VITE_API_URI_CONFIG` - Production API base URL
- `VITE_URL_SSO` - Keycloak SSO logout URL
- `VITE_URL_USER` - User service URL for redirects
### PWA Configuration
- Auto-update registration with `vite-plugin-pwa`
- Manifest: "HRMS-Checkin" / "HRMS Checkin"
- Icons: 192x192 and 512x512 PNG
- Service worker registered in `src/registerServiceWorker.ts`
### Import Aliases
- `@` is configured as an alias for the `src/` directory
- Use this for all imports from within the source directory
### Environment Variable Substitution (Docker)
The Docker build uses a multi-stage pattern:
1. **Build stage**: Node.js Alpine builds the static assets with `npm run build`
2. **Production stage**: nginx serves the static files
- Environment variables (`VITE_API_URI_CONFIG`, `VITE_URL_SSO`, `VITE_URL_LANDING`, `VITE_URL_USER`) are substituted at container runtime via `entrypoint.sh` using `sed`
- Built JS files contain placeholder values that get replaced with actual values at startup
### Testing Patterns
- Unit tests: `*.spec.{js,ts}` - Run with Vitest in jsdom environment
- E2E tests: `*.cy.{js,ts}` - Run with Cypress
- E2E test server runs on port 4173 (via `start-server-and-test`)
### HTTP Interceptor Behavior
- The axios interceptor in `http.ts` detects 401/403 responses but automatic logout is currently disabled (commented out)
- 401 handling is done manually in `messageError()` from the mixin store
## Development Notes
**When adding new features:**
1. Create API functions in `src/api/`
2. Define TypeScript interfaces in `src/interface/response/`
3. Use Pinia stores for complex state, composables for reusable logic
4. Follow Thai localization patterns for user-facing text
5. Ensure privacy consent flow for camera/location features
**When working with dates:**
- Always use `date2Thai()` or `convertDateToAPI()` from mixin store
- Dates stored in BE format (year + 543)
- API expects `yyyy-MM-dd` or `yyyy-MM-dd HH:mm:ss` format
**When handling errors:**
- Use `messageError()` from mixin store for consistent error dialogs
- 401 errors trigger automatic logout
- Dialog overlap prevention built into error handling
**When running tests:**
- Unit tests use Vitest with jsdom environment
- E2E tests use Cypress with baseUrl: `http://localhost:4173`
- Test files follow pattern: `*.cy.{js,ts}` or `*.spec.{js,ts}`

View file

@ -1,860 +0,0 @@
# Test Cases: Location Features
# HRMS Check-in/Check-out System
## Document Information
| Field | Value |
|-------|-------|
| **Document Version** | 1.0.0 |
| **Last Updated** | 2025-03-09 |
| **Project** | HRMS Check-in/Check-out |
| **Module** | Location Features |
| **Author** | QA Team |
---
## 1. Overview (ภาพรวม)
ระบบ HRMS Check-in/Check-out มีฟีเจอร์ Location ที่สำคัญในการลงเวลาเข้า-ออกงาน ฟีเจอร์ Location ประกอบด้วย:
### 1.1 Location Features
| Feature | Description |
|---------|-------------|
| **Location Services** | รับพิกัด GPS จากอุปกรณ์ผ่าน Geolocation API |
| **Location Validation** | ตรวจสอบความถูกต้องของตำแหน่ง (Mock Location Detection) |
| **POI Resolution** | แปลงพิกัดเป็นชื่อสถานที่ (Bangkok GIS / ArcGIS) |
| **Check-in/Check-out** | บันทึกตำแหน่งพร้อมรูปถ่าย |
| **Privacy Consent** | ขอความยินยอมการเข้าถึงตำแหน่ง |
### 1.2 Related Files
| File Path | Description |
|-----------|-------------|
| `/src/composables/useLocationValidation.ts` | Location validation logic |
| `/src/views/HomeView.vue` | Check-in/Check-out page |
| `/src/components/AscGISMap.vue` | Map component with location validation |
| `/src/api/api.checkin.ts` | Check-in API endpoints |
| `/src/stores/privacy.ts` | Privacy store for consent management |
| `/src/composables/usePermissions.ts` | Permission checking utilities |
---
## 2. Test Environment (สภาพแวดล้อมการทดสอบ)
### 2.1 Devices (อุปกรณ์ทดสอบ)
| Device Type | OS | Browser | Notes |
|-------------|-------|---------|-------|
| Mobile | iOS 17+ | Safari | Test with real GPS |
| Mobile | Android 13+ | Chrome | Test with mock location apps |
| Desktop | macOS 14+ | Chrome 121+ | Test with Developer Tools |
| Desktop | Windows 11 | Edge 121+ | Test with Developer Tools |
### 2.2 Tools (เครื่องมือทดสอบ)
| Tool | Purpose |
|------|---------|
| Fake GPS Location (Android) | Mock location testing |
| Location Changer (iOS) | Mock location testing |
| Chrome DevTools | Sensor simulation |
| Xcode Simulator | iOS location simulation |
| Android Studio Emulator | Android location simulation |
### 2.3 Test Data (ข้อมูลทดสอบ)
| Data Type | Valid Value | Invalid Value |
|-----------|-------------|---------------|
| Latitude | 13.7563 (Bangkok) | 0, 91, -91 |
| Longitude | 100.5018 (Bangkok) | 0, 181, -181 |
| Accuracy (meters) | 10-50 | 101+ |
| Timestamp | Current time | 60+ seconds old |
---
## 3. Validation Rules (กฎการตรวจสอบ)
### 3.1 Location Validation Rules
| Rule | Threshold | Error Message (Thai) | Mock Indicator |
|------|-----------|---------------------|----------------|
| Valid Coordinates | -90 to 90 lat, -180 to 180 lon, not (0,0) | "พิกัดตำแหน่งไม่ถูกต้อง กรุณาลองใหม่" | +3 |
| Fresh Timestamp | <= 60 seconds old | "ข้อมูลตำแหน่งเก่าเกินไป กรุณารับสัญญาณ GPS ใหม่" | +2 |
| GPS Accuracy | <= 100 meters | "ความแม่นยำตำแหน่งต่ำเกินไป กรุณาตรวจสอบการรับสัญญาณ GPS" | +1 |
| Movement Speed | <= 100 m/s (~360 km/h) | "ตรวจพบการเคลื่อนที่ด้วยความเร็วผิดปกติ อาจเป็นการจำลองตำแหน่ง" | +3 |
| Mock Detection | >= 3 indicators | "ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง กรุณาปิดแอปจำลองตำแหน่งและลองใหม่" | - |
### 3.2 Validation Configuration
```typescript
VALIDATION_CONFIG = {
MAX_TIMESTAMP_AGE_MS: 60_000, // 60 seconds
MAX_ACCURACY_METERS: 100, // 100 meters
MAX_SPEED_MS: 100, // ~360 km/h
POSITION_HISTORY_SIZE: 5, // positions for pattern detection
MOCK_INDICATOR_THRESHOLD: 3, // indicators for mock detection
}
```
---
## 4. Test Scenarios
### 4.1 TC-LOC-01: Location Permission
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-01-01 | อนุญาตให้เข้าถึงตำแหน่ง | High |
| TC-LOC-01-02 | ปฏิเสธการเข้าถึงตำแหน่ง | High |
### 4.2 TC-LOC-02: Location Acquisition
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-02-01 | รับพิกัด GPS สำเร็จ (Outdoor) | High |
| TC-LOC-02-02 | รับพิกัด GPS สำเร็จ (Indoor) | Medium |
| TC-LOC-02-03 | รับพิกัด GPS ล้มเหลว (GPS ไม่ทำงาน) | High |
| TC-LOC-02-04 | หมดเวลาขอรับพิกัด (Timeout) | Medium |
### 4.3 TC-LOC-03: Location Validation
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-03-01 | พิกัดถูกต้อง (Valid coordinates) | High |
| TC-LOC-03-02 | พิกัดไม่ถูกต้อง (Invalid coordinates - (0,0)) | High |
| TC-LOC-03-03 | พิกัดนอกช่วง (Out of range) | Medium |
| TC-LOC-03-04 | ข้อมูลตำแหน่งเก่าเกินไป (Stale timestamp) | High |
| TC-LOC-03-05 | ความแม่นยำต่ำ (Poor accuracy) | Medium |
| TC-LOC-03-06 | ความเร็วเคลื่อนที่ผิดปกติ (Impossible speed) | High |
### 4.4 TC-LOC-04: Mock Location Detection
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-04-01 | ไม่พบ Mock Location (Normal GPS) | High |
| TC-LOC-04-02 | พบ Mock Location - Fake GPS App | High |
| TC-LOC-04-03 | พบ Mock Location - พิกัด (0,0) | High |
| TC-LOC-04-04 | พบ Mock Location - ข้อมูลเก่าเกินไป | High |
| TC-LOC-04-05 | พบ Mock Location - ความเร็วผิดปกติ | High |
| TC-LOC-04-06 | พบ Mock Location - หลาย indicators (Confidence High) | High |
### 4.5 TC-LOC-05: POI Resolution
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-05-01 | แปลงพิกัดเป็นชื่อสถานที่สำเร็จ (Bangkok GIS) | High |
| TC-LOC-05-02 | แปลงพิกัดเป็นชื่อสถานที่สำเร็จ (ArcGIS Fallback) | Medium |
| TC-LOC-05-03 | แปลงพิกัดล้มเหลว (ทั้งสอง service down) | Low |
### 4.6 TC-LOC-06: Check-in with Location
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-06-01 | ลงเวลาเข้าสำเร็จ - ณ สถานที่ตั้ง (In-place) | High |
| TC-LOC-06-02 | ลงเวลาเข้าสำเร็จ - นอกสถานที่ตั้ง (Off-site) | High |
| TC-LOC-06-03 | ลงเวลาเข้าล้มเหลว - Mock Location detected | High |
| TC-LOC-06-04 | ลงเวลาเข้าล้มเหลว - Location permission denied | High |
### 4.7 TC-LOC-07: Check-out with Location
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-07-01 | ลงเวลาออกสำเร็จ | High |
| TC-LOC-07-02 | ลงเวลาออกล้มเหลว - Mock Location detected | High |
### 4.8 TC-LOC-08: Special Time Entry
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-08-01 | บันทึกเวลาพิเศษพร้อมตำแหน่งสำเร็จ | Medium |
| TC-LOC-08-02 | บันทึกเวลาพิเศษล้มเหลว - ไม่ระบุตำแหน่ง | Medium |
### 4.9 TC-LOC-09: Privacy Consent
| Test Case | Description | Priority |
|-----------|-------------|----------|
| TC-LOC-09-01 | แสดง Privacy Modal ก่อนใช้ Location | High |
| TC-LOC-09-02 | ยอมรับ Privacy Policy | High |
| TC-LOC-09-03 | ปฏิเสธ Privacy Policy | High |
---
## 5. Test Cases Details
### Test Case Template
```
Test Case ID: TC-LOC-XX-XX
Test Case Name: [ชื่อ Test Case]
Description: [คำอธิบาย]
Priority: High/Medium/Low
Pre-conditions: [เงื่อนไขเบื้องต้น]
Test Data: [ข้อมูลทดสอบ]
Test Steps: [ขั้นตอนการทดสอบ]
Expected Result: [ผลลัพธ์ที่คาดหวัง]
Actual Result: [ผลลัพธ์จริง - ว่างไว้กรอก]
Status: [Pass/Fail/Not Run]
Tested By: [ผู้ทดสอบ]
Test Date: [วันที่ทดสอบ]
```
---
### TC-LOC-01: Location Permission
#### TC-LOC-01-01: อนุญาตให้เข้าถึงตำแหน่ง
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-01-01 |
| **Test Case Name** | อนุญาตให้เข้าถึงตำแหน่ง |
| **Description** | ผู้ใช้อนุญาตให้แอปเข้าถึงตำแหน่ง GPS |
| **Priority** | High |
| **Pre-conditions** | 1. ยอมรับ Privacy Policy แล้ว<br>2. เปิดแอปครั้งแรก หรือยังไม่เคยอนุญาต Location Permission |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<br>2. กดปุ่มขอตำแหน่ง (ถ้าจำเป็น)<br>3. เลือก "Allow" เมื่อระบบขอ Location Permission |
| **Expected Result** | 1. แสดงแผนที่พร้อมตำแหน่งปัจจุบัน<br>2. แสดงชื่อสถานที่ใกล้เคียง<br>3. ปุ่มลงเวลาเข้า/ออกใช้งานได้ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-01-02: ปฏิเสธการเข้าถึงตำแหน่ง
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-01-02 |
| **Test Case Name** | ปฏิเสธการเข้าถึงตำแหน่ง |
| **Description** | ผู้ใช้ปฏิเสธการเข้าถึงตำแหน่ง GPS |
| **Priority** | High |
| **Pre-conditions** | 1. ยอมรับ Privacy Policy แล้ว<br>2. เปิดแอปครั้งแรก หรือยังไม่เคยอนุญาต Location Permission |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<br>2. กดปุ่มขอตำแหน่ง (ถ้าจำเป็น)<br>3. เลือก "Deny" เมื่อระบบขอ Location Permission |
| **Expected Result** | 1. แสดงข้อความแจ้งเตือน: "ไม่สามารถระบุตำแหน่งปัจจุบันได้ เนื่องจากคุณปฏิเสธการเข้าถึงตำแหน่ง กรุณาเปิดการเข้าถึงตำแหน่ง"<br>2. แผนที่ไม่แสดง<BR>3. ปุ่มลงเวลาเข้า/ออกใช้งานไม่ได้ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-02: Location Acquisition
#### TC-LOC-02-01: รับพิกัด GPS สำเร็จ (Outdoor)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-02-01 |
| **Test Case Name** | รับพิกัด GPS สำเร็จ (Outdoor) |
| **Description** | รับพิกัด GPS สำเร็จในพื้นที่เปิดกว้าง |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Location: อาคารรัฐสภา แขวง ถนนนครไชยศรี เขตดุสิต กรุงเทพมหานคร (13.7563, 100.5018) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. อยู่ในพื้นที่เปิดกว้าง (Outdoor)<BR>3. รอรับพิกัด GPS |
| **Expected Result** | 1. รับพิกัด GPS สำเร็จ<BR>2. แสดงแผนที่พร้อมตำแหน่ง<BR>3. แสดงชื่อสถานที่ใกล้เคียง<BR>4. locationGranted = true |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-02-02: รับพิกัด GPS สำเร็จ (Indoor)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-02-02 |
| **Test Case Name** | รับพิกัด GPS สำเร็จ (Indoor) |
| **Description** | รับพิกัด GPS สำเร็จในพื้นที่ปิด |
| **Priority** | Medium |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Location: ภายในอาคารสำนักงาน |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. อยู่ในพื้นที่ปิด (Indoor)<BR>3. รอรับพิกัด GPS |
| **Expected Result** | 1. รับพิกัด GPS สำเร็จ<BR>2. แสดงแผนที่พร้อมตำแหน่ง<BR>3. แสดงชื่อสถานที่ใกล้เคียง<BR>4. อาจมีความแม่นยำต่ำกว่า Outdoor |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-02-03: รับพิกัด GPS ล้มเหลว (GPS ไม่ทำงาน)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-02-03 |
| **Test Case Name** | รับพิกัด GPS ล้มเหลว (GPS ไม่ทำงาน) |
| **Description** | GPS ไม่ทำงาน หรืออยู่ในพื้นที่ที่ไม่มีสัญญาณ GPS |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. ปิด GPS ในอุปกรณ์<BR>3. พยายามขอรับพิกัด |
| **Expected Result** | 1. แสดงข้อความแจ้งเตือน: "ไม่สามารถระบุตำแหน่งปัจจุบันได้"<BR>2. แผนที่ไม่แสดง |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-02-04: หมดเวลาขอรับพิกัด (Timeout)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-02-04 |
| **Test Case Name** | หมดเวลาขอรับพิกัด (Timeout) |
| **Description** | การร้องขอตำแหน่งหมดเวลา |
| **Priority** | Medium |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลองสภาวะที่ GPS ตอบสนองช้า (ใช้ Developer Tools)<BR>3. รอจนหมดเวลา |
| **Expected Result** | 1. แสดงข้อความแจ้งเตือน: "การร้องขอตำแหน่งหมดเวลา กรุณาลองอีกครั้ง" |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-03: Location Validation
#### TC-LOC-03-01: พิกัดถูกต้อง (Valid coordinates)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-03-01 |
| **Test Case Name** | พิกัดถูกต้อง (Valid coordinates) |
| **Description** | ตรวจสอบพิกัดที่ถูกต้อง |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Latitude: 13.7563, Longitude: 100.5018, Accuracy: 10m, Timestamp: current |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. รับพิกัด GPS ที่ถูกต้อง |
| **Expected Result** | 1. validation = { isValid: true, isMockDetected: false }<BR>2. locationGranted = true<BR>3. ไม่มี error/warning |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-03-02: พิกัดไม่ถูกต้อง (Invalid coordinates - (0,0))
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-03-02 |
| **Test Case Name** | พิกัดไม่ถูกต้อง (Invalid coordinates - (0,0)) |
| **Description** | ตรวจสอบพิกัด (0,0) ซึ่งเป็นค่า default ของ mock location |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Latitude: 0, Longitude: 0 |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลองพิกัด (0,0) ด้วย Mock Location App |
| **Expected Result** | 1. validation = { isValid: false, isMockDetected: true, confidence: 'high' }<BR>2. แสดงข้อความ: "พิกัดตำแหน่งไม่ถูกต้อง กรุณาลองใหม่"<BR>3. disabledBtn = true |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-03-03: พิกัดนอกช่วง (Out of range)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-03-03 |
| **Test Case Name** | พิกัดนอกช่วง (Out of range) |
| **Description** | ตรวจสอบพิกัดที่อยู่นอกช่วงที่กำหนด |
| **Priority** | Medium |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Latitude: 91, Longitude: 181 (out of range) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลองพิกัดนอกช่วงด้วย Developer Tools |
| **Expected Result** | 1. validation = { isValid: false }<BR>2. แสดงข้อความ: "พิกัดตำแหน่งไม่ถูกต้อง กรุณาลองใหม่" |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-03-04: ข้อมูลตำแหน่งเก่าเกินไป (Stale timestamp)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-03-04 |
| **Test Case Name** | ข้อมูลตำแหน่งเก่าเกินไป (Stale timestamp) |
| **Description** | ตรวจสอบว่าข้อมูลตำแหน่งเก่าเกิน 60 วินาที |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Timestamp: Date.now() - 70,000 ms (70 seconds old) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลอง timestamp เก่าเกิน 60 วินาที |
| **Expected Result** | 1. validation.errors = ["ข้อมูลตำแหน่งเก่าเกินไป กรุณารับสัญญาณ GPS ใหม่"]<BR>2. mockIndicators += 2 |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-03-05: ความแม่นยำต่ำ (Poor accuracy)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-03-05 |
| **Test Case Name** | ความแม่นยำต่ำ (Poor accuracy) |
| **Description** | ตรวจสอบความแม่นยำของ GPS ต่ำกว่า 100 เมตร |
| **Priority** | Medium |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Accuracy: 150 meters |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลองความแม่นยำต่ำด้วย Developer Tools |
| **Expected Result** | 1. validation.warnings = ["ความแม่นยำตำแหน่งต่ำเกินไป กรุณาตรวจสอบการรับสัญญาณ GPS"]<BR>2. mockIndicators += 1 |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-03-06: ความเร็วเคลื่อนที่ผิดปกติ (Impossible speed)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-03-06 |
| **Test Case Name** | ความเร็วเคลื่อนที่ผิดปกติ (Impossible speed) |
| **Description** | ตรวจสอบความเร็วเคลื่อนที่เกิน 100 m/s (360 km/h) |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. มีตำแหน่งเดิมใน history |
| **Test Data** | Position 1: (13.7563, 100.5018) at t=0<br>Position 2: (15.8700, 100.9925) at t=60 (~180 km in 60s = 3000 km/h) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลองการเคลื่อนที่ด้วยความเร็วผิดปกติ |
| **Expected Result** | 1. validation.errors = ["ตรวจพบการเคลื่อนที่ด้วยความเร็วผิดปกติ อาจเป็นการจำลองตำแหน่ง"]<BR>2. mockIndicators += 3 |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-04: Mock Location Detection
#### TC-LOC-04-01: ไม่พบ Mock Location (Normal GPS)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-04-01 |
| **Test Case Name** | ไม่พบ Mock Location (Normal GPS) |
| **Description** | การใช้งาน GPS ปกติ ไม่พบ mock location |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. ไม่ได้เปิด Mock Location App |
| **Test Data** | Normal GPS data |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. ใช้งาน GPS ปกติ |
| **Expected Result** | 1. validation = { isValid: true, isMockDetected: false }<BR>2. locationGranted = true<BR>3. isMockLocationDetected = false<BR>4. ปุ่มลงเวลาเข้า/ออกใช้งานได้ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-04-02: พบ Mock Location - Fake GPS App
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-04-02 |
| **Test Case Name** | พบ Mock Location - Fake GPS App |
| **Description** | ตรวจพบ mock location จาก Fake GPS App |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Mock location from Fake GPS App |
| **Test Steps** | 1. เปิด Fake GPS Location App<BR>2. ตั้งค่าตำแหน่งปลอม<BR>3. เปิดแอป HRMS<BR>4. ขอรับพิกัด |
| **Expected Result** | 1. ตรวจพบ mock location (indicators >= 3)<BR>2. แสดงข้อความ: "ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง กรุณาปิดแอปจำลองตำแหน่งและลองใหม่"<BR>3. isMockLocationDetected = true<BR>4. disabledBtn = true |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-04-03: พบ Mock Location - พิกัด (0,0)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-04-03 |
| **Test Case Name** | พบ Mock Location - พิกัด (0,0) |
| **Description** | ตรวจพบพิกัด (0,0) ซึ่งเป็นค่า default ของ mock location |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Latitude: 0, Longitude: 0 |
| **Test Steps** | 1. จำลองพิกัด (0,0) ด้วย Mock Location App<BR>2. เปิดแอป HRMS<BR>3. ขอรับพิกัด |
| **Expected Result** | 1. mockIndicators = 3 (จาก invalid coordinates)<BR>2. isMockDetected = true<BR>3. confidence = 'medium'<BR>4. แสดงข้อความแจ้งเตือน |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-04-04: พบ Mock Location - ข้อมูลเก่าเกินไป
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-04-04 |
| **Test Case Name** | พบ Mock Location - ข้อมูลเก่าเกินไป |
| **Description** | ตรวจพบข้อมูลตำแหน่งเก่าเกิน 60 วินาที |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Timestamp: Date.now() - 70,000 ms |
| **Test Steps** | 1. จำลอง timestamp เก่าเกิน 60 วินาที<BR>2. เปิดแอป HRMS<BR>3. ขอรับพิกัด |
| **Expected Result** | 1. mockIndicators = 2 (จาก stale timestamp)<BR>2. แสดง warning: "ข้อมูลตำแหน่งเก่าเกินไป กรุณารับสัญญาณ GPS ใหม่" |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-04-05: พบ Mock Location - ความเร็วผิดปกติ
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-04-05 |
| **Test Case Name** | พบ Mock Location - ความเร็วผิดปกติ |
| **Description** | ตรวจพบความเร็วเคลื่อนที่ผิดปกติ |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. มีตำแหน่งเดิมใน history |
| **Test Data** | Speed > 100 m/s |
| **Test Steps** | 1. จำลองการเคลื่อนที่ด้วยความเร็ว > 100 m/s<BR>2. เปิดแอป HRMS |
| **Expected Result** | 1. mockIndicators = 3 (จาก impossible speed)<BR>2. isMockDetected = true<BR>3. confidence = 'medium' |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-04-06: พบ Mock Location - หลาย indicators (Confidence High)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-04-06 |
| **Test Case Name** | พบ Mock Location - หลาย indicators (Confidence High) |
| **Description** | ตรวจพบหลาย mock indicators พร้อมกัน |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | Combined: invalid coordinates (0,0) + stale timestamp + impossible speed |
| **Test Steps** | 1. จำลอง multiple mock indicators<BR>2. เปิดแอป HRMS |
| **Expected Result** | 1. mockIndicators >= 5<BR>2. isMockDetected = true<BR>3. confidence = 'high'<BR>4. แสดงข้อความแจ้งเตือนชัดเจน |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-05: POI Resolution
#### TC-LOC-05-01: แปลงพิกัดเป็นชื่อสถานที่สำเร็จ (Bangkok GIS)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-05-01 |
| **Test Case Name** | แปลงพิกัดเป็นชื่อสถานที่สำเร็จ (Bangkok GIS) |
| **Description** | แปลงพิกัดเป็นชื่อสถานที่สำเร็จผ่าน Bangkok GIS API |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. รับพิกัดสำเร็จแล้ว |
| **Test Data** | Latitude: 13.7563, Longitude: 100.5018 (Sanam Suea Pa, Bangkok) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. รับพิกัด GPS<BR>3. รอให้ระบบแปลงพิกัดเป็นชื่อสถานที่ |
| **Expected Result** | 1. เรียก Bangkok GIS API: `https://bmagis.bangkok.go.th/...`<BR>2. แสดงชื่อสถานที่ (POI name)<BR>3. poiPlaceName มีค่า |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-05-02: แปลงพิกัดเป็นชื่อสถานที่สำเร็จ (ArcGIS Fallback)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-05-02 |
| **Test Case Name** | แปลงพิกัดเป็นชื่อสถานที่สำเร็จ (ArcGIS Fallback) |
| **Description** | แปลงพิกัดเป็นชื่อสถานที่สำเร็จผ่าน ArcGIS API (เมื่อ Bangkok GIS fail) |
| **Priority** | Medium |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. Bangkok GIS API ล้มเหลว |
| **Test Data** | Latitude: 13.7563, Longitude: 100.5018 |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. รับพิกัด GPS<BR>3. จำลอง Bangkok GIS API fail<BR>4. รอ fallback ไป ArcGIS |
| **Expected Result** | 1. เรียก ArcGIS API: `https://geocode.arcgis.com/...`<BR>2. แสดงชื่อสถานที่ (POI name)<BR>3. poiPlaceName มีค่า |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-05-03: แปลงพิกัดล้มเหลว (ทั้งสอง service down)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-05-03 |
| **Test Case Name** | แปลงพิกัดล้มเหลว (ทั้งสอง service down) |
| **Description** | แปลงพิกัดล้มเหลวเมื่อทั้ง Bangkok GIS และ ArcGIS down |
| **Priority** | Low |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. จำลองทั้งสอง API fail |
| **Expected Result** | 1. แอปยังทำงานต่อไปได้<BR>2. แผนที่แสดงตำแหน่งแต่ไม่มีชื่อสถานที่<BR>3. formLocation.POI = '' |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-06: Check-in with Location
#### TC-LOC-06-01: ลงเวลาเข้าสำเร็จ - ณ สถานที่ตั้ง (In-place)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-06-01 |
| **Test Case Name** | ลงเวลาเข้าสำเร็จ - ณ สถานที่ตั้ง (In-place) |
| **Description** | ลงเวลาเข้าสำเร็จเมื่ออยู่ ณ สถานที่ตั้ง |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. รับพิกัดและชื่อสถานที่สำเร็จ<BR>4. ถ่ายรูปภาพแล้ว<BR>5. statusCheckin = true (เข้างาน) |
| **Test Data** | workplace: 'in-place', locationName: '', POI: 'สนามเสือป่า', img: (รูปถ่าย) |
| **Test Steps** | 1. เลือก "ในสถานที่"<BR>2. กด "ลงเวลาเข้างาน"<BR>3. ยืนยันการลงเวลา |
| **Expected Result** | 1. API call: POST `/leave/check-in`<BR>2. formdata: { lat, lon, POI, isLocation: true, locationName: '', img, remark, checkInId }<BR>3. แสดง modal ลงเวลาเข้างานสำเร็จ<BR>4. statusCheckin = false |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-06-02: ลงเวลาเข้าสำเร็จ - นอกสถานที่ตั้ง (Off-site)
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-06-02 |
| **Test Case Name** | ลงเวลาเข้าสำเร็จ - นอกสถานที่ตั้ง (Off-site) |
| **Description** | ลงเวลาเข้าสำเร็จเมื่ออยู่นอกสถานที่ตั้ง |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. รับพิกัดและชื่อสถานที่สำเร็จ<BR>4. ถ่ายรูปภาพแล้ว<BR>5. statusCheckin = true (เข้างาน) |
| **Test Data** | workplace: 'off-site', locationName: 'ปฏิบัติงานที่บ้าน (WFH)', POI: 'บ้าน', img: (รูปถ่าย) |
| **Test Steps** | 1. เลือก "นอกสถานที่"<BR>2. เลือก "ปฏิบัติงานที่บ้าน (WFH)"<BR>3. กด "ลงเวลาเข้างาน"<BR>4. ยืนยันการลงเวลา |
| **Expected Result** | 1. API call: POST `/leave/check-in`<BR>2. formdata: { lat, lon, POI, isLocation: false, locationName: 'ปฏิบัติงานที่บ้าน (WFH)', img, remark, checkInId }<BR>3. แสดง modal ลงเวลาเข้างานสำเร็จ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-06-03: ลงเวลาเข้าล้มเหลว - Mock Location detected
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-06-03 |
| **Test Case Name** | ลงเวลาเข้าล้มเหลว - Mock Location detected |
| **Description** | ลงเวลาเข้าล้มเหลวเมื่อตรวจพบ mock location |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. เปิด Mock Location App |
| **Test Data** | Mock location enabled |
| **Test Steps** | 1. เปิด Mock Location App<BR>2. ตั้งค่าตำแหน่งปลอง<BR>3. เปิดแอป HRMS<BR>4. พยายามลงเวลาเข้างาน |
| **Expected Result** | 1. แสดงข้อความ: "ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง..."<BR>2. isMockLocationDetected = true<BR>3. disabledBtn = true<BR>4. ไม่สามารถลงเวลาเข้างานได้ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-06-04: ลงเวลาเข้าล้มเหลว - Location permission denied
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-06-04 |
| **Test Case Name** | ลงเวลาเข้าล้มเหลว - Location permission denied |
| **Description** | ลงเวลาเข้าล้มเหลวเมื่อปฏิเสธ Location Permission |
| **Priority** | High |
| **Pre-conditions** | 1. ยอมรับ Privacy Policy แล้ว<BR>2. ปฏิเสธ Location Permission |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. ปฏิเสธ Location Permission<BR>3. พยายามลงเวลาเข้างาน |
| **Expected Result** | 1. locationGranted = false<BR>2. ปุ่มลงเวลาเข้า/ออก disabled<BR>3. ไม่สามารถลงเวลาเข้างานได้ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-07: Check-out with Location
#### TC-LOC-07-01: ลงเวลาออกสำเร็จ
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-07-01 |
| **Test Case Name** | ลงเวลาออกสำเร็จ |
| **Description** | ลงเวลาออกสำเร็จพร้อมตำแหน่ง |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. เคยลงเวลาเข้างานแล้ว<BR>4. statusCheckin = false (ออกงาน) |
| **Test Data** | POI: 'Office', img: (รูปถ่าย) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. ถ่ายรูปภาพ<BR>3. กด "ลงเวลาออกงาน" |
| **Expected Result** | 1. API call: POST `/leave/check-in` (with checkInId)<BR>2. แสดง modal ลงเวลาออกงานสำเร็จ<BR>3. statusCheckin = true |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-07-02: ลงเวลาออกล้มเหลว - Mock Location detected
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-07-02 |
| **Test Case Name** | ลงเวลาออกล้มเหลว - Mock Location detected |
| **Description** | ลงเวลาออกล้มเหลวเมื่อตรวจพบ mock location |
| **Priority** | High |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. เคยลงเวลาเข้างานแล้ว<BR>4. เปิด Mock Location App |
| **Test Data** | Mock location enabled |
| **Test Steps** | 1. เปิด Mock Location App<BR>2. พยายามลงเวลาออกงาน |
| **Expected Result** | 1. แสดงข้อความ: "ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง..."<BR>2. disabledBtn = true<BR>3. ไม่สามารถลงเวลาออกงานได้ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-08: Special Time Entry
#### TC-LOC-08-01: บันทึกเวลาพิเศษพร้อมตำแหน่งสำเร็จ
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-08-01 |
| **Test Case Name** | บันทึกเวลาพิเศษพร้อมตำแหน่งสำเร็จ |
| **Description** | บันทึกเวลาพิเศษพร้อมตำแหน่งสำเร็จ |
| **Priority** | Medium |
| **Pre-conditions** | 1. อนุญาต Location Permission แล้ว<BR>2. ยอมรับ Privacy Policy แล้ว<BR>3. รับพิกัดสำเร็จ |
| **Test Data** | POI: 'Meeting Room', img: (รูปถ่าย) |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. ไปที่หน้าบันทึกเวลาพิเศษ<BR>3. กรอกข้อมูล<BR>4. บันทึก |
| **Expected Result** | 1. บันทึกเวลาพิเศษสำเร็จ<BR>2. มีข้อมูลตำแหน่ง |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-08-02: บันทึกเวลาพิเศษล้มเหลว - ไม่ระบุตำแหน่ง
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-08-02 |
| **Test Case Name** | บันทึกเวลาพิเศษล้มเหลว - ไม่ระบุตำแหน่ง |
| **Description** | บันทึกเวลาพิเศษล้มเหลวเมื่อไม่ระบุตำแหน่ง |
| **Priority** | Medium |
| **Pre-conditions** | 1. ยอมรับ Privacy Policy แล้ว<BR>2. ปฏิเสธ Location Permission |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. ปฏิเสธ Location Permission<BR>3. พยายามบันทึกเวลาพิเศษ |
| **Expected Result** | 1. แจ้งเตือนให้ระบุตำแหน่ง |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
### TC-LOC-09: Privacy Consent
#### TC-LOC-09-01: แสดง Privacy Modal ก่อนใช้ Location
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-09-01 |
| **Test Case Name** | แสดง Privacy Modal ก่อนใช้ Location |
| **Description** | แสดง Privacy Modal ก่อนใช้ Location |
| **Priority** | High |
| **Pre-conditions** | 1. เปิดแอปครั้งแรก<BR>2. ยังไม่ยอมรับ Privacy Policy |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. กดปุ่มที่ต้องการ Location (แผนที่/กล้อง) |
| **Expected Result** | 1. privacyStore.modalPrivacy = true<BR>2. แสดง Privacy Modal<BR>3. ไม่สามารถใช้งาน Location ได้จนกว่าจะยอมรับ |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-09-02: ยอมรับ Privacy Policy
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-09-02 |
| **Test Case Name** | ยอมรับ Privacy Policy |
| **Description** | ยอมรับ Privacy Policy และใช้งาน Location ได้ |
| **Priority** | High |
| **Pre-conditions** | 1. เปิดแอปครั้งแรก<BR>2. Privacy Modal แสดงขึ้นมา |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. แสดง Privacy Modal<BR>3. กด "ยอมรับ" |
| **Expected Result** | 1. privacyStore.isAccepted = true<BR>2. privacyStore.modalPrivacy = false<BR>3. สามารถใช้งาน Location ได้<BR>4. เรียก mapRef.value?.requestLocationPermission() |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
#### TC-LOC-09-03: ปฏิเสธ Privacy Policy
| Field | Value |
|-------|-------|
| **Test Case ID** | TC-LOC-09-03 |
| **Test Case Name** | ปฏิเสธ Privacy Policy |
| **Description** | ปฏิเสธ Privacy Policy และไม่สามารถใช้งาน Location |
| **Priority** | High |
| **Pre-conditions** | 1. เปิดแอปครั้งแรก<BR>2. Privacy Modal แสดงขึ้นมา |
| **Test Data** | - |
| **Test Steps** | 1. เปิดแอป HRMS<BR>2. แสดง Privacy Modal<BR>3. กด "ปฏิเสธ" หรือปิด Modal |
| **Expected Result** | 1. privacyStore.isAccepted = false<BR>2. privacyStore.modalPrivacy = false<BR>3. ไม่สามารถใช้งาน Location ได้<BR>4. แจ้งเตือนเมื่อพยายามใช้งาน Location |
| **Actual Result** | |
| **Status** | Not Run |
| **Tested By** | |
| **Test Date** | |
---
## 6. Test Summary
### 6.1 Test Case Statistics
| Category | Total | Critical | High | Medium | Low |
|----------|-------|----------|------|--------|-----|
| Location Permission | 2 | - | 2 | - | - |
| Location Acquisition | 4 | - | 2 | 2 | - |
| Location Validation | 6 | - | 4 | 2 | - |
| Mock Location Detection | 6 | - | 6 | - | - |
| POI Resolution | 3 | - | 1 | 1 | 1 |
| Check-in with Location | 4 | - | 4 | - | - |
| Check-out with Location | 2 | - | 2 | - | - |
| Special Time Entry | 2 | - | - | 2 | - |
| Privacy Consent | 3 | - | 3 | - | - |
| **Total** | **32** | - | **24** | **7** | **1** |
### 6.2 Execution Status
| Status | Count | Percentage |
|--------|-------|------------|
| Not Run | 32 | 100% |
| Pass | 0 | 0% |
| Fail | 0 | 0% |
| Blocked | 0 | 0% |
---
## 7. References
### 7.1 API Endpoints
| Endpoint | Method | Description |
|----------|--------|-------------|
| `/leave/check-in` | POST | Check-in/Check-out with location data |
| `/leave/check-time` | GET | Get check-in/check-out status |
| `/leave/check-status` | GET | Get queue status |
| `/leave/user/checkout-check/{isSeminar}` | GET | Check before check-out |
### 7.2 Key Functions
| Function | Location | Description |
|----------|----------|-------------|
| `validateLocation()` | `useLocationValidation.ts` | Main validation function |
| `validateCoordinates()` | `useLocationValidation.ts` | Coordinate validation |
| `validateTimestamp()` | `useLocationValidation.ts` | Timestamp validation |
| `validateAccuracy()` | `useLocationValidation.ts` | Accuracy validation |
| `validateSpeed()` | `useLocationValidation.ts` | Speed validation |
| `haversineDistance()` | `useLocationValidation.ts` | Distance calculation |
| `checkPrivacyAccepted()` | `usePermissions.ts` | Check privacy consent |
| `requestLocationPermission()` | `AscGISMap.vue` | Request location permission |
### 7.3 Related Files
- `/src/composables/useLocationValidation.ts` - Location validation logic
- `/src/views/HomeView.vue` - Check-in/Check-out page
- `/src/components/AscGISMap.vue` - Map component with location validation
- `/src/api/api.checkin.ts` - Check-in API endpoints
- `/src/stores/privacy.ts` - Privacy store for consent management
- `/src/composables/usePermissions.ts` - Permission checking utilities
---
## 8. Revision History
| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0.0 | 2025-03-09 | QA Team | Initial version - 32 test cases for Location features |
---
## 9. Approval
| Role | Name | Signature | Date |
|------|------|-----------|------|
| QA Lead | | | |
| Developer | | | |
| Product Owner | | | |

File diff suppressed because it is too large Load diff

View file

@ -30,7 +30,6 @@
"keycloak-js": "^22.0.2", "keycloak-js": "^22.0.2",
"moment": "^2.29.4", "moment": "^2.29.4",
"pinia": "^2.1.4", "pinia": "^2.1.4",
"pinia-plugin-persistedstate": "^3.2.3",
"quasar": "^2.11.1", "quasar": "^2.11.1",
"register-service-worker": "^1.7.2", "register-service-worker": "^1.7.2",
"simple-vue-camera": "^1.1.3", "simple-vue-camera": "^1.1.3",

View file

@ -9,8 +9,7 @@ export default {
checkStatus: () => `${leave}/check-status`, checkStatus: () => `${leave}/check-status`,
keycloakLogSSO: `${env.API_URI}/org/keycloak/log/sso`, keycloakLogSSO: `${env.API_URI}/org/keycloak/log/sso`,
keycloakPosition: () => keycloakPosition: () => `${env.API_URI}/org/profile/keycloak/position`,
`${env.API_URI}/org/profile/keycloak/position-checkin`,
fileByFile: (name: string, group: string, id: string, fileName: string) => fileByFile: (name: string, group: string, id: string, fileName: string) =>
`${urlFile}/file/${name}/${group}/${id}/${fileName}`, `${urlFile}/file/${name}/${group}/${id}/${fileName}`,

View file

@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none">
<path d="M12 2c-3.866 0-7 3.134-7 7 0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7Z" fill="#1E88E5"/>
<circle cx="12" cy="9" r="3" fill="#fff"/>
</svg>

Before

Width:  |  Height:  |  Size: 254 B

View file

@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24" fill="none">
<path d="M12 2c-3.866 0-7 3.134-7 7 0 5.25 7 13 7 13s7-7.75 7-13c0-3.866-3.134-7-7-7Z" fill="#E53935"/>
<circle cx="12" cy="9" r="3" fill="#fff"/>
</svg>

Before

Width:  |  Height:  |  Size: 254 B

View file

@ -1,415 +1,204 @@
<script setup lang="ts"> <script setup lang="ts">
import { import { ref } from 'vue'
computed,
ref,
shallowRef,
onBeforeUnmount,
onMounted,
watch,
nextTick,
} from 'vue'
import { loadModules } from 'esri-loader' import { loadModules } from 'esri-loader'
import axios from 'axios' import axios from 'axios'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
import { useQuasar } from 'quasar' import { useQuasar } from 'quasar'
import { usePrivacyStore } from '@/stores/privacy' import { usePrivacyStore } from '@/stores/privacy'
import markerRedUrl from '@/assets/markers/marker-red.svg?url' import { useLocationValidation } from '@/composables/useLocationValidation'
import markerBlueUrl from '@/assets/markers/marker-blue.svg?url'
const mixin = useCounterMixin() const mixin = useCounterMixin()
const { messageError } = mixin const { messageError } = mixin
const privacyStore = usePrivacyStore() const privacyStore = usePrivacyStore()
const emit = defineEmits(['update:location']) // import type { LocationObject } from '@/interface/index/Main'
const mapElement = ref<HTMLElement | null>(null)
// Accept initial POI from parent to prevent skeleton on re-mount const emit = defineEmits(['update:location', 'locationStatus', 'mockDetected'])
const props = defineProps<{
initialPOI?: string
}>()
const $q = useQuasar() const $q = useQuasar()
// Throttle mechanism to prevent excessive location updates const { validateLocation, showMockWarning } = useLocationValidation()
const LOCATION_UPDATE_THROTTLE_MS = 500
let lastLocationUpdate = 0
// Track if map is initialized to prevent re-initialization
const isMapInitialized = ref<boolean>(false)
const isInitializing = ref<boolean>(false)
const currentScreenSize = ref<boolean>($q.screen.gt.xs) // Track screen size to detect changes
const mobileMapExpanded = ref<boolean>(true)
function updateLocation(latitude: number, longitude: number, namePOI: string) { function updateLocation(latitude: number, longitude: number, namePOI: string) {
const now = Date.now()
// Skip update if called too frequently (within throttle period)
if (now - lastLocationUpdate < LOCATION_UPDATE_THROTTLE_MS) {
return
}
lastLocationUpdate = now
// event parent component props // event parent component props
emit('update:location', latitude, longitude, namePOI) emit('update:location', latitude, longitude, namePOI)
} }
const poiPlaceName = ref<string>(props.initialPOI || '') // - use initialPOI if provided const poiPlaceName = ref<string>('') //
const mapView = shallowRef<any>(null) // Store mapView reference for cleanup (use shallowRef to avoid reactivity issues)
const desktopMapContainerRef = ref<HTMLElement | null>(null)
const mobileMapContainerRef = ref<HTMLElement | null>(null)
const isMapVisible = computed(
() => !!mapView.value && !mapView.value.destroyed && isMapInitialized.value
)
// Unique container ID for each component instance to avoid conflicts // Replace ArcGIS api key
const mapContainerId = `mapViewDisplay_${Math.random()
.toString(36)
.substring(2, 9)}`
// ArcGIS API key from environment variable
const apiKey = ref<string>( const apiKey = ref<string>(
'YLATgWuywoeRLHn6KImj5rg7UaP8bJoR9jiTldoCVBHlqFIebwMSA5wIXEmcYhwXwMHkmNISEYtUz3x0oiGIIx0bIXXnUwi0OzupoOEtDrQIsRPVtor7gaPpXEmH8TrNaMT3snf6zO_yujHLGzborg-L9aeAjTJn4ndL6f8qFmRzYcX93E2vyA-7XCufLYTRsdTE5Aq-9hnx1q9PmYVMqhAZpL7dWqn3JgO33fRXetk.' 'YLATgWuywoeRLHn6KImj5rg7UaP8bJoR9jiTldoCVBHlqFIebwMSA5wIXEmcYhwXwMHkmNISEYtUz3x0oiGIIx0bIXXnUwi0OzupoOEtDrQIsRPVtor7gaPpXEmH8TrNaMT3snf6zO_yujHLGzborg-L9aeAjTJn4ndL6f8qFmRzYcX93E2vyA-7XCufLYTRsdTE5Aq-9hnx1q9PmYVMqhAZpL7dWqn3JgO33fRXetk.'
// 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP'
) )
const zoomMap = ref<number>(18) const zoomMap = ref<number>(18)
const textTooltip = ref<string>(
'พื้นที่ใกล้เคียงคือ สถานที่สำคัญรอบตัวคุณ (ไม่ใช่ตำแหน่งปัจจุบัน)'
)
let attachRetryTimer: number | undefined
let mapInitVersion = 0
let isRecoveryReinitializing = false
function getActiveMapContainer() {
return $q.screen.gt.xs
? desktopMapContainerRef.value
: mobileMapContainerRef.value
}
async function waitForActiveMapContainer(maxAttempts = 25, delayMs = 120) {
for (let i = 0; i < maxAttempts; i += 1) {
await nextTick()
const container = getActiveMapContainer()
if (container && container.clientWidth > 0 && container.clientHeight > 0) {
return container
}
await new Promise((resolve) => setTimeout(resolve, delayMs))
}
return null
}
function clearAttachRetryTimer() {
if (attachRetryTimer) {
clearTimeout(attachRetryTimer)
attachRetryTimer = undefined
}
}
async function recoverMapByReinitialize() {
if (isRecoveryReinitializing) {
return
}
isRecoveryReinitializing = true
try {
mapInitVersion += 1
isInitializing.value = false
clearAttachRetryTimer()
if (mapView.value && !mapView.value.destroyed) {
mapView.value.destroy()
mapView.value = null
}
isMapInitialized.value = false
await nextTick()
await initializeMap()
} finally {
isRecoveryReinitializing = false
}
}
function reattachAndResizeMap(retry = 0) {
if (!mapView.value || mapView.value.destroyed) {
return
}
const activeContainer = getActiveMapContainer()
if (
!activeContainer ||
activeContainer.clientWidth === 0 ||
activeContainer.clientHeight === 0
) {
if (retry < 15) {
clearAttachRetryTimer()
attachRetryTimer = window.setTimeout(() => {
reattachAndResizeMap(retry + 1)
}, 140)
} else if (!isRecoveryReinitializing) {
void recoverMapByReinitialize()
}
return
}
clearAttachRetryTimer()
nextTick(() => {
if (!mapView.value || mapView.value.destroyed) {
return
}
if (mapView.value.container !== activeContainer) {
mapView.value.container = null
mapView.value.container = activeContainer
}
mapView.value.resize()
mapView.value.requestRender?.()
mapView.value
.goTo(
{
center: mapView.value.center,
zoom: mapView.value.zoom,
},
{ animate: false }
)
.catch(() => {
// Ignore interrupted goTo during rapid orientation changes.
})
})
}
async function initializeMap() { async function initializeMap() {
if (isInitializing.value || (mapView.value && !mapView.value.destroyed)) {
return
}
const initVersion = ++mapInitVersion
isInitializing.value = true
try { try {
// Load modules of ArcGIS // Load modules of ArcGIS
const [esriConfig, Map, MapView, Point, Graphic, TileLayer] = loadModules([
await loadModules([ 'esri/config',
'esri/config', 'esri/Map',
'esri/Map', 'esri/views/MapView',
'esri/views/MapView', 'esri/geometry/Point',
'esri/geometry/Point', 'esri/Graphic',
'esri/Graphic', 'esri/layers/TileLayer',
// 'esri/layers/TileLayer', ]).then(async ([esriConfig, Map, MapView, Point, Graphic, TileLayer]) => {
]) // Set apiKey
// Set apiKey // esriConfig.apiKey =
// esriConfig.apiKey = // 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP'
// 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP'
// Create a FeatureLayer using a custom server URL // Create a FeatureLayer using a custom server URL
// const hillshadeLayer = new TileLayer({ // const hillshadeLayer = new TileLayer({
// url: `https://bmagis.bangkok.go.th/arcgis/rest/services/cache/BMA_3D_2D_Cache/MapServer`, // url: `https://bmagis.bangkok.go.th/arcgis/rest/services/cache/BMA_3D_2D_Cache/MapServer`,
// }) // })
const map = new Map({ const map = new Map({
basemap: 'streets', basemap: 'streets',
// basemap: 'arcgis-topographic', // basemap: 'arcgis-topographic',
// layers: [hillshadeLayer], // layers: [hillshadeLayer],
}) })
if (initVersion !== mapInitVersion) { navigator.geolocation.getCurrentPosition(async (position) => {
return const { latitude, longitude } = position.coords
}
const position = await new Promise<GeolocationPosition>( const mapView = new MapView({
(resolve, reject) => { container: 'mapViewDisplay',
navigator.geolocation.getCurrentPosition(resolve, reject, { map: map,
enableHighAccuracy: true, center: {
timeout: 10000, latitude: latitude,
}) longitude: longitude,
} }, // Set the initial map center current position
)
if (initVersion !== mapInitVersion) { zoom: zoomMap.value,
return constraints: {
} snapToZoom: false, // Disables snapping to the zoom level
minZoom: zoomMap.value, // Set minimum zoom level
const { latitude, longitude } = position.coords maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom)
const mapContainer = await waitForActiveMapContainer()
if (!mapContainer || initVersion !== mapInitVersion) {
isMapInitialized.value = false
return
}
mapView.value = new MapView({
container: mapContainer,
map: map,
center: {
latitude: latitude,
longitude: longitude,
}, // Set the initial map center current position
zoom: zoomMap.value,
constraints: {
snapToZoom: false, // Disables snapping to the zoom level
minZoom: zoomMap.value, // Set minimum zoom level
maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom)
},
ui: {
components: [], // Empty array to remove all default UI components
},
})
await mapView.value.when()
if (initVersion !== mapInitVersion) {
if (mapView.value && !mapView.value.destroyed) {
mapView.value.destroy()
}
mapView.value = null
return
}
isMapInitialized.value = true
reattachAndResizeMap()
//
const userPoint = new Point({ longitude, latitude })
const userSymbol = {
type: 'picture-marker',
url: markerRedUrl,
width: '32px',
height: '32px',
}
const userGraphic = new Graphic({
geometry: userPoint,
symbol: userSymbol,
})
mapView.value.graphics.add(userGraphic)
// Get POI place server .
// await axios
// .get(
// 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
// {
// params: {
// f: 'json', // Format JSON response
// distance: 2000,
// category: 'POI',
// location: {
// spatialReference: { wkid: 4326 },
// x: longitude,
// y: latitude,
// },
// token: apiKey.value,
// },
// }
// )
// .then((response) => {
// // console.log('poi', response.data.location)
// poiPlaceName.value = response.data.address
// ? response.data.address.PlaceName === ''
// ? response.data.address.ShortLabel
// : response.data.address.PlaceName
// : ''
// const poiPoint = new Point({
// longitude: response.data.location.x,
// latitude: response.data.location.y,
// })
// const poiSymbol = {
// type: 'picture-marker',
// url: markerBlueUrl,
// width: '32px',
// height: '32px',
// }
// const poiGraphic = new Graphic({
// geometry: poiPoint,
// symbol: poiSymbol,
// })
// mapView.value.graphics.add(poiGraphic)
// // POI
// mapView.value.goTo({
// target: [userPoint, poiPoint],
// zoom: zoomMap.value,
// })
// // Mark map as initialized
// isMapInitialized.value = true
// updateLocation(latitude, longitude, poiPlaceName.value)
// })
// .catch(async (error) => {
// console.error('Error fetching points of interest:', error)
// Get POI place server arcgis token
await axios
.get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/',
{
params: {
f: 'json', // Format JSON response
distance: 2000,
category: 'POI',
location: {
spatialReference: { wkid: 4326 },
x: longitude,
y: latitude,
},
}, },
}
)
.then((response) => {
if (initVersion !== mapInitVersion || !mapView.value) {
return
}
// console.log('poi', response.data.location) ui: {
poiPlaceName.value = response.data.address components: [], // Empty array to remove all default UI components
? response.data.address.PlaceName === '' },
? response.data.address.ShortLabel
: response.data.address.PlaceName
: 'ไม่พบข้อมูล'
const poiPoint = new Point({
longitude: response.data.location.x,
latitude: response.data.location.y,
}) })
const poiSymbol = {
//
const userPoint = new Point({ longitude, latitude })
const userSymbol = {
type: 'picture-marker', type: 'picture-marker',
url: markerBlueUrl, url: 'http://maps.google.com/mapfiles/ms/icons/red.png',
width: '32px', width: '32px',
height: '32px', height: '32px',
} }
const poiGraphic = new Graphic({ const userGraphic = new Graphic({
geometry: poiPoint, geometry: userPoint,
symbol: poiSymbol, symbol: userSymbol,
})
mapView.value.graphics.add(poiGraphic)
// POI
mapView.value.goTo({
target: [userPoint, poiPoint],
zoom: zoomMap.value,
}) })
mapView.graphics.add(userGraphic)
// Get POI place server .
await axios
.get(
'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
{
params: {
f: 'json', // Format JSON response
distance: 2000,
category: 'POI',
location: {
spatialReference: { wkid: 4326 },
x: longitude,
y: latitude,
},
token: apiKey.value,
},
}
)
.then((response) => {
// console.log('poi', response.data.location)
poiPlaceName.value = response.data.address
? response.data.address.PlaceName === ''
? response.data.address.ShortLabel
: response.data.address.PlaceName
: 'ไม่พบข้อมูล'
const poiPoint = new Point({
longitude: response.data.location.x,
latitude: response.data.location.y,
})
const poiSymbol = {
type: 'picture-marker',
url: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
width: '32px',
height: '32px',
}
const poiGraphic = new Graphic({
geometry: poiPoint,
symbol: poiSymbol,
})
mapView.graphics.add(poiGraphic)
// POI
mapView.goTo({
target: [userPoint, poiPoint],
zoom: zoomMap.value,
})
updateLocation(latitude, longitude, poiPlaceName.value) updateLocation(latitude, longitude, poiPlaceName.value)
}) })
.catch(() => { .catch(async (error) => {
if (initVersion !== mapInitVersion) { // console.error('Error fetching points of interest:', error)
return // Get POI place server arcgis token
} await axios
poiPlaceName.value = poiPlaceName.value || 'ไม่พบข้อมูล' .get(
updateLocation(latitude, longitude, poiPlaceName.value) 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/',
}) {
params: {
f: 'json', // Format JSON response
distance: 2000,
category: 'POI',
location: {
spatialReference: { wkid: 4326 },
x: longitude,
y: latitude,
},
},
}
)
.then((response) => {
// console.log('poi', response.data.location)
poiPlaceName.value = response.data.address
? response.data.address.PlaceName === ''
? response.data.address.ShortLabel
: response.data.address.PlaceName
: 'ไม่พบข้อมูล'
const poiPoint = new Point({
longitude: response.data.location.x,
latitude: response.data.location.y,
})
const poiSymbol = {
type: 'picture-marker',
url: 'http://maps.google.com/mapfiles/ms/icons/blue.png',
width: '32px',
height: '32px',
}
const poiGraphic = new Graphic({
geometry: poiPoint,
symbol: poiSymbol,
})
mapView.graphics.add(poiGraphic)
// POI
mapView.goTo({
target: [userPoint, poiPoint],
zoom: zoomMap.value,
})
if (initVersion === mapInitVersion) { updateLocation(latitude, longitude, poiPlaceName.value)
reattachAndResizeMap() })
} .catch((error) => {
// console.error('Error fetching points of interest:', error)
})
})
})
})
} catch (error) { } catch (error) {
if (initVersion === mapInitVersion) {
isMapInitialized.value = false
}
console.error('Error loading the map', error) console.error('Error loading the map', error)
} finally {
if (initVersion === mapInitVersion) {
isInitializing.value = false
}
} }
} }
@ -437,8 +226,30 @@ const requestLocationPermission = () => {
navigator.geolocation.getCurrentPosition( navigator.geolocation.getCurrentPosition(
async (position) => { async (position) => {
// Permission granted // Validate location first
locationGranted.value = true const validationResult = validateLocation(position)
// Always emit mockDetected event (regardless of result)
if (validationResult.isMockDetected) {
showMockWarning(validationResult)
emit('mockDetected', validationResult)
}
// Check for critical errors (invalid coordinates) that prevent showing location
const hasCriticalErrors = validationResult.errors.some(error =>
error.includes('พิกัดตำแหน่งไม่ถูกต้อง')
)
if (hasCriticalErrors) {
locationGranted.value = false
emit('locationStatus', false)
messageError($q, '', validationResult.errors[0])
return
}
// Permission granted based on mock detection
locationGranted.value = !validationResult.isMockDetected
emit('locationStatus', !validationResult.isMockDetected)
const { latitude, longitude } = position.coords const { latitude, longitude } = position.coords
// console.log('Current position:', latitude, longitude) // console.log('Current position:', latitude, longitude)
@ -456,6 +267,7 @@ const requestLocationPermission = () => {
(error) => { (error) => {
// Permission denied // Permission denied
locationGranted.value = false locationGranted.value = false
emit('locationStatus', false)
switch (error.code) { switch (error.code) {
case error.PERMISSION_DENIED: case error.PERMISSION_DENIED:
@ -484,126 +296,15 @@ const requestLocationPermission = () => {
) )
} }
// Also add a resize event listener as a fallback for orientation changes
// that might not trigger the Quasar screen watcher
let resizeTimeout: number | undefined
const handleWindowResize = () => {
// Debounce resize events to avoid excessive calls
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
resizeTimeout = window.setTimeout(() => {
handleMapResize()
}, 300)
}
/**
* Handle map resize when screen orientation changes
* ArcGIS MapView needs to be manually resized when its container changes dimensions
* Only call resize() if the map is fully initialized
*/
function handleMapResize() {
if (mapView.value && !mapView.value.destroyed && isMapInitialized.value) {
// Use nextTick to ensure the DOM has finished updating before resizing
reattachAndResizeMap()
}
}
/**
* Watch for screen size/orientation changes
* When the screen size changes (e.g., portrait to landscape), we need to re-initialize the map
* because the container div changes between desktop and mobile versions
*/
watch(
() => $q.screen.gt.xs,
async (newValue) => {
// Skip if no actual change (same layout)
if (newValue === currentScreenSize.value) {
return
}
currentScreenSize.value = newValue
if (!newValue) {
mobileMapExpanded.value = true
}
mapInitVersion += 1
isInitializing.value = false
clearAttachRetryTimer()
// Always destroy and re-initialize when screen size changes
// This ensures the map is attached to the correct container
if (mapView.value && !mapView.value.destroyed) {
mapView.value.destroy()
mapView.value = null
}
// Reset initialization state
isMapInitialized.value = false
// Wait for DOM to update with new layout
await nextTick()
await waitForActiveMapContainer(30, 100)
// Re-initialize the map
if (privacyStore.isAccepted) {
await initializeMap()
if (!mapView.value || mapView.value.destroyed) {
await recoverMapByReinitialize()
}
reattachAndResizeMap()
}
}
)
// Watch for initialPOI prop changes to update poiPlaceName
watch(
() => props.initialPOI,
(newValue) => {
if (newValue && newValue !== poiPlaceName.value) {
poiPlaceName.value = newValue
}
}
)
// Set up resize event listener on mount
onMounted(async () => {
window.addEventListener('resize', handleWindowResize)
// Component can be remounted after orientation/layout switches.
// Recreate map automatically when consent is already granted.
if (privacyStore.isAccepted && (!mapView.value || mapView.value.destroyed)) {
await waitForActiveMapContainer(30, 100)
await initializeMap()
reattachAndResizeMap()
}
})
// Cleanup map resources when component unmounts
onBeforeUnmount(() => {
clearAttachRetryTimer()
if (mapView.value) {
mapView.value.destroy()
mapView.value = null
}
// Clean up resize event listener
window.removeEventListener('resize', handleWindowResize)
// Clear timeout if it exists
if (resizeTimeout) {
clearTimeout(resizeTimeout)
}
})
defineExpose({ defineExpose({
requestLocationPermission, requestLocationPermission,
locationGranted,
}) })
</script> </script>
<template> <template>
<!-- Loading skeleton - show until map is visible --> <!-- Loading skeleton -->
<div v-if="!isMapVisible" class="col-12"> <div v-if="!poiPlaceName" class="col-12">
<q-skeleton <q-skeleton
:height="$q.screen.gt.xs ? '35vh' : '45px'" :height="$q.screen.gt.xs ? '35vh' : '45px'"
width="100%" width="100%"
@ -613,16 +314,16 @@ defineExpose({
</div> </div>
<q-card <q-card
v-show="poiPlaceName"
bordered bordered
flat flat
class="col-12 bg-grey-2 shadow-0" class="col-12 bg-grey-2 shadow-0"
:class="{ 'map-hidden': !isMapVisible }"
:style="$q.screen.gt.xs ? ';' : 'border-radius: 20px'" :style="$q.screen.gt.xs ? ';' : 'border-radius: 20px'"
> >
<div v-if="$q.screen.gt.xs"> <div v-if="$q.screen.gt.xs">
<div <div
:id="mapContainerId" id="mapViewDisplay"
ref="desktopMapContainerRef" ref="mapElement"
style="height: 35vh; pointer-events: none" style="height: 35vh; pointer-events: none"
></div> ></div>
@ -634,11 +335,6 @@ defineExpose({
" "
> >
นทใกลเคยง นทใกลเคยง
<q-icon name="mdi-information-outline" size="xs" class="q-mr-xs" />
<q-tooltip anchor="top middle" self="bottom middle" :offset="[0, 5]">
{{ textTooltip }}
</q-tooltip>
<span class="q-px-sm">:</span> <span class="q-px-sm">:</span>
{{ poiPlaceName }} {{ poiPlaceName }}
</div> </div>
@ -646,37 +342,22 @@ defineExpose({
<q-card v-else style="border-radius: 20px"> <q-card v-else style="border-radius: 20px">
<q-expansion-item <q-expansion-item
v-model="mobileMapExpanded" class="shadow-1 overflow-hidden bg-grey-4 text-left"
class="shadow-1 overflow-hidden bg-grey-4 text-left q-pa-xs"
style="border-radius: 20px" style="border-radius: 20px"
dense dense
default-opened default-opened
> >
<template v-slot:header> <template v-slot:header>
<q-item-section avatar class="q-pr-none expanAS"> <q-item-section avatar class="q-pr-none expanAS">
<q-icon name="mdi-map-marker" color="primary" /> <q-avatar icon="mdi-map-marker" />
</q-item-section> </q-item-section>
<q-item-section> <q-item-section>
<q-item-label caption class="text-grey-7"> {{ poiPlaceName }}
นทใกลเคยง
<q-icon
name="mdi-information-outline"
size="xs"
class="q-mr-xs cursor-pointer"
@click.stop="$q.dialog({ message: textTooltip, ok: 'ตกลง' })"
/>
</q-item-label>
<q-item-label class="text-weight-medium text-grey-9">
{{ poiPlaceName || '-' }}
</q-item-label>
</q-item-section> </q-item-section>
</template> </template>
<div <div id="mapViewDisplay" style="height: 20vh"></div>
:id="mapContainerId"
ref="mobileMapContainerRef"
style="height: 20vh"
></div>
</q-expansion-item> </q-expansion-item>
</q-card> </q-card>
</q-card> </q-card>
@ -686,8 +367,4 @@ defineExpose({
.expanAS.q-item__section--avatar { .expanAS.q-item__section--avatar {
min-width: 40px !important; min-width: 40px !important;
} }
.map-hidden {
visibility: hidden;
}
</style> </style>

View file

@ -1,8 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, shallowRef, ref } from 'vue' import { onMounted, ref } from 'vue'
import { loadModules } from 'esri-loader' import { loadModules } from 'esri-loader'
import axios from 'axios' import axios from 'axios'
import markerRedUrl from '@/assets/markers/marker-red.svg?url'
import type { LocationObject } from '@/interface/index/Main'
const emit = defineEmits(['update:location']) const emit = defineEmits(['update:location'])
@ -19,67 +20,8 @@ const apiKey = ref<string>(
// 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP' // 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP'
) )
const zoomMap = ref<number>(18) const zoomMap = ref<number>(18)
const mapViewRef = shallowRef<any>(null)
const mapContainerRef = ref<HTMLElement | null>(null)
const mapRenderKey = ref<number>(0)
let resizeTimer: ReturnType<typeof setTimeout> | null = null
let resizeRetryCount = 0
const MAX_RESIZE_RETRY = 8
const isRecreatingMap = ref<boolean>(false)
function scheduleMapResize() {
if (resizeTimer) {
clearTimeout(resizeTimer)
}
// Delay a little to wait for viewport + CSS layout to settle after rotation.
resizeTimer = setTimeout(async () => {
await nextTick()
if (!mapViewRef.value || !mapContainerRef.value) {
return
}
const container = mapContainerRef.value
const mapView = mapViewRef.value
if (container.clientWidth === 0 || container.clientHeight === 0) {
if (resizeRetryCount < MAX_RESIZE_RETRY) {
resizeRetryCount += 1
scheduleMapResize()
}
return
}
resizeRetryCount = 0
// Force canvas to bind to the current element after repeated rotations.
if (mapView.container !== container) {
mapView.container = null
await nextTick()
mapView.container = container
}
mapView.resize()
mapView
.goTo(
{
center: mapView.center,
zoom: mapView.zoom,
},
{ animate: false }
)
.catch(() => {
// Ignore interruption errors from rapid orientation changes.
})
}, 300)
}
async function initializeMap() { async function initializeMap() {
if (mapViewRef.value || !mapContainerRef.value) {
return
}
try { try {
// Load modules of ArcGIS // Load modules of ArcGIS
loadModules([ loadModules([
@ -125,7 +67,7 @@ async function initializeMap() {
// MapView // MapView
const mapView = new MapView({ const mapView = new MapView({
container: mapContainerRef.value, // div container: 'mapViewDisplay', // div
map: map, map: map,
center: { center: {
latitude: latitude, latitude: latitude,
@ -137,11 +79,10 @@ async function initializeMap() {
components: [], // Empty array to remove all default UI components components: [], // Empty array to remove all default UI components
}, },
}) })
mapViewRef.value = mapView
// //
const markerSymbol = new PictureMarkerSymbol({ const markerSymbol = new PictureMarkerSymbol({
url: markerRedUrl, url: 'https://maps.google.com/mapfiles/ms/icons/red-dot.png', //
width: '32px', width: '32px',
height: '32px', height: '32px',
}) })
@ -157,42 +98,9 @@ async function initializeMap() {
position: 'top-right', // Search widget position: 'top-right', // Search widget
}) })
// token .
// await axios
// .get(
// 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
// {
// params: {
// f: 'json', // Format JSON response
// distance: 2000,
// category: 'POI',
// location: {
// spatialReference: { wkid: 4326 },
// x: longitude,
// y: latitude,
// },
// token: apiKey.value,
// },
// }
// )
// .then((response) => {
// console.log('poi', response.data.location)
// poiPlaceName.value = response.data.address
// ? response.data.address.PlaceName === ''
// ? response.data.address.ShortLabel
// : response.data.address.PlaceName
// : ''
// const poiPoint = new Point({
// longitude: response.data.location.x,
// latitude: response.data.location.y,
// })
// updateLocation(latitude, longitude, poiPlaceName.value)
// })
// .catch(async () => {
await axios await axios
.get( .get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
{ {
params: { params: {
f: 'json', // Format JSON response f: 'json', // Format JSON response
@ -203,20 +111,52 @@ async function initializeMap() {
x: longitude, x: longitude,
y: latitude, y: latitude,
}, },
token: apiKey.value,
}, },
} }
) )
.then((response) => { .then((response) => {
// console.log('poi', response.data.location) console.log('poi', response.data.location)
poiPlaceName.value = response.data.address poiPlaceName.value = response.data.address
? response.data.address.PlaceName === '' ? response.data.address.PlaceName === ''
? response.data.address.ShortLabel ? response.data.address.ShortLabel
: response.data.address.PlaceName : response.data.address.PlaceName
: 'ไม่พบข้อมูล' : 'ไม่พบข้อมูล'
const poiPoint = new Point({
longitude: response.data.location.x,
latitude: response.data.location.y,
})
updateLocation(longitude, latitude, poiPlaceName.value) updateLocation(latitude, longitude, poiPlaceName.value)
})
.catch(async () => {
await axios
.get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/',
{
params: {
f: 'json', // Format JSON response
distance: 2000,
category: 'POI',
location: {
spatialReference: { wkid: 4326 },
x: longitude,
y: latitude,
},
},
}
)
.then((response) => {
// console.log('poi', response.data.location)
poiPlaceName.value = response.data.address
? response.data.address.PlaceName === ''
? response.data.address.ShortLabel
: response.data.address.PlaceName
: 'ไม่พบข้อมูล'
updateLocation(longitude, latitude, poiPlaceName.value)
})
}) })
// })
let searchMarker: any = null let searchMarker: any = null
@ -246,41 +186,9 @@ async function initializeMap() {
symbol: markerSymbol, symbol: markerSymbol,
}) })
if (searchMarker) { if (searchMarker) {
// await axios
// .get(
// 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
// {
// params: {
// f: 'json', // Format JSON response
// distance: 2000,
// category: 'POI',
// location: {
// spatialReference: { wkid: 4326 },
// x: longitude,
// y: latitude,
// },
// token: apiKey.value,
// },
// }
// )
// .then((response) => {
// console.log('poi', response.data.location)
// poiPlaceName.value = response.data.address
// ? response.data.address.PlaceName === ''
// ? response.data.address.ShortLabel
// : response.data.address.PlaceName
// : ''
// const poiPoint = new Point({
// longitude: response.data.location.x,
// latitude: response.data.location.y,
// })
// updateLocation(latitude, longitude, poiPlaceName.value)
// })
// .catch(async () => {
await axios await axios
.get( .get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
{ {
params: { params: {
f: 'json', // Format JSON response f: 'json', // Format JSON response
@ -291,20 +199,52 @@ async function initializeMap() {
x: longitude, x: longitude,
y: latitude, y: latitude,
}, },
token: apiKey.value,
}, },
} }
) )
.then((response) => { .then((response) => {
// console.log('poi', response.data.location) console.log('poi', response.data.location)
poiPlaceName.value = response.data.address poiPlaceName.value = response.data.address
? response.data.address.PlaceName === '' ? response.data.address.PlaceName === ''
? response.data.address.ShortLabel ? response.data.address.ShortLabel
: response.data.address.PlaceName : response.data.address.PlaceName
: 'ไม่พบข้อมูล' : 'ไม่พบข้อมูล'
const poiPoint = new Point({
longitude: response.data.location.x,
latitude: response.data.location.y,
})
updateLocation(longitude, latitude, poiPlaceName.value) updateLocation(latitude, longitude, poiPlaceName.value)
})
.catch(async () => {
await axios
.get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/',
{
params: {
f: 'json', // Format JSON response
distance: 2000,
category: 'POI',
location: {
spatialReference: { wkid: 4326 },
x: longitude,
y: latitude,
},
},
}
)
.then((response) => {
// console.log('poi', response.data.location)
poiPlaceName.value = response.data.address
? response.data.address.PlaceName === ''
? response.data.address.ShortLabel
: response.data.address.PlaceName
: 'ไม่พบข้อมูล'
updateLocation(longitude, latitude, poiPlaceName.value)
})
}) })
// })
} }
mapView.graphics.add(searchMarker) mapView.graphics.add(searchMarker)
@ -335,41 +275,9 @@ async function initializeMap() {
} else { } else {
searchMarker.geometry = point // searchMarker.geometry = point //
if (searchMarker) { if (searchMarker) {
// await axios
// .get(
// 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
// {
// params: {
// f: 'json', // Format JSON response
// distance: 2000,
// category: 'POI',
// location: {
// spatialReference: { wkid: 4326 },
// x: lon,
// y: lat,
// },
// token: apiKey.value,
// },
// }
// )
// .then((response) => {
// console.log('poi', response.data.location)
// poiPlaceName.value = response.data.address
// ? response.data.address.PlaceName === ''
// ? response.data.address.ShortLabel
// : response.data.address.PlaceName
// : ''
// const poiPoint = new Point({
// longitude: response.data.location.x,
// latitude: response.data.location.y,
// })
// updateLocation(latitude, longitude, poiPlaceName.value)
// })
// .catch(async () => {
await axios await axios
.get( .get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/',
{ {
params: { params: {
f: 'json', // Format JSON response f: 'json', // Format JSON response
@ -380,20 +288,52 @@ async function initializeMap() {
x: lon, x: lon,
y: lat, y: lat,
}, },
token: apiKey.value,
}, },
} }
) )
.then((response) => { .then((response) => {
// console.log('poi', response.data.location) console.log('poi', response.data.location)
poiPlaceName.value = response.data.address poiPlaceName.value = response.data.address
? response.data.address.PlaceName === '' ? response.data.address.PlaceName === ''
? response.data.address.ShortLabel ? response.data.address.ShortLabel
: response.data.address.PlaceName : response.data.address.PlaceName
: 'ไม่พบข้อมูล' : 'ไม่พบข้อมูล'
const poiPoint = new Point({
longitude: response.data.location.x,
latitude: response.data.location.y,
})
updateLocation(lat, lon, poiPlaceName.value) updateLocation(latitude, longitude, poiPlaceName.value)
})
.catch(async () => {
await axios
.get(
'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/',
{
params: {
f: 'json', // Format JSON response
distance: 2000,
category: 'POI',
location: {
spatialReference: { wkid: 4326 },
x: lon,
y: lat,
},
},
}
)
.then((response) => {
// console.log('poi', response.data.location)
poiPlaceName.value = response.data.address
? response.data.address.PlaceName === ''
? response.data.address.ShortLabel
: response.data.address.PlaceName
: 'ไม่พบข้อมูล'
updateLocation(lat, lon, poiPlaceName.value)
})
}) })
// })
} }
} }
@ -410,64 +350,14 @@ async function initializeMap() {
} }
} }
async function recreateMapOnOrientationChange() {
if (isRecreatingMap.value) {
return
}
isRecreatingMap.value = true
try {
if (resizeTimer) {
clearTimeout(resizeTimer)
resizeTimer = null
}
if (mapViewRef.value) {
mapViewRef.value.destroy()
mapViewRef.value = null
}
mapRenderKey.value += 1
await nextTick()
await initializeMap()
scheduleMapResize()
} finally {
isRecreatingMap.value = false
}
}
onMounted(async () => { onMounted(async () => {
await initializeMap() await initializeMap()
window.addEventListener('resize', scheduleMapResize)
window.addEventListener('orientationchange', recreateMapOnOrientationChange)
window.addEventListener('pageshow', scheduleMapResize)
})
onBeforeUnmount(() => {
window.removeEventListener('resize', scheduleMapResize)
window.removeEventListener(
'orientationchange',
recreateMapOnOrientationChange
)
window.removeEventListener('pageshow', scheduleMapResize)
if (resizeTimer) {
clearTimeout(resizeTimer)
resizeTimer = null
}
if (mapViewRef.value) {
mapViewRef.value.destroy()
mapViewRef.value = null
}
}) })
</script> </script>
<template> <template>
<q-card bordered flat class="col-12 bg-grey-2 shadow-0"> <q-card bordered flat class="col-12 bg-grey-2 shadow-0">
<div :key="mapRenderKey" ref="mapContainerRef" style="height: 35vh"></div> <div id="mapViewDisplay" style="height: 35vh"></div>
<div <div
:class=" :class="

View file

@ -176,7 +176,7 @@ function onClose() {
<template> <template>
<q-dialog v-model="modal" persistent> <q-dialog v-model="modal" persistent>
<q-card style="width: 700px; max-width: 90vw"> <q-card style="width: 700px; max-width: 80vw">
<q-form greedy @submit.prevent @validation-success="onSubmit"> <q-form greedy @submit.prevent @validation-success="onSubmit">
<DialogHeader :tittle="title" :close="onClose" /> <DialogHeader :tittle="title" :close="onClose" />
<q-separator /> <q-separator />
@ -305,9 +305,6 @@ function onClose() {
</q-uploader> </q-uploader>
</div> </div>
<div class="col-12"> <div class="col-12">
<div class="text-caption text-grey-8 q-mb-sm">
แลระบบจะตดตอกลบผานทางอเมลทานระบ กรณาตรวจสอบอเมลของทานเปนระยะ
</div>
<div class="row col-12 q-col-gutter-sm"> <div class="row col-12 q-col-gutter-sm">
<div class="col-xs-12 col-md-6 col-lg-6"> <div class="col-xs-12 col-md-6 col-lg-6">
<q-input <q-input
@ -318,11 +315,10 @@ function onClose() {
class="inputgreen" class="inputgreen"
hide-bottom-space hide-bottom-space
:rules="[ :rules="[
(val: string) => !!val || 'กรุณากรอกที่อยู่อีเมล', () =>
(val: string) => { !!formData.email ||
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; !!formData.phone ||
return emailPattern.test(val) || 'กรุณากรอกที่อยู่อีเมลในรูปแบบที่ถูกต้อง'; 'กรุณากรอกอีเมลหรือเบอร์โทรติดต่อกลับ',
}
]" ]"
/> />
</div> </div>
@ -334,6 +330,12 @@ function onClose() {
v-model="formData.phone" v-model="formData.phone"
class="inputgreen" class="inputgreen"
hide-bottom-space hide-bottom-space
:rules="[
() =>
!!formData.email ||
!!formData.phone ||
'กรุณากรอกอีเมลหรือเบอร์โทรติดต่อกลับ',
]"
/> />
</div> </div>
</div> </div>

View file

@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch, onMounted, reactive } from 'vue' import { ref, watch, onMounted, reactive } from 'vue'
import type { PropType } from 'vue' import { PropType } from 'vue'
import { useQuasar } from 'quasar' import { useQuasar } from 'quasar'
import moment from 'moment' import moment from 'moment'
@ -38,7 +38,10 @@ const props = defineProps({
}, },
fetchData: { fetchData: {
type: Function, type: Function,
required: true, require: true,
default: () => {
console.log('fetchData func')
},
}, },
action: { action: {
type: String, type: String,

View file

@ -1,11 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue' import { ref, onMounted } from 'vue'
import { GoogleMap, Marker } from 'vue3-google-map' import { GoogleMap, Marker } from 'vue3-google-map'
import { useQuasar } from 'quasar'
const $q = useQuasar()
const googleMapsApiKey = 'AIzaSyBzPSF5NxUZ1G8DKBnJvJPTqCR0Ct2xf58'
declare var google: any declare var google: any
const center = ref<any>() const center = ref<any>()
@ -34,32 +29,11 @@ function findNearestPlace() {
}, },
(error) => { (error) => {
console.error(error) console.error(error)
// Show user-friendly error message console.log('erroe')
let errorMessage = 'ไม่สามารถระบุตำแหน่งได้'
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage = 'คุณปฏิเสธการอนุญาตให้เข้าถึงตำแหน่ง'
break
case error.POSITION_UNAVAILABLE:
errorMessage = 'ข้อมูลตำแหน่งไม่พร้อมใช้งาน'
break
case error.TIMEOUT:
errorMessage = 'หมดเวลาในการระบุตำแหน่ง'
break
}
$q.notify({
type: 'negative',
message: errorMessage,
position: 'top',
})
} }
) )
} else { } else {
$q.notify({ console.error('เบราว์เซอร์ไม่รองรับการระบุตำแหน่ง')
type: 'negative',
message: 'เบราว์เซอร์ไม่รองรับการระบุตำแหน่ง',
position: 'top',
})
} }
} }
@ -95,14 +69,6 @@ function findNearestPlaceFromAPI(userLocation: any) {
onMounted(() => { onMounted(() => {
findNearestPlace() findNearestPlace()
}) })
// Cleanup resources
onBeforeUnmount(() => {
// Clear location reference to prevent memory leaks
center.value = undefined
location.value = ''
test.value = undefined
})
</script> </script>
<template> <template>
@ -114,7 +80,7 @@ onBeforeUnmount(() => {
> >
<div style="width: 100%; height: 90%"> <div style="width: 100%; height: 90%">
<GoogleMap <GoogleMap
:api-key="googleMapsApiKey" api-key="AIzaSyBzPSF5NxUZ1G8DKBnJvJPTqCR0Ct2xf58"
style="width: 100%; height: 100%" style="width: 100%; height: 100%"
:center="center" :center="center"
:zoom="15" :zoom="15"

View file

@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, watch } from 'vue' import { ref, watch } from 'vue'
import type { PropType } from 'vue' import { PropType } from 'vue'
import type { DataCheckIn } from '@/interface/index/Main' import type { DataCheckIn } from '@/interface/index/Main'

View file

@ -4,11 +4,9 @@ import { useQuasar } from 'quasar'
import http from '@/plugins/http' import http from '@/plugins/http'
import config from '@/app.config' import config from '@/app.config'
import { usePrivacyStore } from '@/stores/privacy' import { usePrivacyStore } from '@/stores/privacy'
import { usePositionKeycloakStore } from '@/stores/positionKeycloak'
const $q = useQuasar() const $q = useQuasar()
const privacyStore = usePrivacyStore() const privacyStore = usePrivacyStore()
const positionKeycloakStore = usePositionKeycloakStore()
const modal = defineModel<boolean>('modal', { const modal = defineModel<boolean>('modal', {
required: true, required: true,
@ -80,12 +78,6 @@ const handleAccept = async () => {
accept: true, accept: true,
}) })
privacyStore.setAccepted(true) privacyStore.setAccepted(true)
// privacyCheckin positionKeycloak store
if (positionKeycloakStore.dataPositionKeycloak) {
positionKeycloakStore.dataPositionKeycloak.privacyCheckin = true
}
modal.value = false modal.value = false
} catch (error) {} } catch (error) {}
} }
@ -97,7 +89,7 @@ const toggleDetails = () => {
const checkIfScrollable = () => { const checkIfScrollable = () => {
nextTick(() => { nextTick(() => {
const container = (scrollContainer.value as any)?.$el || scrollContainer.value const container = scrollContainer.value?.$el || scrollContainer.value
if (container) { if (container) {
const { scrollHeight, clientHeight } = container const { scrollHeight, clientHeight } = container
@ -116,7 +108,6 @@ const checkIfScrollable = () => {
transition-show="slide-up" transition-show="slide-up"
transition-hide="slide-down" transition-hide="slide-down"
:maximized="$q.screen.lt.sm" :maximized="$q.screen.lt.sm"
@show="checkIfScrollable"
> >
<q-card class="privacy-card" style="max-width: 560px; max-height: 95vh"> <q-card class="privacy-card" style="max-width: 560px; max-height: 95vh">
<!-- Header --> <!-- Header -->

View file

@ -2,42 +2,42 @@
import { ref, watch } from 'vue' import { ref, watch } from 'vue'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
import { useCheckIn } from '@/stores/checkin' import { useChekIn } from '@/stores/chekin'
import type { QTableProps } from 'quasar' import { is, type QTableProps } from 'quasar'
import type { Pagination, DataCheckIn } from '@/interface/index/Main' import type { Pagination, DataCheckIn } from '@/interface/index/Main'
import Popup from '@/components/PopUp.vue' // dialog / import Popup from '@/components/PopUp.vue' // dialog /
import SkeletonTable from '@/components/SkeletonTable.vue' // skeleton table import SkeletonTable from '@/components/SkeletonTable.vue' // skeleton table
const { date2Thai } = useCounterMixin() const { date2Thai } = useCounterMixin()
const stores = useCheckIn() const stores = useChekIn()
/** props ข้อมูลจาก Components Page HistoryView */ /** props ข้อมูลจาก Components Page HistoryView */
const props = defineProps({ const props = defineProps({
paging: { paging: {
type: Boolean, type: Boolean,
default: false, defualt: false,
}, },
pageSize: { pageSize: {
type: Number, type: Number,
default: 10, defualt: 10,
}, },
page: { page: {
type: Number, type: Number,
default: 1, defualt: 1,
}, },
maxPage: { maxPage: {
type: Number, type: Number,
default: 1, defualt: 1,
}, },
total: { total: {
type: Number, type: Number,
default: 0, defualt: 0,
}, },
tab: { tab: {
type: String, type: String,
default: '', defualt: '',
required: true, required: true,
}, },
fetchData: { fetchData: {
@ -62,15 +62,15 @@ const selected = ref<string[]>([])
const columns = ref<QTableProps['columns']>( const columns = ref<QTableProps['columns']>(
props.tab == 'history' props.tab == 'history'
? [ ? [
// { {
// name: 'checkInDate', name: 'checkInDate',
// align: 'left', align: 'left',
// label: '//', label: 'วัน/เดือน/ปี',
// sortable: true, sortable: true,
// field: 'checkInDate', field: 'checkInDate',
// headerStyle: 'font-size: 14px', headerStyle: 'font-size: 14px',
// style: 'font-size: 14px; width:15%;', style: 'font-size: 14px; width:15%;',
// }, },
{ {
name: 'checkInTime', name: 'checkInTime',
align: 'left', align: 'left',
@ -79,9 +79,6 @@ const columns = ref<QTableProps['columns']>(
field: 'checkInTime', field: 'checkInTime',
headerStyle: 'font-size: 14px', headerStyle: 'font-size: 14px',
style: 'font-size: 14px; width:15%;', style: 'font-size: 14px; width:15%;',
format: (val: string, row: DataCheckIn) => {
return `${row.checkInDate} ${val} น.`
},
}, },
{ {
name: 'checkInLocation', name: 'checkInLocation',
@ -110,9 +107,7 @@ const columns = ref<QTableProps['columns']>(
headerStyle: 'font-size: 14px', headerStyle: 'font-size: 14px',
style: 'font-size: 14px; width:15%;', style: 'font-size: 14px; width:15%;',
format: (val: string, row: DataCheckIn) => { format: (val: string, row: DataCheckIn) => {
return row.checkOutStatus != '-' && val return row.checkOutStatus != '-' && val ? val : '-'
? `${row.checkOutDate} ${val} น.`
: '-'
}, },
}, },
{ {
@ -187,6 +182,7 @@ const columns = ref<QTableProps['columns']>(
) )
const visibleColumns = ref<string[]>([ const visibleColumns = ref<string[]>([
'checkInDateTime', 'checkInDateTime',
'checkInDate',
'checkInTime', 'checkInTime',
'checkInLocation', 'checkInLocation',
'checkInStatus', 'checkInStatus',
@ -258,7 +254,7 @@ function classStatus(status: string) {
case 'ปฏิบัติงานไม่ครบตามกำหนดเวลา': case 'ปฏิบัติงานไม่ครบตามกำหนดเวลา':
return 'text-orange-8' return 'text-orange-8'
default: default:
return '' break
} }
} }

View file

@ -2,14 +2,14 @@
import { onMounted, ref, watch } from 'vue' import { onMounted, ref, watch } from 'vue'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
import { useCheckIn } from '@/stores/checkin' import { useChekIn } from '@/stores/chekin'
import { calculateFiscalYear } from '@/utils/function' import { calculateFiscalYear } from '@/utils/function'
import type { DataDateMonthObject } from '@/interface/index/Main' import type { DataDateMonthObject } from '@/interface/index/Main'
import Popup from '@/components/PopUp.vue' import Popup from '@/components/PopUp.vue'
const stores = useCheckIn() const stores = useChekIn()
const { monthYear2Thai } = useCounterMixin() const { monthYear2Thai } = useCounterMixin()
/** /**
@ -18,11 +18,11 @@ const { monthYear2Thai } = useCounterMixin()
const props = defineProps({ const props = defineProps({
fetchData: { fetchData: {
type: Function, type: Function,
required: true, require: true,
}, },
tab: { tab: {
type: String, type: String,
required: true, require: true,
}, },
}) })
const emit = defineEmits(['update:year']) const emit = defineEmits(['update:year'])
@ -43,6 +43,8 @@ function filterYearFn(type: string) {
const year = type === 'year' ? filterYear.value : dateMonth.value.year const year = type === 'year' ? filterYear.value : dateMonth.value.year
const month = dateMonth.value.month const month = dateMonth.value.month
console.log(year, month)
// //
if (isNaN(Number(year)) || isNaN(Number(month))) { if (isNaN(Number(year)) || isNaN(Number(month))) {
console.warn('Invalid year or month value:', { year, month }) console.warn('Invalid year or month value:', { year, month })

View file

@ -0,0 +1,169 @@
import { ref } from 'vue'
import { useQuasar } from 'quasar'
import { useCounterMixin } from '@/stores/mixin'
export interface LocationValidationResult {
isValid: boolean
isMockDetected: boolean
confidence: 'low' | 'medium' | 'high'
warnings: string[]
errors: string[]
}
export interface PositionSnapshot {
latitude: number
longitude: number
timestamp: number
}
// Configuration constants - exported for documentation and testing purposes
export const VALIDATION_CONFIG = {
MAX_TIMESTAMP_AGE_MS: 60_000, // 60 seconds - maximum acceptable age of location data
MAX_ACCURACY_METERS: 100, // 100 meters - maximum acceptable GPS accuracy
MAX_SPEED_MS: 100, // 100 m/s (~360 km/h) - maximum plausible movement speed
POSITION_HISTORY_SIZE: 5, // number of positions to keep for pattern detection
MOCK_INDICATOR_THRESHOLD: 3, // threshold for mock detection (indicators >= 3 = mock)
} as const
export function useLocationValidation() {
const $q = useQuasar()
const { messageError } = useCounterMixin()
// Thai error messages - exported for i18n consistency
const errorMessages = {
MOCK_DETECTED: 'ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง กรุณาปิดแอปจำลองตำแหน่งและลองใหม่',
INVALID_COORDINATES: 'พิกัดตำแหน่งไม่ถูกต้อง กรุณาลองใหม่',
STALE_TIMESTAMP: 'ข้อมูลตำแหน่งเก่าเกินไป กรุณารับสัญญาณ GPS ใหม่',
POOR_ACCURACY: 'ความแม่นยำตำแหน่งต่ำเกินไป กรุณาตรวจสอบการรับสัญญาณ GPS',
IMPOSSIBLE_SPEED: 'ตรวจพบการเคลื่อนที่ด้วยความเร็วผิดปกติ อาจเป็นการจำลองตำแหน่ง',
}
const previousPositions = ref<PositionSnapshot[]>([])
// คำนวณระยะห่างระหว่าง 2 จุด (Haversine formula)
const haversineDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
const R = 6371e3 // Earth's radius in meters
const φ1 = (lat1 * Math.PI) / 180
const φ2 = (lat2 * Math.PI) / 180
const Δφ = ((lat2 - lat1) * Math.PI) / 180
const Δλ = ((lon2 - lon1) * Math.PI) / 180
const a =
Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ / 2) * Math.sin(Δλ / 2)
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return R * c
}
// ตรวจสอบพิกัดถูกต้อง
const validateCoordinates = (lat: number, lon: number): boolean => {
return (
lat >= -90 && lat <= 90 &&
lon >= -180 && lon <= 180 &&
!isNaN(lat) && !isNaN(lon) &&
!(lat === 0 && lon === 0) // Mock มักใช้ 0,0
)
}
// ตรวจสอบความแม่นยำ
const validateAccuracy = (accuracy: number | null): boolean => {
if (accuracy === null) return true
return accuracy <= VALIDATION_CONFIG.MAX_ACCURACY_METERS
}
// ตรวจสอบ Timestamp
const validateTimestamp = (timestamp: number): boolean => {
const now = Date.now()
const age = Math.abs(now - timestamp)
return age <= VALIDATION_CONFIG.MAX_TIMESTAMP_AGE_MS
}
// คำนวณความเร็ว
const calculateSpeed = (pos1: PositionSnapshot, pos2: PositionSnapshot): number => {
const distance = haversineDistance(pos1.latitude, pos1.longitude, pos2.latitude, pos2.longitude)
const timeDiff = Math.abs(pos2.timestamp - pos1.timestamp) / 1000 // seconds
return timeDiff > 0 ? distance / timeDiff : 0
}
// ตรวจสอบความเร็วปกติ
const validateSpeed = (current: PositionSnapshot, previous: PositionSnapshot): boolean => {
const speed = calculateSpeed(previous, current)
return speed <= VALIDATION_CONFIG.MAX_SPEED_MS
}
// Main validation function
const validateLocation = (position: GeolocationPosition): LocationValidationResult => {
const warnings: string[] = []
const errors: string[] = []
let mockIndicators = 0
const { latitude, longitude, accuracy } = position.coords
const { timestamp } = position
// 1. Coordinate validation
if (!validateCoordinates(latitude, longitude)) {
errors.push(errorMessages.INVALID_COORDINATES)
mockIndicators += 3
}
// 2. Timestamp validation
if (!validateTimestamp(timestamp)) {
errors.push(errorMessages.STALE_TIMESTAMP)
mockIndicators += 2
}
// 3. Accuracy validation
if (!validateAccuracy(accuracy)) {
warnings.push(errorMessages.POOR_ACCURACY)
mockIndicators += 1
}
// 4. Compare with previous positions
if (previousPositions.value.length > 0) {
const previous = previousPositions.value[previousPositions.value.length - 1]
if (!validateSpeed({ latitude, longitude, timestamp }, previous)) {
errors.push(errorMessages.IMPOSSIBLE_SPEED)
mockIndicators += 3
}
}
// Store current position
previousPositions.value.push({ latitude, longitude, timestamp })
if (previousPositions.value.length > VALIDATION_CONFIG.POSITION_HISTORY_SIZE) {
previousPositions.value.shift()
}
// Determine result
const isMockDetected = mockIndicators >= VALIDATION_CONFIG.MOCK_INDICATOR_THRESHOLD
const isValid = errors.length === 0
let confidence: 'low' | 'medium' | 'high' = 'low'
if (mockIndicators >= 5) confidence = 'high'
else if (mockIndicators >= 3) confidence = 'medium'
return {
isValid,
isMockDetected,
confidence,
warnings,
errors,
}
}
const showMockWarning = (result: LocationValidationResult) => {
if (!result.isMockDetected) return
messageError($q, null, errorMessages.MOCK_DETECTED)
}
const resetValidation = () => {
previousPositions.value = []
}
return {
validateLocation,
showMockWarning,
resetValidation,
}
}

View file

@ -1,171 +1,52 @@
import { onBeforeUnmount, ref } from 'vue' import { useQuasar } from 'quasar'
import { usePrivacyStore } from '@/stores/privacy' import { usePrivacyStore } from '@/stores/privacy'
type BrowserPermissionState = PermissionState | 'unsupported'
type PermissionQueryName = 'camera' | 'geolocation'
export function usePermissions() { export function usePermissions() {
const $q = useQuasar()
const privacyStore = usePrivacyStore() const privacyStore = usePrivacyStore()
const cameraPermissionState = ref<BrowserPermissionState>('prompt')
const locationPermissionState = ref<BrowserPermissionState>('prompt')
let cameraPermissionStatus: PermissionStatus | null = null // const checkCameraPermission = (): boolean => {
let locationPermissionStatus: PermissionStatus | null = null // if (!privacyStore.isAccepted) {
// privacyStore.modalPrivacy = true
// $q.notify({
// type: 'warning',
// message: 'กรุณายอมรับนโยบายคุ้มครองข้อมูลส่วนบุคคลก่อนใช้งานกล้อง',
// position: 'top',
// })
// return false
// }
// return true
// }
const isPermissionsApiSupported = () => // const checkLocationPermission = (): boolean => {
typeof navigator !== 'undefined' && 'permissions' in navigator // if (!privacyStore.isAccepted) {
// privacyStore.modalPrivacy = true
const setPermissionState = ( // $q.notify({
target: typeof cameraPermissionState | typeof locationPermissionState, // type: 'warning',
state: BrowserPermissionState // message: 'กรุณายอมรับนโยบายคุ้มครองข้อมูลส่วนบุคคลก่อนใช้งานแผนที่',
) => { // position: 'top',
target.value = state // })
} // return false
// }
const setPermissionChangeListener = ( // return true
name: PermissionQueryName, // }
status: PermissionStatus
) => {
status.onchange = () => {
const target =
name === 'camera' ? cameraPermissionState : locationPermissionState
setPermissionState(target, status.state)
}
}
async function queryPermissionState(name: PermissionQueryName) {
if (!isPermissionsApiSupported()) {
return null
}
try {
return await navigator.permissions.query({ name } as PermissionDescriptor)
} catch (error) {
return null
}
}
async function syncPermissionState(name: PermissionQueryName) {
const target =
name === 'camera' ? cameraPermissionState : locationPermissionState
const previousStatus =
name === 'camera' ? cameraPermissionStatus : locationPermissionStatus
if (previousStatus) {
previousStatus.onchange = null
}
const status = await queryPermissionState(name)
if (!status) {
if (target.value === 'prompt') {
setPermissionState(target, 'unsupported')
}
return
}
if (name === 'camera') {
cameraPermissionStatus = status
} else {
locationPermissionStatus = status
}
setPermissionState(target, status.state)
setPermissionChangeListener(name, status)
}
async function syncPermissionStates() {
await Promise.all([
syncPermissionState('camera'),
syncPermissionState('geolocation'),
])
}
const checkPrivacyAccepted = (): boolean => { const checkPrivacyAccepted = (): boolean => {
if (!privacyStore.isAccepted) { if (!privacyStore.isAccepted) {
privacyStore.modalPrivacy = true privacyStore.modalPrivacy = true
// $q.notify({
// type: 'warning',
// message: 'กรุณายอมรับนโยบายคุ้มครองข้อมูลส่วนบุคคลก่อนใช้งาน',
// position: 'center',
// })
return false return false
} }
return true return true
} }
async function requestCameraPermission() {
if (!checkPrivacyAccepted()) {
return false
}
if (cameraPermissionState.value === 'granted') {
return true
}
if (!navigator.mediaDevices?.getUserMedia) {
setPermissionState(cameraPermissionState, 'unsupported')
return false
}
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'user' },
audio: false,
})
stream.getTracks().forEach((track) => track.stop())
setPermissionState(cameraPermissionState, 'granted')
return true
} catch (error) {
setPermissionState(cameraPermissionState, 'denied')
return false
} finally {
await syncPermissionState('camera')
}
}
async function requestLocationPermission() {
if (!checkPrivacyAccepted()) {
return false
}
if (locationPermissionState.value === 'granted') {
return true
}
if (!navigator.geolocation) {
setPermissionState(locationPermissionState, 'unsupported')
return false
}
return new Promise<boolean>((resolve) => {
navigator.geolocation.getCurrentPosition(
async () => {
setPermissionState(locationPermissionState, 'granted')
await syncPermissionState('geolocation')
resolve(true)
},
async () => {
setPermissionState(locationPermissionState, 'denied')
await syncPermissionState('geolocation')
resolve(false)
}
)
})
}
onBeforeUnmount(() => {
if (cameraPermissionStatus) {
cameraPermissionStatus.onchange = null
}
if (locationPermissionStatus) {
locationPermissionStatus.onchange = null
}
})
return { return {
cameraPermissionState, // checkCameraPermission,
locationPermissionState, // checkLocationPermission,
checkPrivacyAccepted, checkPrivacyAccepted,
syncPermissionStates,
requestCameraPermission,
requestLocationPermission,
} }
} }

View file

@ -38,7 +38,6 @@ interface DataCheckIn {
checkInLocation: string checkInLocation: string
checkInStatus: string checkInStatus: string
checkInTime: string checkInTime: string
checkOutDate: string
checkOutLocation: string checkOutLocation: string
checkOutStatus: string checkOutStatus: string
checkOutTime: string checkOutTime: string

View file

@ -1,29 +0,0 @@
/**
* Interface for Keycloak position data from /org/profile/keycloak/position API
*/
export interface KeycloakPosition {
/** Privacy consent status */
privacyCheckin: boolean
/** Profile image filename */
avatarName?: string
/** User profile ID */
profileId: string
/** Organization hierarchy data */
organization?: Organization
}
/**
* Organization hierarchy structure
*/
export interface Organization {
/** Top level organization */
root?: string
/** Child level 1 */
child1?: string
/** Child level 2 */
child2?: string
/** Child level 3 */
child3?: string
/** Child level 4 */
child4?: string
}

View file

@ -3,7 +3,6 @@ import App from '@/App.vue'
import '@/registerServiceWorker' import '@/registerServiceWorker'
import router from '@/router' import router from '@/router'
import { createPinia } from 'pinia' import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { Quasar, Dialog, Notify, Loading } from 'quasar' import { Quasar, Dialog, Notify, Loading } from 'quasar'
import '@vuepic/vue-datepicker/dist/main.css' import '@vuepic/vue-datepicker/dist/main.css'
import quasarUserOptions from '@/quasar-user-options' import quasarUserOptions from '@/quasar-user-options'
@ -15,7 +14,6 @@ import http from '@/plugins/http'
const app = createApp(App) const app = createApp(App)
const pinia = createPinia() const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(router) app.use(router)
app.use(pinia) app.use(pinia)

View file

@ -2,7 +2,7 @@ import Axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios'
import { getToken } from './auth' import { getToken } from './auth'
const http = Axios.create({ const http = Axios.create({
timeout: 30000, // 30 seconds - reasonable timeout for API calls timeout: 1000000000, // เพิ่มค่า timeout
headers: { headers: {
'X-Requested-With': 'XMLHttpRequest', 'X-Requested-With': 'XMLHttpRequest',
}, },
@ -30,7 +30,6 @@ http.interceptors.response.use(
// eslint-disable-next-line no-prototype-builtins // eslint-disable-next-line no-prototype-builtins
if (error.hasOwnProperty('response')) { if (error.hasOwnProperty('response')) {
if (error.response.status === 401 || error.response.status === 403) { if (error.response.status === 401 || error.response.status === 403) {
// TODO: Implement proper logout logic on 401/403
// Store.commit("SET_ERROR_MESSAGE", error.response.data.message); // Store.commit("SET_ERROR_MESSAGE", error.response.data.message);
// Store.commit("REMOVE_ACCESS_TOKEN") // Store.commit("REMOVE_ACCESS_TOKEN")
} }

View file

@ -1,8 +1,6 @@
// // authen with keycloak client // // authen with keycloak client
// import Keycloak from 'keycloak-js' // import Keycloak from 'keycloak-js'
export {}
// const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY' // const ACCESS_TOKEN = 'BMAHRIS_KEYCLOAK_IDENTITY'
// const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH' // const REFRESH_TOKEN = 'BMAHRIS_KEYCLOAK_REFRESH'
// const keycloakConfig = { // const keycloakConfig = {

View file

@ -5,7 +5,6 @@ import MainView from '@/views/MainView.vue'
const loginView = () => import('@/views/login.vue') const loginView = () => import('@/views/login.vue')
const resetPasswordView = () => import('@/views/ResetPassword.vue') const resetPasswordView = () => import('@/views/ResetPassword.vue')
const noPositionView = () => import('@/views/NoPositionView.vue')
import { authenticated, logout } from '@/plugins/auth' import { authenticated, logout } from '@/plugins/auth'
@ -25,14 +24,14 @@ const router = createRouter({
Auth: true, Auth: true,
}, },
}, },
// { {
// path: '/map', path: '/map',
// name: 'map', name: 'map',
// component: MapView, component: MapView,
// meta: { meta: {
// Auth: true, Auth: true,
// }, },
// }, },
{ {
path: '/about', path: '/about',
name: 'about', name: 'about',
@ -88,63 +87,19 @@ const router = createRouter({
Auth: false, Auth: false,
}, },
}, },
{
path: '/no-position',
name: 'no-position',
component: noPositionView,
meta: {
Auth: false,
},
},
], ],
}) })
// authen with keycloak client // authen with keycloak client
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
// ตรวจสอบเส้นทางพิเศษที่ไม่ต้องตรวจสอบสิทธิ์
const publicPaths = ['/login', '/auth', '/reset-password', '/no-position']
if (publicPaths.includes(to.path)) {
next()
return
}
// ตรวจสอบการ authenticate
if (to.meta.Auth) { if (to.meta.Auth) {
const checkAuthen = await authenticated() const checkAuthen = await authenticated()
if (!checkAuthen && to.meta.Auth) { if (!checkAuthen && to.meta.Auth) {
logout() logout()
return
} }
} else {
next()
} }
// ตรวจสอบว่าผู้ใช้มีข้อมูลสังกัดหรือไม่
// ต้องทำการ dynamic import เนื่องจากเป็นการใช้งาน Pinia store ใน router
if (to.path !== '/no-position') {
try {
const { usePositionKeycloakStore } = await import('@/stores/positionKeycloak')
const positionKeycloakStore = usePositionKeycloakStore()
const dataPositionKeycloak = positionKeycloakStore.dataPositionKeycloak
// ถ้ามีข้อมูล positionKeycloak แล้ว ให้ตรวจสอบว่ามี organization หรือไม่
if (dataPositionKeycloak) {
const hasOrganization =
dataPositionKeycloak.organization &&
(dataPositionKeycloak.organization.root ||
dataPositionKeycloak.organization.child1 ||
dataPositionKeycloak.organization.child2 ||
dataPositionKeycloak.organization.child3 ||
dataPositionKeycloak.organization.child4)
if (!hasOrganization) {
next('/no-position')
return
}
}
} catch (error) {
console.error('Error checking position:', error)
}
}
next() next()
}) })

View file

@ -8,7 +8,7 @@ const mixin = useCounterMixin()
const { date2Thai } = mixin const { date2Thai } = mixin
/** store for checkin history*/ /** store for checkin history*/
export const useCheckIn = defineStore('checkin', () => { export const useChekIn = defineStore('checkin', () => {
const year = ref<number>(calculateFiscalYear(new Date())) //ปีงบประมาณ const year = ref<number>(calculateFiscalYear(new Date())) //ปีงบประมาณ
const rows = ref<Datalist[]>([]) const rows = ref<Datalist[]>([])
const tab = ref<string>('history') const tab = ref<string>('history')
@ -33,7 +33,6 @@ export const useCheckIn = defineStore('checkin', () => {
editStatus: e.editStatus != '' ? convertEditStatus(e.editStatus) : '', editStatus: e.editStatus != '' ? convertEditStatus(e.editStatus) : '',
editReason: e.editReason, editReason: e.editReason,
isEdit: e.isEdit, isEdit: e.isEdit,
checkOutDate: e.checkOutDate ? date2Thai(e.checkOutDate) : null,
})) }))
rows.value = dataList rows.value = dataList
} }

View file

@ -5,56 +5,6 @@ import { logout } from '@/plugins/auth'
import { format, utcToZonedTime } from 'date-fns-tz' import { format, utcToZonedTime } from 'date-fns-tz'
export const useCounterMixin = defineStore('mixin', () => { export const useCounterMixin = defineStore('mixin', () => {
let activeErrorDialog: any = null
const clearActiveErrorDialog = () => {
if (!activeErrorDialog) return
try {
if (typeof activeErrorDialog.hide === 'function') {
activeErrorDialog.hide()
} else if (typeof activeErrorDialog.destroy === 'function') {
activeErrorDialog.destroy()
}
} finally {
activeErrorDialog = null
}
}
const openSingleErrorDialog = (
q: any,
message: string,
onCancel?: () => void | Promise<void>
) => {
clearActiveErrorDialog()
const dialog = q.dialog({
component: CustomComponent,
componentProps: {
title: `พบข้อผิดพลาด`,
message,
icon: 'warning',
color: 'red',
onlycancel: true,
},
})
activeErrorDialog = dialog
dialog.onDismiss(() => {
if (activeErrorDialog === dialog) {
activeErrorDialog = null
}
})
if (onCancel) {
dialog.onCancel(() => {
void onCancel()
})
}
return dialog
}
function date2Thai(srcDate: Date, isFullMonth = false, isTime = false) { function date2Thai(srcDate: Date, isFullMonth = false, isTime = false) {
if (srcDate == null) { if (srcDate == null) {
return null return null
@ -183,30 +133,53 @@ export const useCounterMixin = defineStore('mixin', () => {
} }
const messageError = (q: any, e: any = '', msg: string = '') => { const messageError = (q: any, e: any = '', msg: string = '') => {
// Keep only one active warning popup to prevent dialog overlap. // q.dialog.hide();
if (e.response !== undefined) { if (e.response !== undefined) {
if (e.response.data.status !== undefined) { if (e.response.data.status !== undefined) {
if (e.response.data.status == 401) { if (e.response.data.status == 401) {
//invalid_token //invalid_token
openSingleErrorDialog( q.dialog({
q, component: CustomComponent,
'ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง', componentProps: {
async () => { title: `พบข้อผิดพลาด`,
showLoader() message: `ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง`,
await logout() icon: 'warning',
setTimeout(() => { color: 'red',
hideLoader() onlycancel: true,
}, 1000) },
} }).onCancel(async () => {
) showLoader()
await logout()
setTimeout(() => {
hideLoader()
}, 1000)
})
} else { } else {
const message = e.response.data.result ?? e.response.data.message const message = e.response.data.result ?? e.response.data.message
openSingleErrorDialog(q, `${message}`) q.dialog({
component: CustomComponent,
componentProps: {
title: `พบข้อผิดพลาด`,
message: `${message}`,
icon: 'warning',
color: 'red',
onlycancel: true,
},
})
} }
} else { } else {
if (e.response.status == 401) { if (e.response.status == 401) {
if (msg !== '') { if (msg !== '') {
openSingleErrorDialog(q, msg, async () => { q.dialog({
component: CustomComponent,
componentProps: {
title: `พบข้อผิดพลาด`,
message: msg,
icon: 'warning',
color: 'red',
onlycancel: true,
},
}).onCancel(async () => {
showLoader() showLoader()
await logout() await logout()
setTimeout(() => { setTimeout(() => {
@ -215,35 +188,70 @@ export const useCounterMixin = defineStore('mixin', () => {
}) })
} else { } else {
//invalid_token //invalid_token
openSingleErrorDialog( q.dialog({
q, component: CustomComponent,
'ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง', componentProps: {
async () => { title: `พบข้อผิดพลาด`,
showLoader() message: `ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง`,
await logout() icon: 'warning',
setTimeout(() => { color: 'red',
hideLoader() onlycancel: true,
}, 1000) },
} }).onCancel(async () => {
) showLoader()
await logout()
setTimeout(() => {
hideLoader()
}, 1000)
})
} }
} else if (e.response.data.successful === false) { } else if (e.response.data.successful === false) {
openSingleErrorDialog(q, e.response.data.message) q.dialog({
component: CustomComponent,
componentProps: {
title: `พบข้อผิดพลาด`,
message: e.response.data.message,
icon: 'warning',
color: 'red',
onlycancel: true,
},
})
} else { } else {
openSingleErrorDialog( q.dialog({
q, component: CustomComponent,
'ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์' componentProps: {
) title: `พบข้อผิดพลาด`,
message: `ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์`,
icon: 'warning',
color: 'red',
onlycancel: true,
},
})
} }
} }
} else { } else {
if (msg !== '') { if (msg !== '') {
return openSingleErrorDialog(q, msg) return q.dialog({
component: CustomComponent,
componentProps: {
title: `พบข้อผิดพลาด`,
message: msg,
icon: 'warning',
color: 'red',
onlycancel: true,
},
})
} }
openSingleErrorDialog( q.dialog({
q, component: CustomComponent,
'ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์' componentProps: {
) title: `พบข้อผิดพลาด`,
message: `ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์`,
icon: 'warning',
color: 'red',
onlycancel: true,
},
})
} }
} }

View file

@ -1,78 +1,65 @@
import { ref } from 'vue' import { ref } from 'vue'
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import type { KeycloakPosition } from '@/interface/keycloak-position'
export const usePositionKeycloakStore = defineStore( export const usePositionKeycloakStore = defineStore('positionKeycloak', () => {
'positionKeycloak', const menuData = ref<string[]>([
() => { 'ลงเวลาปฏิบัติงาน',
const menuData = ref<string[]>([ 'ประวัติการลงเวลา',
'ลงเวลาปฏิบัติงาน', 'รายการลงเวลากรณีพิเศษ',
'ประวัติการลงเวลา', ])
'รายการลงเวลากรณีพิเศษ', const dataPositionKeycloak = ref<any>(null)
])
const dataPositionKeycloak = ref<KeycloakPosition | null>(null)
const profileImg = ref<string>('')
function setPositionKeycloak(data: KeycloakPosition) { function setPositionKeycloak(data: any) {
dataPositionKeycloak.value = data dataPositionKeycloak.value = data
}
/**
*
* @param url URL
*/
function setProfileImg(url: string) {
profileImg.value = url
}
/**
* Keycloak position ( logout)
*/
function clearPositionKeycloak() {
dataPositionKeycloak.value = null
profileImg.value = ''
// ลบ localStorage ด้วยเพื่อให้แน่ใจว่าข้อมูลหายจริง
localStorage.removeItem('positionKeycloak')
}
/**
*
* @param obj child4 -> child3 -> child2 -> child1 -> root
* @returns string /
*/
function findOrgName(obj: KeycloakPosition | null): string {
if (!obj?.organization) {
return ''
}
const org = obj.organization
const levels = ['child4', 'child3', 'child2', 'child1', 'root'] as const
const parts: string[] = []
for (const level of levels) {
const value = org[level]
if (value) {
parts.push(value)
}
}
return parts.length > 0 ? parts.join('/') : '-'
}
return {
setPositionKeycloak,
clearPositionKeycloak,
setProfileImg,
dataPositionKeycloak,
profileImg,
findOrgName,
menuData,
}
},
{
persist: {
key: 'positionKeycloak',
storage: localStorage, // ใช้ localStorage เพื่อให้ข้อมูลอยู่ถาวร
},
} }
)
function findOrgName(obj: any) {
if (obj) {
let name =
obj.child4 != null &&
obj.child4 !== '' &&
obj.child3 != null &&
obj.child3 !== ''
? obj.child4 + (obj.child3 ? '/' : '')
: obj.child4 != null && obj.child4 !== ''
? obj.child4
: ''
name +=
obj.child3 != null &&
obj.child3 !== '' &&
obj.child2 != null &&
obj.child2 !== ''
? obj.child3 + (obj.child2 ? '/' : '')
: obj.child3 != null && obj.child3 !== ''
? obj.child3
: ''
name +=
obj.child2 != null &&
obj.child2 !== '' &&
obj.child1 != null &&
obj.child1 !== ''
? obj.child2 + (obj.child1 ? '/' : '')
: obj.child2 != null && obj.child2 !== ''
? obj.child2
: ''
name +=
obj.child1 != null &&
obj.child1 !== '' &&
obj.root != null &&
obj.root !== ''
? obj.child1 + (obj.root ? '/' : '')
: obj.child1 != null && obj.child1 !== ''
? obj.child1
: ''
name += obj.root != null && obj.root !== '' ? obj.root : ''
return name == '' ? '-' : name
} else {
return ''
}
}
return { setPositionKeycloak, dataPositionKeycloak, findOrgName, menuData }
})

View file

@ -5,7 +5,7 @@ import { useQuasar } from 'quasar'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import http from '@/plugins/http' import http from '@/plugins/http'
import config from '@/app.config' import config from '@/app.config'
import { useCheckIn } from '@/stores/checkin' import { useChekIn } from '@/stores/chekin'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
import { calculateFiscalYear } from '@/utils/function' import { calculateFiscalYear } from '@/utils/function'
@ -14,7 +14,7 @@ import ToolBar from '@/components/ToolBar.vue' // เมนู Herder
const $q = useQuasar() // noti quasar const $q = useQuasar() // noti quasar
const router = useRouter() const router = useRouter()
const stores = useCheckIn() const stores = useChekIn()
const { showLoader, hideLoader, messageError } = useCounterMixin() const { showLoader, hideLoader, messageError } = useCounterMixin()
const { fetchHistoryList } = stores const { fetchHistoryList } = stores
@ -195,7 +195,7 @@ watch(
:tab="stores.tab" :tab="stores.tab"
/> />
<TableHistory <TableHistory
:fetch-data="functionFetch" :fetchData="functionFetch"
:page-size="pageSize" :page-size="pageSize"
:total="total" :total="total"
:page="page" :page="page"

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, computed, onMounted } from 'vue' import { ref, onMounted } from 'vue'
import { useQuasar } from 'quasar' import { useQuasar } from 'quasar'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
@ -10,7 +10,6 @@ import { logout, tokenParsed, getCookie, gotoLeavePage } from '@/plugins/auth'
import { useCounterMixin } from '@/stores/mixin' import { useCounterMixin } from '@/stores/mixin'
import { usePrivacyStore } from '@/stores/privacy' import { usePrivacyStore } from '@/stores/privacy'
import { usePositionKeycloakStore } from '@/stores/positionKeycloak' import { usePositionKeycloakStore } from '@/stores/positionKeycloak'
import type { KeycloakPosition } from '@/interface/keycloak-position'
// import type { notiType } from '@/interface/index/Main' // import type { notiType } from '@/interface/index/Main'
// import type { Noti } from '@/interface/response/Main' // import type { Noti } from '@/interface/response/Main'
@ -145,8 +144,6 @@ function onClickLogout() {
ok: 'ยืนยัน', ok: 'ยืนยัน',
persistent: true, persistent: true,
}).onOk(async () => { }).onOk(async () => {
// positionKeycloak logout
positionKeycloakStore.clearPositionKeycloak()
await http.post(config.API.keycloakLogSSO, { text: 'ออกจากระบบ' }) await http.post(config.API.keycloakLogSSO, { text: 'ออกจากระบบ' })
await logout() await logout()
}) })
@ -177,80 +174,18 @@ const landingPageUrl = ref<string>(configParam.landingPageUrl)
/** ฟังก์ชันเรียกข้อมูลผู้ใช่งาน*/ /** ฟังก์ชันเรียกข้อมูลผู้ใช่งาน*/
async function fetchKeycloakPosition() { async function fetchKeycloakPosition() {
// store ( localStorage)
const existingData = positionKeycloakStore.dataPositionKeycloak
if (existingData) {
//
// (organization)
const hasOrganization =
existingData.organization &&
(existingData.organization.root ||
existingData.organization.child1 ||
existingData.organization.child2 ||
existingData.organization.child3 ||
existingData.organization.child4)
if (!hasOrganization) {
// redirect NoPosition
router.replace('/no-position')
return
}
privacyStore.modalPrivacy = !existingData.privacyCheckin
privacyStore.setAccepted(existingData.privacyCheckin)
return
}
// fetch API
await http await http
.get(config.API.keycloakPosition()) .get(config.API.keycloakPosition())
.then(async (res) => { .then(async (res) => {
const apiData = await res.data.result const data = await res.data.result
positionKeycloakStore.setPositionKeycloak(data)
// Map API response to KeycloakPosition interface privacyStore.modalPrivacy = !data.privacyCheckin ? true : false
const keycloakData: KeycloakPosition = { privacyStore.setAccepted(data.privacyCheckin)
privacyCheckin: apiData.privacyCheckin ?? false,
avatarName: apiData.avatarName,
profileId: apiData.profileId,
organization: {
root: apiData.root,
child1: apiData.child1,
child2: apiData.child2,
child3: apiData.child3,
child4: apiData.child4,
},
}
// (organization)
// redirect NoPosition
const hasOrganization =
keycloakData.organization &&
(keycloakData.organization.root ||
keycloakData.organization.child1 ||
keycloakData.organization.child2 ||
keycloakData.organization.child3 ||
keycloakData.organization.child4)
if (!hasOrganization) {
// ()
positionKeycloakStore.setPositionKeycloak(keycloakData)
// Redirect NoPosition
router.replace('/no-position')
return
}
positionKeycloakStore.setPositionKeycloak(keycloakData)
privacyStore.modalPrivacy = !keycloakData.privacyCheckin
privacyStore.setAccepted(keycloakData.privacyCheckin)
// //
if (keycloakData.avatarName) { if (data.avatarName) {
getImg(keycloakData.profileId, keycloakData.avatarName) getImg(data.profileId, data.avatarName)
} else { } else {
positionKeycloakStore.setProfileImg(avatar) profileImg.value = avatar
} }
}) })
.catch((err) => { .catch((err) => {
@ -258,15 +193,12 @@ async function fetchKeycloakPosition() {
}) })
} }
const profileImg = computed({ const profileImg = ref<string>('')
get: () => positionKeycloakStore.profileImg,
set: (value) => positionKeycloakStore.setProfileImg(value),
})
function getImg(id: string, pathName: string) { function getImg(id: string, pathName: string) {
http http
.get(config.API.fileByFile('ทะเบียนประวัติ', 'โปรไฟล์', id, pathName)) .get(config.API.fileByFile('ทะเบียนประวัติ', 'โปรไฟล์', id, pathName))
.then((res) => { .then((res) => {
positionKeycloakStore.setProfileImg(res.data.downloadUrl) profileImg.value = res.data.downloadUrl
}) })
} }
@ -365,7 +297,6 @@ onMounted(async () => {
const checkTokenParsed = await tokenParsed() const checkTokenParsed = await tokenParsed()
const SSO_TOKEN = await getCookie('SSO') const SSO_TOKEN = await getCookie('SSO')
isSsoToken.value = SSO_TOKEN === 'y' ? true : false isSsoToken.value = SSO_TOKEN === 'y' ? true : false
if (checkTokenParsed != null) { if (checkTokenParsed != null) {
fullName.value = checkTokenParsed.name fullName.value = checkTokenParsed.name
} }
@ -633,10 +564,7 @@ onMounted(async () => {
</q-page-container> </q-page-container>
<!-- Footer --> <!-- Footer -->
<q-footer <q-footer class="bg-grey-1 text-dark q-pa-md">
class="bg-grey-1 text-dark q-pa-md"
:class="$q.screen.xs ? 'hidden' : ''"
>
<footer-contact /> <footer-contact />
</q-footer> </q-footer>
</q-layout> </q-layout>
@ -792,8 +720,4 @@ onMounted(async () => {
background-color: #016987; background-color: #016987;
color: #fff; color: #fff;
} }
.hidden {
display: none !important;
}
</style> </style>

View file

@ -133,19 +133,14 @@ const photoHeight = ref<number>(350)
/** function เปิดกล้อง */ /** function เปิดกล้อง */
async function openCamera() { async function openCamera() {
try { // change camera device
// change camera device if (cameraIsOn.value) {
if (cameraIsOn.value) { camera.value?.stop()
camera.value?.stop() } else {
} else { await camera.value?.start()
await camera.value?.start() changeCamera()
changeCamera()
}
cameraIsOn.value = !cameraIsOn.value
} catch (error) {
console.error('Error opening camera:', error)
messageError($q, error, 'ไม่สามารถเปิดกล้องได้ กรุณาลองใหม่อีกครั้ง')
} }
cameraIsOn.value = !cameraIsOn.value
} }
/** change camera device */ /** change camera device */
@ -157,49 +152,25 @@ async function changeCamera() {
/** function ถ่ายรูป*/ /** function ถ่ายรูป*/
async function capturePhoto() { async function capturePhoto() {
try { const imageBlob: any = await camera.value?.snapshot(
const imageBlob: any = await camera.value?.snapshot( { width: photoWidth.value, height: photoHeight.value },
{ width: photoWidth.value, height: photoHeight.value }, 'image/png',
'image/jpeg', 0.5
0.8 )
) const fileName = 'photo.png'
if (!imageBlob) { //
messageError($q, '', 'ไม่สามารถถ่ายรูปได้ กรุณาลองใหม่อีกครั้ง') const file = new File([imageBlob], fileName, { type: 'image/png' })
return fileImg.value = file
} //
const fileName = `photo_${Date.now()}.jpg` camera.value?.stop()
// const url = URL.createObjectURL(imageBlob)
const file = new File([imageBlob], fileName, { type: 'image/jpeg' }) img.value = url
fileImg.value = file
// URL ( memory leak)
if (img.value) {
URL.revokeObjectURL(img.value)
}
//
camera.value?.stop()
const url = URL.createObjectURL(imageBlob)
img.value = url
} catch (error) {
console.error('Error capturing photo:', error)
messageError($q, error, 'ไม่สามารถถ่ายรูปได้ กรุณาลองใหม่อีกครั้ง')
}
} }
/** function เปลี่ยนรูปภาพ*/ /** function เปลี่ยนรูปภาพ*/
async function refreshPhoto() { function refreshPhoto() {
try { img.value = undefined
// URL ( memory leak) camera.value?.start()
if (img.value) {
URL.revokeObjectURL(img.value)
img.value = undefined
}
await camera.value?.start()
} catch (error) {
console.error('Error refreshing photo:', error)
messageError($q, error, 'ไม่สามารถเปิดกล้องได้ กรุณาลองใหม่อีกครั้ง')
}
} }
/** ref validate*/ /** ref validate*/
@ -364,8 +335,7 @@ onMounted(async () => {
:resolution="{ width: photoWidth, height: photoHeight }" :resolution="{ width: photoWidth, height: photoHeight }"
ref="camera" ref="camera"
:autoplay="false" :autoplay="false"
:playsinline="true" :style="!img ? 'display: block' : 'display: none'"
:facingMode="'user'"
/> />
<!-- แสดงรปเมอกด capture --> <!-- แสดงรปเมอกด capture -->
@ -490,7 +460,7 @@ onMounted(async () => {
<div class="col-12 text-right"> <div class="col-12 text-right">
<q-separator /> <q-separator />
<div class="col-12 q-pa-md"> <div class="col-12 q-pa-md">
<!-- <p <p
:class=" :class="
$q.screen.gt.xs $q.screen.gt.xs
? 'text-red text-caption ' ? 'text-red text-caption '
@ -498,7 +468,7 @@ onMounted(async () => {
" "
> >
*หมายเหต คลกลงเวลาเขางานแลวระบบจะลงเวลาทนท *หมายเหต คลกลงเวลาเขางานแลวระบบจะลงเวลาทนท
</p> --> </p>
<q-btn <q-btn
:label=" :label="
stetusCheckin == true ? 'ลงเวลาเข้างาน' : 'ลงเวลาออกงาน' stetusCheckin == true ? 'ลงเวลาเข้างาน' : 'ลงเวลาออกงาน'
@ -599,12 +569,4 @@ onMounted(async () => {
width: 100%; width: 100%;
height: 100%; height: 100%;
} }
/* iOS-specific video fixes */
.card-container video {
width: 100%;
height: 100%;
object-fit: cover;
-webkit-object-fit: cover;
}
</style> </style>

View file

@ -1,106 +0,0 @@
<script setup lang="ts">
import { useQuasar } from 'quasar'
import { useRouter } from 'vue-router'
import { useCounterMixin } from '@/stores/mixin'
import { usePositionKeycloakStore } from '@/stores/positionKeycloak'
import { logout } from '@/plugins/auth'
import CustomComponent from '@/components/CustomDialog.vue'
const $q = useQuasar()
const router = useRouter()
const mixin = useCounterMixin()
const positionKeycloakStore = usePositionKeycloakStore()
const { showLoader, hideLoader } = mixin
/**
* งกนจดการเมอผใชกดปมตกลง
* ดำเนนการ logout โดยตรง
*/
function handleOkClick() {
performLogout()
}
/**
* งกนดำเนนการออกจากระบบ
*/
async function performLogout() {
showLoader()
try {
// positionKeycloak logout
positionKeycloakStore.clearPositionKeycloak()
await logout()
} catch (error) {
console.error('Logout error:', error)
} finally {
setTimeout(() => {
hideLoader()
}, 1000)
}
}
</script>
<template>
<div
class="fullscreen bg-secondary text-white text-center q-pa-sm flex flex-center"
>
<div class="no-position-container">
<!-- Icon แสดงความผดปกต -->
<div class="icon-container">
<q-icon name="mdi-account-off-outline" size="100px" color="white" />
</div>
<!-- วขอหล -->
<div class="text-h4 q-mt-lg q-mb-md">ไมพบขอมลสงก</div>
<!-- รายละเอยด -->
<div class="text-h6 q-mb-lg text-weight-regular">
านยงไมงกดในโครงสรางองคกร<br />
กรณาตดตอเจาหนาทเบอร 1171
<br />เพอดำเนนการเพมขอม
</div>
<div class="text-weight-regular">
เมอเจาหนาทไดเพมทานในโครงสรางองคกรเรยบรอยแล
กรณาเขาสระบบใหมกคร
</div>
<!-- มตกลง -->
<q-btn
class="q-mt-xl"
color="white"
text-color="secondary"
unelevated
label="ตกลง"
no-caps
size="lg"
padding="md xl"
@click="handleOkClick"
/>
</div>
</div>
</template>
<style lang="scss" scoped>
.no-position-container {
max-width: 600px;
padding: 2rem;
}
.icon-container {
opacity: 0.9;
}
.text-h4 {
font-weight: 700;
}
.text-h6 {
line-height: 1.8;
opacity: 0.95;
}
.q-btn {
border-radius: 8px;
font-weight: 600;
min-width: 150px;
}
</style>

View file

@ -20,7 +20,7 @@ const password = ref<string>('')
async function onSubmit() { async function onSubmit() {
showLoader() showLoader()
const formdata = new URLSearchParams() const formdata = new URLSearchParams()
formdata.append('username', username.value.trim()) formdata.append('username', username.value)
formdata.append('password', password.value) formdata.append('password', password.value)
await axios await axios

View file

@ -1,26 +0,0 @@
import { enableAutoUnmount, flushPromises, VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia } from 'pinia'
/**
* Helper function to setup test environment with Pinia
*/
export function setupTest() {
const pinia = createPinia()
setActivePinia(pinia)
return pinia
}
/**
* Helper to flush all pending promises
*/
export async function flushAllPromises() {
await flushPromises()
await new Promise((resolve) => setTimeout(resolve, 0))
}
/**
* Helper to cleanup after each test
*/
export function teardownTest() {
vi.clearAllMocks()
}

View file

@ -23,7 +23,7 @@ export default defineConfig({
cleanupOutdatedCaches: true, cleanupOutdatedCaches: true,
globPatterns: ['**/*.*'], globPatterns: ['**/*.*'],
}, },
includeAssets: ['icons/safari-pinned-tab.svg', 'src/assets/markers/*.svg'], includeAssets: ['icons/safari-pinned-tab.svg'],
manifest: { manifest: {
name: 'HRMS-Checkin', name: 'HRMS-Checkin',
short_name: 'HRMS Checkin', short_name: 'HRMS Checkin',