diff --git a/.claude/agent-memory/hrms-checkin-expert/MEMORY.md b/.claude/agent-memory/hrms-checkin-expert/MEMORY.md index 7897460..bb4f782 100644 --- a/.claude/agent-memory/hrms-checkin-expert/MEMORY.md +++ b/.claude/agent-memory/hrms-checkin-expert/MEMORY.md @@ -7,3 +7,8 @@ ## 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 diff --git a/.claude/agent-memory/hrms-checkin-expert/issue_front_camera_preview_alignment.md b/.claude/agent-memory/hrms-checkin-expert/issue_front_camera_preview_alignment.md new file mode 100644 index 0000000..f78b23d --- /dev/null +++ b/.claude/agent-memory/hrms-checkin-expert/issue_front_camera_preview_alignment.md @@ -0,0 +1,11 @@ +--- +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`. diff --git a/.claude/agent-memory/hrms-checkin-expert/issue_ios16_inline_camera_white_preview.md b/.claude/agent-memory/hrms-checkin-expert/issue_ios16_inline_camera_white_preview.md new file mode 100644 index 0000000..791f98e --- /dev/null +++ b/.claude/agent-memory/hrms-checkin-expert/issue_ios16_inline_camera_white_preview.md @@ -0,0 +1,11 @@ +--- +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. diff --git a/.claude/agent-memory/hrms-checkin-expert/issue_ios_native_camera_popup_control.md b/.claude/agent-memory/hrms-checkin-expert/issue_ios_native_camera_popup_control.md new file mode 100644 index 0000000..22792d0 --- /dev/null +++ b/.claude/agent-memory/hrms-checkin-expert/issue_ios_native_camera_popup_control.md @@ -0,0 +1,11 @@ +--- +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 `` 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. diff --git a/.claude/agent-memory/hrms-checkin-expert/issue_ios_native_photo_mirroring.md b/.claude/agent-memory/hrms-checkin-expert/issue_ios_native_photo_mirroring.md new file mode 100644 index 0000000..77f33ef --- /dev/null +++ b/.claude/agent-memory/hrms-checkin-expert/issue_ios_native_photo_mirroring.md @@ -0,0 +1,11 @@ +--- +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. diff --git a/.claude/agent-memory/hrms-checkin-expert/project_active_camera_scope.md b/.claude/agent-memory/hrms-checkin-expert/project_active_camera_scope.md new file mode 100644 index 0000000..a10c142 --- /dev/null +++ b/.claude/agent-memory/hrms-checkin-expert/project_active_camera_scope.md @@ -0,0 +1,11 @@ +--- +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`. diff --git a/package.json b/package.json index c36ed30..503f2f9 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "quasar": "^2.11.1", "register-service-worker": "^1.7.2", "simple-vue-camera": "^1.1.3", + "socket.io-client": "^4.8.3", "vite-plugin-pwa": "^0.16.7", "vue": "^3.4.15", "vue-router": "^4.1.6", diff --git a/src/App.vue b/src/App.vue index ea76d33..ed177ca 100644 --- a/src/App.vue +++ b/src/App.vue @@ -1,5 +1,64 @@ + + diff --git a/src/api/socket.ts b/src/api/socket.ts new file mode 100644 index 0000000..b018666 --- /dev/null +++ b/src/api/socket.ts @@ -0,0 +1,7 @@ +import env from "./index"; + +const socket = `${env.API_URI}/org-socket`; + +export default { + socket, +}; diff --git a/src/app.config.ts b/src/app.config.ts index c6dbe0c..085d287 100644 --- a/src/app.config.ts +++ b/src/app.config.ts @@ -4,6 +4,7 @@ import leave from '@/api/api.checkin' import history from '@/api/api.history' import message from '@/api/api.message' +import socket from '@/api/socket' const API = { /**leave */ @@ -12,6 +13,7 @@ const API = { ...history, /**message */ ...message, + ...socket, } export default { diff --git a/src/components/AscGISMap.vue b/src/components/AscGISMap.vue index ec1eb0b..bfe0e9c 100644 --- a/src/components/AscGISMap.vue +++ b/src/components/AscGISMap.vue @@ -163,8 +163,19 @@ function reattachAndResizeMap(retry = 0) { mapView.value.container = activeContainer } - mapView.value.resize() - mapView.value.requestRender?.() + // เรียก resize() อย่างปลอดภัยด้วยการตรวจสอบว่ามี method นี้หรือไม่ + try { + if (typeof mapView.value.resize === 'function') { + mapView.value.resize() + } + } catch (error) { + console.warn('Map resize failed:', error) + } + + if (typeof mapView.value.requestRender === 'function') { + mapView.value.requestRender?.() + } + mapView.value .goTo( { @@ -285,7 +296,11 @@ async function initializeMap() { geometry: userPoint, symbol: userSymbol, }) - mapView.value.graphics.add(userGraphic) + + // เพิ่มการตรวจสอบความปลอดภัยก่อนเข้าถึง graphics + if (mapView.value && mapView.value.graphics && !mapView.value.destroyed) { + mapView.value.graphics.add(userGraphic) + } // Get POI place ยิงไปขอที่ server ของกทม.ก่อน // await axios // .get( @@ -381,12 +396,22 @@ async function initializeMap() { geometry: poiPoint, symbol: poiSymbol, }) - mapView.value.graphics.add(poiGraphic) - // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI - mapView.value.goTo({ - target: [userPoint, poiPoint], - zoom: zoomMap.value, - }) + + // เพิ่มการตรวจสอบความปลอดภัยก่อนเข้าถึง graphics และ goTo + if (mapView.value && !mapView.value.destroyed) { + if (mapView.value.graphics) { + mapView.value.graphics.add(poiGraphic) + } + // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI + if (typeof mapView.value.goTo === 'function') { + mapView.value.goTo({ + target: [userPoint, poiPoint], + zoom: zoomMap.value, + }).catch(() => { + // Ignore goTo errors + }) + } + } updateLocation(latitude, longitude, poiPlaceName.value) }) diff --git a/src/components/PopupPrivacy.vue b/src/components/PopupPrivacy.vue index 1bd816b..739d65f 100644 --- a/src/components/PopupPrivacy.vue +++ b/src/components/PopupPrivacy.vue @@ -16,41 +16,26 @@ const modal = defineModel('modal', { // Privacy content data const privacyContent = { - title: 'การคุ้มครองข้อมูลส่วนบุคคล', + title: 'ประกาศความเป็นส่วนตัว', mainText: - 'ระบบนี้มีการเก็บ และใช้ภาพถ่ายของท่าน เพื่อยืนยันตัวตนในการลงเวลาปฏิบัติราชการ ข้อมูลจะถูกใช้เฉพาะตามวัตถุประสงค์ของระบบ และจัดเก็บอย่างปลอดภัยตามกฎหมายคุ้มครองข้อมูลส่วนบุคคล (PDPA)', + 'ประกาศความเป็นส่วนตัวสำหรับการลงเวลาปฏิบัติราชการผ่านระบบอิเล็กทรอนิกส์ในระบบริหารทรัพยากรบุคคลของกรุงเทพมหานคร (BMA – HRMS)', warningText: '* หากท่านไม่กดยอมรับ อาจทำให้ไม่สามารถใช้งานระบบได้', detailIntro: - 'ข้าพเจ้าตกลงให้กรุงเทพมหานครเก็บ ใช้ และประมวลผลข้อมูลส่วนบุคคลประเภทภาพถ่ายของข้าพเจ้า ซึ่งได้มาจากการใช้งานระบบลงเวลาปฏิบัติราชการอิเล็กทรอนิกส์ ของระบบบริหารทรัพยากรบุคคลของกรุงเทพมหานคร (BMA - HRMS) ทั้งนี้ เพื่อวัตถุประสงค์ดังต่อไปนี้', - purposes: { - title: 'วัตถุประสงค์การใช้ข้อมูล', - items: [ - 'เพื่อยืนยันตัวตนของผู้ปฏิบัติงานในการบันทึกเวลาเข้า-ออกการปฏิบัติราชการ', - 'เพื่อใช้เป็นหลักฐานประกอบการบริหารงานด้านทรัพยากรบุคคล การจ่ายค่าตอบแทน และการกำกับ ดูแลการปฏิบัติราชการ', - 'เพื่อรักษาความถูกต้อง โปร่งใส และป้องกันการทุจริตในการบันทึกเวลาการปฏิบัติงาน', - ], - }, - understanding: { - items: [ - 'การเก็บ ใช้ และประมวลผลข้อมูลส่วนบุคคลดังกล่าว จะดำเนินการ เท่าที่จำเป็นตามวัตถุประสงค์ที่ระบุไว้เท่านั้น', - 'หน่วยงานจะจัดให้มีมาตรการรักษาความมั่นคงปลอดภัยของข้อมูลส่วนบุคคล ตามที่กฎหมายกำหนด', - 'ข้อมูลส่วนบุคคลของข้าพเจ้าจะถูกเก็บรักษา ตามระยะเวลาที่จำเป็น ต่อการปฏิบัติงานหรือเป็นไปตามที่กฎหมายกำหนด', - ], - }, - rights: { - title: - 'ข้าพเจ้าทราบถึง สิทธิของเจ้าของข้อมูลส่วนบุคคล ตามพระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. ๒๕๖๒ ได้แก่', - items: [ - 'สิทธิขอเข้าถึงและขอรับสำเนาข้อมูล', - 'สิทธิขอแก้ไขข้อมูลให้ถูกต้อง', - 'สิทธิขอถอนความยินยอม (ทั้งนี้ การถอนความยินยอมอาจส่งผลต่อการใช้งานระบบลงเวลาการปฏิบัติราชการ)', - 'สิทธิร้องเรียนต่อคณะกรรมการคุ้มครองข้อมูลส่วนบุคคล', - ], - }, + 'กรุงเทพมหานครเก็บรวบรวมและใช้ข้อมูลส่วนบุคคลของท่าน ได้แก่ ข้อมูลวันและเวลาลงเวลาปฏิบัติราชการ พิกัดสถานที่ ณ ขณะลงเวลา ภาพถ่าย ณ ขณะลงเวลา ข้อมูลหน่วยงานหรือสถานที่ปฏิบัติงาน และข้อมูลทางเทคนิคที่จำเป็นต่อการใช้งานระบบ เพื่อวัตถุประสงค์ในการยืนยันการมาปฏิบัติราชการ ป้องกันการลงเวลาแทนกัน ตรวจสอบความถูกต้องของข้อมูล บริหารวันและเวลาปฏิบัติราชการ การลา การประเมินผลการปฏิบัติราชการ การพิจารณาเลื่อนเงินเดือน ตลอดจนการบริหารทรัพยากรบุคคลตามกฎหมาย กฎ ระเบียบ และหลักเกณฑ์ที่เกี่ยวข้อง', + + paragraphs: [ + 'การเก็บรวบรวมและใช้ข้อมูลดังกล่าวเป็นการดำเนินการโดยอาศัยฐานการปฏิบัติหน้าที่ในการดำเนินภารกิจเพื่อประโยชน์สาธารณะหรือการใช้อำนาจรัฐตามมาตรา 24 (4) และฐานการปฏิบัติตามกฎหมายของ ผู้ควบคุมข้อมูลส่วนบุคคลตามมาตรา 24 (6) แห่งพระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. 2562 โดยมิได้อาศัยความยินยอมของเจ้าของข้อมูลส่วนบุคคล', + 'ระบบจะเข้าถึงข้อมูลพิกัดและกล้องถ่ายภาพเฉพาะในขณะที่ท่านดำเนินการลงเวลาเข้าและออกจากการปฏิบัติราชการเท่านั้น โดยไม่มีการติดตามหรือบันทึกพิกัดของท่านอย่างต่อเนื่องภายหลังจากการลงเวลาเสร็จสิ้น', + 'กรุงเทพมหานครจะเก็บรักษาข้อมูลภาพถ่าย พิกัด ณ ขณะลงเวลา และข้อมูลรายละเอียดการลงเวลาไว้ตามรอบการประเมินผลการปฏิบัติราชการเป็นระยะเวลาไม่เกิน 6 เดือนนับแต่วันที่เก็บรวบรวม หรือจนกว่าการตรวจสอบข้อมูลในรอบการประเมินนั้นจะแล้วเสร็จ แล้วแต่ระยะเวลาใดจะยาวกว่า เมื่อครบกำหนด กรุงเทพมหานครจะลบ ทำลาย หรือทำให้ข้อมูลดังกล่าวไม่สามารถระบุตัวบุคคลได้ตามวิธีการและมาตรการรักษาความมั่นคงปลอดภัยที่กำหนด', + 'กรณีข้อมูลดังกล่าวเกี่ยวข้องกับการร้องเรียน การโต้แย้ง การตรวจสอบ การดำเนินการทางวินัยการอุทธรณ์ การดำเนินคดี หรือการใช้สิทธิเรียกร้องตามกฎหมาย กรุงเทพมหานครอาจเก็บรักษาข้อมูลไว้เกินกว่า 6 เดือนได้เท่าที่จำเป็น จนกว่ากระบวนการดังกล่าวจะถึงที่สุดหรือพ้นระยะเวลาที่กฎหมายกำหนด', + 'ทั้งนี้ ข้อมูลสรุปเกี่ยวกับวันเวลาปฏิบัติราชการ การลา การมาสาย การขาดราชการ ผลการประเมินผลการปฏิบัติราชการ และผลการพิจารณาเลื่อนเงินเดือน ซึ่งเป็นส่วนหนึ่งของทะเบียนประวัติหรือเอกสารด้านการบริหารทรัพยากรบุคคล อาจได้รับการเก็บรักษาตามระยะเวลาที่กฎหมาย ระเบียบ หลักเกณฑ์งานบุคคล และระเบียบงานสารบรรณกำหนด ซึ่งอาจมีระยะเวลาแตกต่างจากข้อมูลภาพถ่ายและพิกัดที่ใช้ประกอบการลงเวลา', + 'กรุงเทพมหานครจะจำกัดการเข้าถึงข้อมูลเฉพาะเจ้าหน้าที่หรือผู้ปฏิบัติงานที่มีหน้าที่เกี่ยวข้อง และจะไม่นำข้อมูลไปใช้หรือเปิดเผยเพื่อวัตถุประสงค์อื่นที่ไม่สอดคล้องกับวัตถุประสงค์ที่ได้แจ้งไว้ เว้นแต่เป็นกรณีที่กฎหมายกำหนดหรืออนุญาตให้ดำเนินการได้', + 'ท่านมีสิทธิขอเข้าถึง ขอรับสำเนา ขอแก้ไข ขอคัดค้าน ขอระงับการใช้ หรือขอให้ลบข้อมูลส่วนบุคคลของท่านได้ตามหลักเกณฑ์และเงื่อนไขที่พระราชบัญญัติคุ้มครองข้อมูลส่วนบุคคล พ.ศ. 2562 กำหนด โดยการใช้สิทธิดังกล่าวไม่กระทบต่อหน้าที่ในการลงเวลาปฏิบัติราชการและการปฏิบัติตามกฎหมาย กฎ ระเบียบ และหลักเกณฑ์ของกรุงเทพมหานคร', + ], consentText: - 'ข้าพเจ้าได้อ่านและเข้าใจรายละเอียดทั้งหมดแล้ว และยินยอมให้เก็บ ใช้ และประมวลผลข้อมูลส่วนบุคคล ประเภทภาพถ่ายของข้าพเจ้า ตามที่ระบุไว้ข้างต้นโดยสมัครใจ', + 'ข้าพเจ้าได้รับทราบประกาศความเป็นส่วนตัวเกี่ยวกับการลงเวลาปฏิบัติราชการผ่านระบบอิเล็กทรอนิกส์แล้ว', buttons: { - accept: 'ยอมรับ', + accept: 'รับทราบและดำเนินการต่อ', decline: 'ไม่ยอมรับ', }, } @@ -97,7 +82,8 @@ const toggleDetails = () => { const checkIfScrollable = () => { nextTick(() => { - const container = (scrollContainer.value as any)?.$el || scrollContainer.value + const container = + (scrollContainer.value as any)?.$el || scrollContainer.value if (container) { const { scrollHeight, clientHeight } = container @@ -167,50 +153,18 @@ const checkIfScrollable = () => { {{ privacyContent.detailIntro }}

- +
-
    -
  1. - {{ item }} -
  2. -
-
- - -
- ข้าพเจ้าทราบและเข้าใจว่า - -
- - -
-

- {{ privacyContent.rights.title }} +

+ {{ paragraph }}

- - -
+ + diff --git a/src/components/TableHistory.vue b/src/components/TableHistory.vue index c364c30..e081a3c 100644 --- a/src/components/TableHistory.vue +++ b/src/components/TableHistory.vue @@ -13,20 +13,15 @@ import SkeletonTable from '@/components/SkeletonTable.vue' // skeleton table const { date2Thai } = useCounterMixin() const stores = useCheckIn() +const page = defineModel('page', { required: true }) +const pageSize = defineModel('pageSize', { required: true }) + /** props ข้อมูลจาก Components Page HistoryView */ const props = defineProps({ paging: { type: Boolean, default: false, }, - pageSize: { - type: Number, - default: 10, - }, - page: { - type: Number, - default: 1, - }, maxPage: { type: Number, default: 1, @@ -194,31 +189,20 @@ const visibleColumns = ref([ 'checkOutLocation', 'checkOutStatus', ]) - -const currentPage = ref(1) //หน้าปัจจุบัน -// Pagination - initial pagination -const initialPagination = ref({ - sortBy: null, - descending: false, - page: 1, - rowsPerPage: props.pageSize, // set ตาม page หลักส่งมา +const pagination = ref({ + page: page.value, + rowsPerPage: pageSize.value, }) // Pagination - update rowsPerPage async function updatePagination(newPagination: Pagination) { - initialPagination.value = newPagination - currentPage.value = 1 // set current page เป็น 1 เสมอเมื่อเปลี่ยน per row + pageSize.value = newPagination.rowsPerPage } async function filterFn() { - // ส่งอีเวนต์ 'update:change-page' เมื่อหน้าเปลี่ยนแปลง - emit( - 'update:change-page', - 1, - initialPagination.value.rowsPerPage, - keyword.value - ) + emit('update:change-page', 1, pageSize.value, keyword.value) } + const modalPopup = ref(false) // popup แก้ไขลงเวลา const titlePopup = ref('') // หัวขข้อ popup แก้ไขลงเวลา const dataRow = ref() // ข้อมูลการลงเวลา @@ -276,17 +260,15 @@ function onClickOpenPopupRejrct(data: DataCheckIn) { } } -/** watch currentPage และ rowsPerPage*/ +function onUpdatePage(val: number) { + emit('update:change-page', val, pageSize.value, keyword.value) +} + +/** watch pageSize*/ watch( - [() => currentPage.value, () => initialPagination.value.rowsPerPage], + () => pageSize.value, () => { - // ส่งอีเวนต์ 'update:change-page' เมื่อหน้าเปลี่ยนแปลง - emit( - 'update:change-page', - currentPage.value, - initialPagination.value.rowsPerPage, - keyword.value - ) + emit('update:change-page', 1, pageSize.value, keyword.value) } ) @@ -340,10 +322,10 @@ watch( v-model:selected="selected" :virtual-scroll-sticky-size-start="48" :style="$q.screen.gt.xs ? 'max-height: 64vh' : ''" - :rows-per-page-options="[10, 25, 50, 100]" + :rows-per-page-options="[1, 10, 25, 50, 100]" :grid="$q.screen.gt.xs ? false : true" - :pagination="initialPagination" @update:pagination="updatePagination" + v-model:pagination="pagination" > + diff --git a/src/composables/usePermissions.ts b/src/composables/usePermissions.ts index ecf1ef3..b92ed29 100644 --- a/src/composables/usePermissions.ts +++ b/src/composables/usePermissions.ts @@ -1,52 +1,171 @@ -import { useQuasar } from 'quasar' +import { onBeforeUnmount, ref } from 'vue' import { usePrivacyStore } from '@/stores/privacy' +type BrowserPermissionState = PermissionState | 'unsupported' + +type PermissionQueryName = 'camera' | 'geolocation' + export function usePermissions() { - const $q = useQuasar() const privacyStore = usePrivacyStore() + const cameraPermissionState = ref('prompt') + const locationPermissionState = ref('prompt') - // const checkCameraPermission = (): boolean => { - // if (!privacyStore.isAccepted) { - // privacyStore.modalPrivacy = true - // $q.notify({ - // type: 'warning', - // message: 'กรุณายอมรับนโยบายคุ้มครองข้อมูลส่วนบุคคลก่อนใช้งานกล้อง', - // position: 'top', - // }) - // return false - // } - // return true - // } + let cameraPermissionStatus: PermissionStatus | null = null + let locationPermissionStatus: PermissionStatus | null = null - // const checkLocationPermission = (): boolean => { - // if (!privacyStore.isAccepted) { - // privacyStore.modalPrivacy = true - // $q.notify({ - // type: 'warning', - // message: 'กรุณายอมรับนโยบายคุ้มครองข้อมูลส่วนบุคคลก่อนใช้งานแผนที่', - // position: 'top', - // }) - // return false - // } - // return true - // } + const isPermissionsApiSupported = () => + typeof navigator !== 'undefined' && 'permissions' in navigator + + const setPermissionState = ( + target: typeof cameraPermissionState | typeof locationPermissionState, + state: BrowserPermissionState + ) => { + target.value = state + } + + const setPermissionChangeListener = ( + 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 => { if (!privacyStore.isAccepted) { privacyStore.modalPrivacy = true - // $q.notify({ - // type: 'warning', - // message: 'กรุณายอมรับนโยบายคุ้มครองข้อมูลส่วนบุคคลก่อนใช้งาน', - // position: 'center', - // }) return false } 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((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 { - // checkCameraPermission, - // checkLocationPermission, + cameraPermissionState, + locationPermissionState, checkPrivacyAccepted, + syncPermissionStates, + requestCameraPermission, + requestLocationPermission, } } diff --git a/src/interface/index/Main.ts b/src/interface/index/Main.ts index 5d82bd2..72b2ba1 100644 --- a/src/interface/index/Main.ts +++ b/src/interface/index/Main.ts @@ -29,7 +29,7 @@ interface Pagination { sortBy: string | null descending: boolean page: number - rowsPerPage: number | undefined + rowsPerPage: number } interface DataCheckIn { checkInDate: string diff --git a/src/main.ts b/src/main.ts index b04278c..04b0dfd 100644 --- a/src/main.ts +++ b/src/main.ts @@ -12,6 +12,9 @@ import 'quasar/src/css/index.sass' import th from 'quasar/lang/th' import http from '@/plugins/http' +import { forceOpenInExternalBrowser } from '@/utils/forceExternalBrowser' + +forceOpenInExternalBrowser() const app = createApp(App) const pinia = createPinia() diff --git a/src/stores/socket.ts b/src/stores/socket.ts new file mode 100644 index 0000000..28c1e3b --- /dev/null +++ b/src/stores/socket.ts @@ -0,0 +1,101 @@ +import { ref } from 'vue' +import config from '@/app.config' +import { getToken } from '@/plugins/auth' +import { defineStore } from 'pinia' +import { Notify } from 'quasar' +import { io, Socket } from 'socket.io-client' +interface sockeBackup { + message: string + success?: boolean +} + +export const useSocketStore = defineStore('socket', () => { + let socket: Socket + const notificationCounter = ref(0); + + async function init() { + socket = io(new URL(config.API.socket).origin, { + auth: { token: await getToken() }, + path: '/api/v1/org-socket', + }) + + socket.on('socket-notification', (payload) => { + let body: sockeBackup = JSON.parse(payload) + notificationCounter.value++ + notifyStatus(body.message, body.success) + }) + } + + function notifyStatus(message: string, success?: boolean) { + Notify.create({ + group: false, + type: success === undefined || success ? 'positive' : 'negative', + message: `${message}`, + position: 'top', + classes: 'custom-notification-top', // ใส่ class ที่เราสร้างไว้ + timeout: success === undefined || success ? 3000 : 0, + actions: + success === undefined || success + ? [] + : [ + { + icon: 'close', + color: 'white', + round: true, + }, + ], + progress: true, + }) + } + + function fnStyleNotiOrg() { + if (document.getElementById('notify-link-style')) return + const style = document.createElement('style') + style.id = 'notify-link-style' + style.textContent = ` + .notify-link { + padding: 4px 8px; + border-radius: 4px; + text-decoration: none; + color: #fff; + border: 1px solid #fff; + transition: all 0.3s; + cursor: pointer; + margin:0 0 0 5px; + } + .notify-link:hover { + background-color: #ffffff; + color: #21BA45; + } + ` + document.head.appendChild(style) + } + ;(window as any).resetOrgPage = (type: string) => { + localStorage.setItem('org_type', type) + window.location.reload() + } + function notifyStatusOrg(type: string, message: string, success?: boolean) { + fnStyleNotiOrg() + Notify.create({ + message: `${message} ${ + type == 'draft' ? 'ไปยังโครงสร้างแบบร่าง' : 'ไปยังโครงสร้างปัจจุบัน' + }`, + html: true, + group: false, + type: success === undefined || success ? 'positive' : 'negative', + position: 'top', + timeout: 0, + actions: [ + { + icon: 'close', + color: 'white', + round: true, + }, + ], + }) + } + + init() + + return { notificationCounter } +}) diff --git a/src/style/quasar-variables.sass b/src/style/quasar-variables.sass index f2c3dc4..e590103 100644 --- a/src/style/quasar-variables.sass +++ b/src/style/quasar-variables.sass @@ -69,30 +69,30 @@ div $separator-color: #EDEDED !default .bg-teal-1 - background: #e0f2f1a6 !important - + background: #e0f2f1a6 !important + .table_ellipsis - max-width: 200px - white-space: nowrap - overflow: hidden - text-overflow: ellipsis + max-width: 200px + white-space: nowrap + overflow: hidden + text-overflow: ellipsis .table_ellipsis:hover - word-wrap: break-word - overflow: visible - white-space: normal + word-wrap: break-word + overflow: visible + white-space: normal .table_ellipsis2 - max-width: 25vw - white-space: nowrap - overflow: hidden - text-overflow: ellipsis + max-width: 25vw + white-space: nowrap + overflow: hidden + text-overflow: ellipsis .table_ellipsis2:hover - word-wrap: break-word - overflow: visible - white-space: normal - transition: width 2s + word-wrap: break-word + overflow: visible + white-space: normal + transition: width 2s $muti-tab: #87d4cc .text-muti-tab @@ -100,35 +100,33 @@ $muti-tab: #87d4cc .bg-muti-tab background: $muti-tab !important - /* editor */ .q-editor font-size: 1rem line-height: 1.5rem font-weight: 400 - + .q-editor h1, .q-menu h1 - font-size: 1.5rem - line-height: 2rem - font-weight: 400 - margin-block-start: 0em - margin-block-end: 0em + font-size: 1.5rem + line-height: 2rem + font-weight: 400 + margin-block-start: 0em + margin-block-end: 0em .q-editor h2, .q-menu h2 - font-size: 1.25rem - line-height: 1.5rem - font-weight: 400 - margin-block-start: 0em - margin-block-end: 0em - + font-size: 1.25rem + line-height: 1.5rem + font-weight: 400 + margin-block-start: 0em + margin-block-end: 0em .q-editor h3, .q-menu h3 - font-size: 1.1rem - line-height: 1.5rem - font-weight: 400 - margin-block-start: 0em - margin-block-end: 0em + font-size: 1.1rem + line-height: 1.5rem + font-weight: 400 + margin-block-start: 0em + margin-block-end: 0em .q-editor p, .q-menu p margin: 0 @@ -136,4 +134,7 @@ $muti-tab: #87d4cc /* q-tree */ .q-tree - color: #c8d3db + color: #c8d3db + +.custom-notification-top + margin-top: 180px !important diff --git a/src/utils/forceExternalBrowser.ts b/src/utils/forceExternalBrowser.ts new file mode 100644 index 0000000..bf65fa3 --- /dev/null +++ b/src/utils/forceExternalBrowser.ts @@ -0,0 +1,57 @@ +const EXTERNAL_BROWSER_QUERY_KEY = 'openExternalBrowser' + +const isLineBrowser = (userAgent: string) => /Line/i.test(userAgent) + +const isAndroid = (userAgent: string) => /Android/i.test(userAgent) + +const isIOS = (userAgent: string) => /iPhone|iPad|iPod/i.test(userAgent) + +const hasExternalRedirectFlag = () => { + const params = new URLSearchParams(window.location.search) + return params.get(EXTERNAL_BROWSER_QUERY_KEY) === '1' +} + +const buildIOSUrlWithFlag = () => { + const url = new URL(window.location.href) + url.searchParams.set(EXTERNAL_BROWSER_QUERY_KEY, '1') + return url.toString() +} + +const buildUrlWithoutFlag = () => { + const url = new URL(window.location.href) + url.searchParams.delete(EXTERNAL_BROWSER_QUERY_KEY) + return url.toString() +} + +const buildAndroidIntentUrl = () => { + const currentUrl = window.location.href + const strippedUrl = currentUrl.replace(/^https?:\/\//i, '') + return `intent://${strippedUrl}#Intent;scheme=https;package=com.android.chrome;end` +} + +export const forceOpenInExternalBrowser = () => { + const userAgent = navigator.userAgent || '' + + // Prevent redirect loops and only run in LINE browser. + if (!isLineBrowser(userAgent) || hasExternalRedirectFlag()) { + return + } + + if (isAndroid(userAgent)) { + window.location.replace(buildAndroidIntentUrl()) + return + } + + if (isIOS(userAgent)) { + window.location.replace(buildIOSUrlWithFlag()) + } +} + +export const shouldShowIOSLineFallback = () => { + const userAgent = navigator.userAgent || '' + return ( + isLineBrowser(userAgent) && isIOS(userAgent) && hasExternalRedirectFlag() + ) +} + +export const getExternalBrowserUrl = () => buildUrlWithoutFlag() diff --git a/src/views/HistoryView.vue b/src/views/HistoryView.vue index 089d697..8f5a2bd 100644 --- a/src/views/HistoryView.vue +++ b/src/views/HistoryView.vue @@ -115,6 +115,7 @@ async function fetchlistTime() { async function updateYear(y: number, m: number) { stores.tab === 'history' ? (year.value = y) : (year2.value = y) month.value = m + page.value = 1 // รีเซ็ตหน้าเป็นหน้าแรกเมื่อปีหรือเดือนเปลี่ยนแปลง await functionFetch() // เรียกใช้งานฟังก์ชัน functionFetch เพื่อดึงข้อมูลใหม่ } @@ -177,9 +178,9 @@ watch( /> -import { ref, reactive, onMounted, watch, onBeforeUnmount, computed } from 'vue' +import { + ref, + reactive, + onMounted, + watch, + onBeforeUnmount, + computed, + nextTick, +} from 'vue' import { useQuasar } from 'quasar' import { format } from 'date-fns' import Camera from 'simple-vue-camera' +import { storeToRefs } from 'pinia' import config from '@/app.config' import http from '@/plugins/http' @@ -10,6 +19,7 @@ import { useCounterMixin } from '@/stores/mixin' import { usePermissions } from '@/composables/usePermissions' import { usePrivacyStore } from '@/stores/privacy' import { usePositionKeycloakStore } from '@/stores/positionKeycloak' +import { useSocketStore } from '@/stores/socket' import type { FormRef, OptionReason } from '@/interface/response/checkin' @@ -18,7 +28,14 @@ import MapCheck from '@/components/AscGISMap.vue' const mixin = useCounterMixin() const { date2Thai, showLoader, hideLoader, messageError, dialogConfirm } = mixin const $q = useQuasar() -const { checkPrivacyAccepted } = usePermissions() +const { + cameraPermissionState, + checkPrivacyAccepted, + syncPermissionStates, + requestCameraPermission, +} = usePermissions() +const socketStore = useSocketStore() +const { notificationCounter } = storeToRefs(socketStore) const privacyStore = usePrivacyStore() const positionKeycloakStore = usePositionKeycloakStore() const MOCK_CHECK_DELAY_MS = 800 @@ -50,10 +67,40 @@ const msgCheckTime = ref('') // ข้อความแจ้งเต const isDisabledCheckTime = ref(true) // ข้อความแจ้งเตือน const isErr = ref(null) // ข้อความแจ้งเตือน const endTimeAfternoon = ref('12:00:00') //เวลาเช็คเอาท์ตามรอบ +const crossDayCheckoutWarning = ref('') const isLoadingCheckTime = ref(false) // ตัวแปรสำหรับการโหลด const disabledBtn = ref(false) +function parseApiDateTime(value?: string | null) { + if (!value) return null + + const normalizedValue = value.includes('T') ? value : value.replace(' ', 'T') + const parsedDate = new Date(normalizedValue) + return Number.isNaN(parsedDate.getTime()) ? null : parsedDate +} + +function isSameCalendarDay(firstDate: Date, secondDate: Date) { + return ( + firstDate.getFullYear() === secondDate.getFullYear() && + firstDate.getMonth() === secondDate.getMonth() && + firstDate.getDate() === secondDate.getDate() + ) +} + +function updateCrossDayCheckoutWarning(checkInTime?: string | null) { + crossDayCheckoutWarning.value = '' + + const checkInDate = parseApiDateTime(checkInTime) + if (!checkInDate) return + + if (!isSameCalendarDay(checkInDate, new Date())) { + crossDayCheckoutWarning.value = `คุณยังไม่ได้ลงเวลาออกของวันที่ ${date2Thai( + checkInDate + )} กรุณาลงเวลาออกก่อน จึงจะลงเวลาเข้าของวันนี้ได้` + } +} + /** * fetch เช็คเวลาต้องลงเวลาเข้าหรือออกงาน */ @@ -66,6 +113,7 @@ async function fetchCheckTime(load: any = true) { statusCheckin.value = data.checkInId ? false : true checkInId.value = data.checkInId ? data.checkInId : '' + updateCrossDayCheckoutWarning(data.checkInTime) endTimeAfternoon.value = data.endTimeAfternoon isDisabledCheckTime.value = isDisabledCheckTime.value ? true : false }) @@ -89,7 +137,7 @@ const formattedM = ref() const formattedH = ref() const formattedHH = ref() const formattedA = ref() -const clockInterval = ref() +const clockInterval = ref | undefined>() /** function อัพเดทเวลา*/ function updateClock() { @@ -118,6 +166,7 @@ const useLocation = ref('') //กรณีเลือกนอกสถ const fileImg = ref() //รูปถ่ายสถานที่ const remark = ref('') //ข้อความหมายเหตุที่ต้องการระบุเพิ่ม const checkInId = ref('') //Id ลงเวลา check-in ล่าสุดที่ยังไม่ลงเวลาออก +const MIN_CAPTURE_FILE_SIZE_BYTES = 5 * 1024 /** * funciton เรียกพิกัดละติจูด พิกัดลองติจูด @@ -150,6 +199,131 @@ function wait(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)) } +function getCameraVideoElement() { + return camera.value?.video +} + +function prepareInlineCameraVideo(videoElement: HTMLVideoElement) { + videoElement.autoplay = true + videoElement.muted = true + videoElement.setAttribute('autoplay', '') + videoElement.setAttribute('muted', '') + videoElement.setAttribute('playsinline', '') + videoElement.setAttribute('webkit-playsinline', 'true') +} + +function isInlineCameraPreviewReady(videoElement: HTMLVideoElement) { + return ( + Boolean(videoElement.srcObject) && + videoElement.videoWidth > 0 && + videoElement.videoHeight > 0 && + videoElement.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA + ) +} + +async function waitForCameraInstance() { + for (let attempt = 0; attempt < 10; attempt += 1) { + await nextTick() + + if (camera.value) { + return camera.value + } + + await wait(50) + } + + return null +} + +async function stopInlineCamera() { + camera.value?.stop() + cameraIsOn.value = false +} + +async function remountInlineCameraComponent() { + await stopInlineCamera() + cameraMountKey.value += 1 + await nextTick() + await wait(INLINE_CAMERA_REMOUNT_DELAY_MS) +} + +async function ensureInlineCameraPreviewReady() { + const deadline = Date.now() + INLINE_CAMERA_PREVIEW_TIMEOUT_MS + let lastPlaybackError: unknown = null + + while (Date.now() < deadline) { + const videoElement = getCameraVideoElement() + + if (videoElement) { + prepareInlineCameraVideo(videoElement) + + if (isInlineCameraPreviewReady(videoElement)) { + return + } + + if (videoElement.srcObject) { + try { + await videoElement.play() + } catch (error) { + lastPlaybackError = error + } + } + } + + await wait(INLINE_CAMERA_PREVIEW_POLL_MS) + } + + if (lastPlaybackError instanceof Error) { + throw lastPlaybackError + } + + throw new Error('Inline camera preview did not become ready in time') +} + +async function syncActiveCameraDevices() { + const devices: any = await camera.value?.devices(['videoinput']) + if (!devices) { + return + } + + availableCameras.value = devices + + const activeId = camera.value?.currentDeviceID() + const activeIdx = activeId + ? devices.findIndex((device: any) => device.deviceId === activeId) + : -1 + currentCameraIndex.value = activeIdx >= 0 ? activeIdx : 0 + currentCameraType.value = resolveCameraType( + devices[currentCameraIndex.value]?.label || '', + 'front' + ) +} + +async function startInlineCamera(recoveryAttempt = 0): Promise { + const cameraInstance = await waitForCameraInstance() + + if (!cameraInstance) { + throw new Error('Camera component is unavailable') + } + + try { + currentCameraType.value = 'front' + await cameraInstance.start() + await ensureInlineCameraPreviewReady() + await syncActiveCameraDevices() + cameraIsOn.value = true + } catch (error) { + await stopInlineCamera() + + if (recoveryAttempt < MAX_INLINE_CAMERA_RECOVERY_ATTEMPTS) { + await remountInlineCameraComponent() + return startInlineCamera(recoveryAttempt + 1) + } + + throw error + } +} + async function getDelayedFreshPosition() { const firstPosition = await getCurrentPositionAsync({ enableHighAccuracy: true, @@ -192,6 +366,11 @@ const options = ref([ // value: 'ประสบภัย เช่น น้ำท่วม มีพายุ ประสบอุบัติเหตุ', // text: 'ประสบภัย เช่น น้ำท่วม มีพายุ ประสบอุบัติเหตุ', // }, + { + value: 'ปฏิบัติงานในจุดบริการด่วนมหานคร', + text: 'ปฏิบัติงานในจุดบริการด่วนมหานคร', + }, + { value: 'อื่นๆ', text: 'อื่นๆ' }, ]) @@ -210,11 +389,227 @@ const cameraIsOn = ref(false) const img = ref(undefined) const photoWidth = ref(350) const photoHeight = ref(350) +const cameraMountKey = ref(0) const availableCameras = ref([]) const currentCameraIndex = ref(0) const currentCameraType = ref<'front' | 'back' | 'unknown'>('unknown') -const intervalId = ref(undefined) // ต้องใช้ตัวแปรเก็บค่า interval +/** + * Detect real iOS/iPadOS devices. Desktop mobile emulation can spoof the + * iPhone user-agent, so rely on platform + touch capability instead. + */ +const isIOSDevice: boolean = (() => { + const platform = navigator.platform || '' + const hasTouchPoints = navigator.maxTouchPoints > 1 + + return ( + /iPhone|iPad|iPod/.test(platform) || + (platform === 'MacIntel' && hasTouchPoints) + ) +})() + +const isAndroidDevice: boolean = /Android/i.test(navigator.userAgent) +/** + * `preferNativePhotoCapture` starts false on every device — inline camera is + * always attempted first. It is set to true only by + * `switchToNativePhotoCapture()` / `enableNativePhotoCaptureFallback()` when + * inline capture is proven to be unsupported or has failed. This covers iOS + * Safari too: getUserMedia is supported there since iOS 14.3, so we try + * inline first and fall back gracefully on first failure. + */ +const preferNativePhotoCapture = ref(false) +const useNativePhotoCapture = computed(() => preferNativePhotoCapture.value) +const centeredPreviewImageStyle = Object.freeze({ + objectFit: 'cover', + objectPosition: 'center center', +}) +const INLINE_CAMERA_PREVIEW_TIMEOUT_MS = isIOSDevice ? 2500 : 1800 +const INLINE_CAMERA_PREVIEW_POLL_MS = 120 +const INLINE_CAMERA_REMOUNT_DELAY_MS = 120 +const MAX_INLINE_CAMERA_RECOVERY_ATTEMPTS = 1 + +/** Ref for the hidden file input used as native camera fallback */ +const nativePhotoInput = ref(null) +const DEFAULT_NORMALIZED_IMAGE_QUALITY = 0.92 + +interface NormalizePhotoOptions { + fileName?: string + mirrorHorizontally?: boolean + quality?: number +} + +function clearSelectedPhoto() { + if (img.value) { + URL.revokeObjectURL(img.value) + img.value = undefined + } + fileImg.value = undefined +} + +async function canDecodeImageBlob(blob: Blob) { + if (!blob.type.startsWith('image/')) { + return false + } + + const imageUrl = URL.createObjectURL(blob) + + try { + const image = await new Promise((resolve, reject) => { + const element = new Image() + element.onload = () => { + if (element.naturalWidth > 0 && element.naturalHeight > 0) { + resolve(element) + } else { + reject(new Error('Image has invalid dimensions')) + } + } + element.onerror = () => reject(new Error('Image decode failed')) + element.src = imageUrl + }) + + return image.naturalWidth > 0 && image.naturalHeight > 0 + } catch (error) { + console.error('Error decoding captured image:', error) + return false + } finally { + URL.revokeObjectURL(imageUrl) + } +} + +async function isValidCapturedImage(blob: Blob) { + if (blob.size < MIN_CAPTURE_FILE_SIZE_BYTES) { + return false + } + + return canDecodeImageBlob(blob) +} + +async function loadImageFromBlob(blob: Blob) { + const imageUrl = URL.createObjectURL(blob) + + try { + return await new Promise((resolve, reject) => { + const image = new Image() + image.onload = () => resolve(image) + image.onerror = () => reject(new Error('Image load failed')) + image.src = imageUrl + }) + } finally { + URL.revokeObjectURL(imageUrl) + } +} + +async function normalizePhotoFile( + source: Blob, + options: NormalizePhotoOptions = {} +) { + const fileName = + options.fileName ?? + (source instanceof File && source.name + ? source.name + : `photo_${Date.now()}.jpg`) + const imageType = + source.type && source.type.startsWith('image/') ? source.type : 'image/jpeg' + + if (!options.mirrorHorizontally) { + if (source instanceof File && source.name === fileName) { + return source + } + + return new File([source], fileName, { type: imageType }) + } + + const image = await loadImageFromBlob(source) + const canvas = document.createElement('canvas') + canvas.width = image.naturalWidth + canvas.height = image.naturalHeight + + const context = canvas.getContext('2d') + if (!context) { + throw new Error('Canvas context unavailable') + } + + context.translate(canvas.width, 0) + context.scale(-1, 1) + context.drawImage(image, 0, 0, canvas.width, canvas.height) + + const normalizedBlob = await new Promise((resolve) => { + canvas.toBlob( + resolve, + imageType, + options.quality ?? DEFAULT_NORMALIZED_IMAGE_QUALITY + ) + }) + + if (!normalizedBlob) { + throw new Error('Failed to normalize image') + } + + return new File([normalizedBlob], fileName, { type: imageType }) +} + +async function assignSelectedPhoto(file: File) { + clearSelectedPhoto() + fileImg.value = file + img.value = URL.createObjectURL(file) +} + +function openNativePhotoCapture() { + void stopInlineCamera() + + if (nativePhotoInput.value) { + nativePhotoInput.value.value = '' + nativePhotoInput.value.click() + } +} + +function enableNativePhotoCaptureFallback() { + preferNativePhotoCapture.value = true + void stopInlineCamera() + clearSelectedPhoto() +} + +function switchToNativePhotoCapture() { + enableNativePhotoCaptureFallback() + openNativePhotoCapture() +} + +/** + * Called when the user selects / captures a photo via the native file-input + * fallback. Keeps the same `img` + `fileImg` state that capturePhoto() + * sets so the upload flow is identical. + */ +async function onNativePhotoSelected(event: Event) { + const input = event.target as HTMLInputElement + const file = input.files?.[0] + input.value = '' + if (!file) return + + if (!(await isValidCapturedImage(file))) { + clearSelectedPhoto() + messageError($q, '', 'ไม่สามารถอ่านไฟล์รูปภาพได้ กรุณาถ่ายรูปใหม่อีกครั้ง') + return + } + + try { + const normalizedFile = await normalizePhotoFile(file, { + fileName: file.name, + mirrorHorizontally: !isIOSDevice, + }) + + if (!(await isValidCapturedImage(normalizedFile))) { + throw new Error('Normalized image is invalid') + } + + await assignSelectedPhoto(normalizedFile) + } catch (error) { + console.error('Error normalizing native photo:', error) + clearSelectedPhoto() + messageError($q, error, 'ไม่สามารถเตรียมรูปภาพได้ กรุณาถ่ายรูปใหม่อีกครั้ง') + } +} + +const intervalId = ref | undefined>(undefined) /** * เริ่มจาก onMounted #1 เช็ค status คิว @@ -243,19 +638,18 @@ async function fetchCheckStatus() { /** inQueue เป็น true */ isDisabledCheckTime.value = true msgCheckTime.value = 'ระบบกำลังประมวลผล' - if (intervalId.value === undefined) { - intervalId.value = setInterval(async () => { - try { - await fetchCheckStatus() - } catch (error) { - console.error('Error in interval fetchCheckStatus:', error) - // หยุด interval ถ้าเกิด error - stopChecking() - } - }, 3000) - console.log('startChecking called, intervalId:', intervalId.value) - } - // hideLoader() + // if (intervalId.value === undefined) { + // intervalId.value = setInterval(async () => { + // try { + // await fetchCheckStatus() + // } catch (error) { + // console.error('Error in interval fetchCheckStatus:', error) + // // หยุด interval ถ้าเกิด error + // stopChecking() + // } + // }, 3000) + // console.log('startChecking called, intervalId:', intervalId.value) + // } } else { /** inQueue เป็น false */ isDisabledCheckTime.value = false @@ -334,6 +728,14 @@ function identifyCameraType(label: string): 'front' | 'back' | 'unknown' { return 'unknown' } +function resolveCameraType( + label: string, + fallbackType: 'front' | 'back' +): 'front' | 'back' { + const detectedType = identifyCameraType(label) + return detectedType === 'unknown' ? fallbackType : detectedType +} + /** function เปิดกล้อง*/ async function openCamera() { // เช็คสิทธิ์ privacy ก่อนเปิดกล้อง @@ -341,20 +743,35 @@ async function openCamera() { return } - if (!isPermissionCameraDenied.value) { - // change camera device - if (cameraIsOn.value) { - camera.value?.stop() - } else { - await camera.value?.start() - const devices: any = await camera.value?.devices(['videoinput']) - if (devices) { - availableCameras.value = devices - await changeCamera() - } + // If inline capture previously failed on this device, fall back to the + // native still-photo picker instead of reopening the live camera. + if (useNativePhotoCapture.value) { + openNativePhotoCapture() + return + } + + if (cameraIsOn.value) { + await stopInlineCamera() + return + } + + if ( + (isIOSDevice || isAndroidDevice) && + !useNativePhotoCapture.value && + (cameraPermissionState.value === 'denied' || + cameraPermissionState.value === 'unsupported') + ) { + switchToNativePhotoCapture() + return + } + + const hasCameraPermission = await requestCameraPermission() + if (!hasCameraPermission) { + if ((isIOSDevice || isAndroidDevice) && !useNativePhotoCapture.value) { + switchToNativePhotoCapture() + return } - cameraIsOn.value = !cameraIsOn.value - } else { + messageError( $q, '', @@ -362,6 +779,19 @@ async function openCamera() { ) return } + + try { + await startInlineCamera() + } catch (error) { + console.error('Error opening camera:', error) + + if ((isIOSDevice || isAndroidDevice) && !useNativePhotoCapture.value) { + switchToNativePhotoCapture() + return + } + + messageError($q, error, 'ไม่สามารถเปิดกล้องได้ กรุณาลองใหม่อีกครั้ง') + } } /** change camera device*/ @@ -378,9 +808,16 @@ async function changeCamera(targetCameraType?: 'front' | 'back') { if (devices.length === 1 || !targetCameraType) { const device = devices[0] + const fallbackType = + targetCameraType ?? + (currentCameraType.value === 'back' ? 'back' : 'front') await camera.value?.changeCamera(device.deviceId) + await ensureInlineCameraPreviewReady() currentCameraIndex.value = 0 - currentCameraType.value = identifyCameraType(device.label || '') + currentCameraType.value = resolveCameraType( + device.label || '', + fallbackType + ) return } @@ -392,14 +829,22 @@ async function changeCamera(targetCameraType?: 'front' | 'back') { if (matchingCameras.length > 0) { const targetDevice = matchingCameras[0] await camera.value?.changeCamera(targetDevice.deviceId) + await ensureInlineCameraPreviewReady() currentCameraIndex.value = devices.indexOf(targetDevice) - currentCameraType.value = targetCameraType + currentCameraType.value = resolveCameraType( + targetDevice.label || '', + targetCameraType + ) } else { const nextIndex = (currentCameraIndex.value + 1) % devices.length const nextDevice = devices[nextIndex] await camera.value?.changeCamera(nextDevice.deviceId) + await ensureInlineCameraPreviewReady() currentCameraIndex.value = nextIndex - currentCameraType.value = identifyCameraType(nextDevice.label || '') + currentCameraType.value = resolveCameraType( + nextDevice.label || '', + targetCameraType + ) } } catch (error) { console.error('Error switching camera:', error) @@ -415,34 +860,75 @@ async function switchCamera() { // สลับแค่ระหว่างกล้อง 2 ตัวแรก (กล้องหน้าและหลังหลัก) const targetIndex = currentCameraIndex.value === 0 ? 1 : 0 const targetDevice = availableCameras.value[targetIndex] + const fallbackType = currentCameraType.value === 'back' ? 'front' : 'back' await camera.value?.changeCamera(targetDevice.deviceId) + await ensureInlineCameraPreviewReady() currentCameraIndex.value = targetIndex - currentCameraType.value = identifyCameraType(targetDevice.label || '') + currentCameraType.value = resolveCameraType( + targetDevice.label || '', + fallbackType + ) } /** function ถ่ายรูป*/ async function capturePhoto() { - const imageBlob: any = await camera.value?.snapshot( - { width: photoWidth.value, height: photoHeight.value }, - 'image/png', - 0.5 - ) - if (!imageBlob) return - const fileName = 'photo.jpg' - //ไฟล์รูป - const file = new File([imageBlob], fileName, { type: 'image/png' }) - fileImg.value = file - //แสดงรูป - camera.value?.stop() - const url = URL.createObjectURL(imageBlob) - img.value = url + try { + const imageBlob: any = await camera.value?.snapshot( + { width: photoWidth.value, height: photoHeight.value }, + 'image/jpeg', + 0.8 + ) + if (!imageBlob || !(await isValidCapturedImage(imageBlob))) { + if (isIOSDevice || isAndroidDevice) { + switchToNativePhotoCapture() + return + } + + messageError($q, '', 'ไม่สามารถถ่ายรูปได้ กรุณาลองใหม่อีกครั้ง') + return + } + const fileName = `photo_${Date.now()}.jpg` + const normalizedFile = await normalizePhotoFile(imageBlob, { + fileName, + mirrorHorizontally: false, + quality: 0.8, + }) + + if (!(await isValidCapturedImage(normalizedFile))) { + throw new Error('Normalized image is invalid') + } + + await assignSelectedPhoto(normalizedFile) + + //แสดงรูป + await stopInlineCamera() + } catch (error) { + console.error('Error capturing photo:', error) + + if ((isIOSDevice || isAndroidDevice) && !useNativePhotoCapture.value) { + switchToNativePhotoCapture() + return + } + + messageError($q, error, 'ไม่สามารถถ่ายรูปได้ กรุณาลองใหม่อีกครั้ง') + } } /** function เปลี่ยนรูปภาพ*/ -function refreshPhoto() { - img.value = undefined - camera.value?.start() +async function refreshPhoto() { + try { + clearSelectedPhoto() + + if (useNativePhotoCapture.value) { + openNativePhotoCapture() + return + } + await startInlineCamera() + } catch (error) { + console.error('Error refreshing photo:', error) + messageError($q, error, 'ไม่สามารถเปิดกล้องได้ กรุณาลองใหม่อีกครั้ง') + } } /** ref validate*/ @@ -504,6 +990,7 @@ const mapRef = computed(() => ) const timeChickin = ref('') //เวลาเข้างาน,เวลาออกงาน +const displayedCheckDate = ref(new Date()) /** function ยืนยันการลงเวลาเข้า - ออก*/ async function confirm() { @@ -519,6 +1006,16 @@ async function confirm() { return } + if (!fileImg.value || !(await isValidCapturedImage(fileImg.value))) { + if ((isIOSDevice || isAndroidDevice) && !useNativePhotoCapture.value) { + enableNativePhotoCaptureFallback() + } + clearSelectedPhoto() + disabledBtn.value = false + messageError($q, '', 'รูปภาพไม่สมบูรณ์ กรุณาถ่ายรูปใหม่อีกครั้งก่อนลงเวลา') + return + } + showLoader() const isLocation = workplace.value === 'in-place' //*true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง const locationName = workplace.value === 'in-place' ? '' : useLocation.value @@ -536,6 +1033,7 @@ async function confirm() { .then(async (res) => { const data = await res.data.result const dateObject = new Date(data.date) + displayedCheckDate.value = dateObject checkDate.value = data.date ? true : false const options: Intl.DateTimeFormatOptions = { hour12: false, @@ -567,7 +1065,12 @@ async function getCheck() { } showLoader() - const isSeminar = model.value === 'ไปประชุม / อบรม / สัมมนา' ? 'Y' : 'N' + const isSeminar = + model.value === 'ไปประชุม / อบรม / สัมมนา' + ? 'S' + : model.value === 'ปฏิบัติงานในจุดบริการด่วนมหานคร' + ? 'O' + : 'N' await http .get(config.API.checkoutCheck + `/${isSeminar}`) @@ -617,7 +1120,7 @@ async function onClickConfirm() { try { showLoader() cameraIsOn.value = false - img.value = undefined + clearSelectedPhoto() modalTime.value = false if (!statusCheckin.value) { statusCheckin.value = true @@ -655,13 +1158,8 @@ const inQueue = ref(false) // ฟังก์ชันสำหรับรีเซ็ตรูปและหยุดกล้อง function resetCameraAndImage() { - if (img.value) { - img.value = undefined - } - if (cameraIsOn.value && camera.value) { - camera.value.stop() - cameraIsOn.value = false - } + clearSelectedPhoto() + void stopInlineCamera() } // เพิ่มฟังก์ชันสำหรับจัดการการปิดแอพในมือถือ @@ -687,16 +1185,6 @@ function handleVisibilityChange() { } } -const isPermissionCameraDenied = ref(false) // ตัวแปรสำหรับตรวจสอบการปฏิเสธสิทธิ์กล้อง - -async function requestCamera() { - try { - await navigator.mediaDevices.getUserMedia({ video: true }) - } catch (err) { - isPermissionCameraDenied.value = true - } -} - /** Hook*/ onMounted(async () => { // เริ่มต้น clock เสมอ @@ -713,10 +1201,11 @@ onMounted(async () => { startChecking() } + await syncPermissionStates() + // เรียกแผนที่เฉพาะเมื่อยอมรับ privacy แล้ว if (privacyStore.isAccepted) { mapRef.value?.requestLocationPermission() - requestCamera() } }) @@ -755,13 +1244,18 @@ onBeforeUnmount(() => { watch( () => privacyStore.isAccepted, - (newVal) => { + async (newVal) => { if (newVal) { + await syncPermissionStates() mapRef.value?.requestLocationPermission() - requestCamera() } } ) + +/** Watch notification counter on socket */ +watch(notificationCounter, () => { + startChecking() +}) diff --git a/src/views/login.vue b/src/views/login.vue index df02614..df0725d 100644 --- a/src/views/login.vue +++ b/src/views/login.vue @@ -20,7 +20,7 @@ const password = ref('') async function onSubmit() { showLoader() const formdata = new URLSearchParams() - formdata.append('username', username.value) + formdata.append('username', username.value.trim()) formdata.append('password', password.value) await axios