From 7771a9e67bb706f3ec108a2319ba662aa9679efa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20?= =?UTF-8?q?=D0=9F=D0=BE=D1=80=D1=8F=D0=B4=D0=B8=D0=BD?= Date: Tue, 12 May 2026 17:25:36 +0300 Subject: [PATCH 01/12] =?UTF-8?q?feat(mobile):=20shared=20infra=20for=20cl?= =?UTF-8?q?osed=20epics=20=E2=80=94=20API,=20i18n,=20routes,=20types?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Базовый слой для phase 2/3/4 student flows, edge-cases, notifications phase 2, review reports, change-password, delete-account, blacklist, multi-device push. - API client: change_password, delete_my_account, blacklist CRUD, slot reschedule/cancel-with-reason, reviews (canCreate/update/delete/report), notifications (listMyNotifications/markRead/markAllRead/unreadCount/sendTestPush), multi-device push token register/deregister, release endpoint stub - Types/contract: TutorSummary enrichment (min_price/max_price/is_online/ last_seen_at/accepts_online/accepts_offline/services_count/has_slots_this_week/ reviews_count), NotificationItem, ReviewReport, blacklist entries - i18n: ~120 новых ключей (change-password, delete-account, reschedule, edge-cases, notifications, legal, test push) en+ru - Routes: CHANGE_PASSWORD, DELETE_ACCOUNT, RESCHEDULE_SLOT - Navigation types: новые экраны зарегистрированы в SettingsStack/CalendarStack --- src/navigation/types.ts | 8 + src/shared/api/client.methods.test.ts | 23 ++ src/shared/api/client.ts | 150 ++++++- src/shared/api/contract.ts | 32 +- src/shared/api/endpoints.ts | 13 + src/shared/api/mockClient.ts | 409 ++++++++++++++++++- src/shared/api/types.ts | 98 ++++- src/shared/components/ServerStatusBanner.tsx | 2 + src/shared/config/i18n.ts | 142 +++++++ src/shared/constants/routes.ts | 4 + src/shared/state/authStore.ts | 32 +- src/shared/state/slotsStore.test.ts | 9 + src/shared/state/slotsStore.ts | 8 +- src/shared/utils/storage.ts | 44 ++ src/shared/utils/toast.ts | 11 + 15 files changed, 947 insertions(+), 38 deletions(-) create mode 100644 src/shared/utils/storage.ts create mode 100644 src/shared/utils/toast.ts diff --git a/src/navigation/types.ts b/src/navigation/types.ts index ee076bd..9c67b04 100644 --- a/src/navigation/types.ts +++ b/src/navigation/types.ts @@ -30,7 +30,10 @@ type SettingsStackParamList = { [ROUTES.SETTINGS_STACK]: undefined; [ROUTES.APP_SETTINGS]: undefined; [ROUTES.NOTIFICATION_SETTINGS]: undefined; + [ROUTES.NOTIFICATIONS_INBOX]: undefined; [ROUTES.BLACKLIST]: undefined; + [ROUTES.CHANGE_PASSWORD]: undefined; + [ROUTES.DELETE_ACCOUNT]: undefined; [ROUTES.FEEDBACK]: undefined; [ROUTES.RELEASE_NOTES]: undefined; [ROUTES.ADMIN]: undefined; @@ -62,6 +65,11 @@ type CalendarStackParamList = { slotId: number; tutorName?: string; }; + [ROUTES.RESCHEDULE_SLOT]: { + slotId: number; + tutorName?: string; + currentStartAt: string; + }; }; type ChatsStackParamList = { diff --git a/src/shared/api/client.methods.test.ts b/src/shared/api/client.methods.test.ts index 6c67842..799aa80 100644 --- a/src/shared/api/client.methods.test.ts +++ b/src/shared/api/client.methods.test.ts @@ -34,6 +34,9 @@ describe('ApiClient methods', () => { minRating: 4.5, sortBy: 'rating', sortDir: 'desc', + isOnlineOnly: true, + hasSlotsThisWeek: true, + format: 'online', page: 2, pageSize: 20, }); @@ -44,6 +47,9 @@ describe('ApiClient methods', () => { expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('min_rating=4.5'); expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('sort_by=rating'); expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('sort_dir=desc'); + expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('is_online_only=true'); + expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('has_slots_this_week=true'); + expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('format=online'); expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('page=2'); expect(fetchMock.mock.calls.at(-1)?.[0]).toContain('page_size=20'); @@ -112,6 +118,8 @@ describe('ApiClient methods', () => { await client.register({ phone: '+1', password: 'pass', role: 'student' }); await client.checkPhone('+1'); await client.me(); + await client.changePassword({ currentPassword: 'oldpass123', newPassword: 'newpass123' }); + await client.deleteMyAccount(); await client.getUserById(3); expect(fetchMock).toHaveBeenCalled(); }); @@ -138,6 +146,10 @@ describe('ApiClient methods', () => { await client.listTutorStudents(1); await client.updateTutorStudent({ tutorId: 1, studentId: 2, notes: 'note' }); await client.createReview({ slotId: 1, tutorId: 2, studentId: 3, rating: 5, comment: 'ok' }); + await client.canCreateReview(2); + await client.updateReview({ reviewId: 1, studentId: 3, rating: 4, comment: 'upd' }); + await client.deleteReview(1, 3); + await client.reportReview({ reviewId: 2, reason: 'spam' }); expect(fetchMock).toHaveBeenCalled(); }); @@ -219,6 +231,17 @@ describe('ApiClient methods', () => { await client.getOrCreateChatThread({ studentId: 1, tutorId: 101 }); expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://example.com/api/chats/ensure'); + + await client.listMyBlacklist(); + expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://example.com/api/users/me/blacklist'); + + await client.addToMyBlacklist(101); + expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://example.com/api/users/me/blacklist'); + + await client.removeFromMyBlacklist(101); + expect(fetchMock.mock.calls.at(-1)?.[0]).toBe( + 'http://example.com/api/users/me/blacklist/101', + ); }); it('handles tutor analytics endpoints', async () => { diff --git a/src/shared/api/client.ts b/src/shared/api/client.ts index c0a85e7..127c432 100644 --- a/src/shared/api/client.ts +++ b/src/shared/api/client.ts @@ -8,6 +8,7 @@ import type { AuthTokenResponse, AuthUser, AdminNotificationSendResponse, + BlacklistEntry, ChatMessage, ChatThread, Feedback, @@ -16,6 +17,10 @@ import type { ListResponse, NotificationSettings, NotificationSettingsPayload, + NotificationItem, + NotificationListResponse, + NotificationUnreadCountResponse, + PushTokenRegistrationPayload, ReleaseNotesListResponse, TutorAnalyticsPriceHistory, TutorAnalyticsServiceBreakdown, @@ -266,6 +271,9 @@ class ApiClient implements ApiContract { ...(params.minRating !== undefined ? { min_rating: params.minRating } : {}), ...(params.sortBy !== undefined ? { sort_by: params.sortBy } : {}), ...(params.sortDir !== undefined ? { sort_dir: params.sortDir } : {}), + ...(params.isOnlineOnly ? { is_online_only: true } : {}), + ...(params.hasSlotsThisWeek ? { has_slots_this_week: true } : {}), + ...(params.format ? { format: params.format } : {}), ...(params.page !== undefined ? { page: params.page } : {}), ...(params.pageSize !== undefined ? { page_size: params.pageSize } : {}), } @@ -539,6 +547,54 @@ class ApiClient implements ApiContract { }); } + async canCreateReview(tutorId: number, slotId?: number): Promise<{ eligible: boolean; reason?: string | null }> { + return this.request<{ eligible: boolean; reason?: string | null }>(ENDPOINTS.reviewCanCreate, { + params: { + tutor_id: tutorId, + slot_id: slotId, + }, + }); + } + + async updateReview(payload: { + reviewId: number; + studentId: number; + rating?: number; + comment?: string; + }): Promise { + return this.request(ENDPOINTS.reviewById(payload.reviewId), { + method: 'PATCH', + body: { + student_id: payload.studentId, + rating: payload.rating, + comment: payload.comment, + }, + }); + } + + async deleteReview(reviewId: number, studentId: number): Promise { + return this.request(ENDPOINTS.reviewById(reviewId), { + method: 'DELETE', + body: { + student_id: studentId, + }, + }); + } + + async reportReview(payload: { + reviewId: number; + reason: 'spam' | 'offensive' | 'untruthful' | 'other'; + comment?: string; + }): Promise<{ id: number }> { + return this.request<{ id: number }>(ENDPOINTS.reviewReport(payload.reviewId), { + method: 'POST', + body: { + reason: payload.reason, + comment: payload.comment, + }, + }); + } + async listTutorReviews( tutorId: number, params?: { page?: number; pageSize?: number }, @@ -653,6 +709,25 @@ class ApiClient implements ApiContract { }); } + async listMyBlacklist(): Promise { + return this.request(ENDPOINTS.userMeBlacklist); + } + + async addToMyBlacklist(blockedId: number): Promise { + return this.request(ENDPOINTS.userMeBlacklist, { + method: 'POST', + body: { + blocked_id: blockedId, + }, + }); + } + + async removeFromMyBlacklist(blockedId: number): Promise { + return this.request(ENDPOINTS.userMeBlacklistById(blockedId), { + method: 'DELETE', + }); + } + async login(payload: { phone: string; password: string }): Promise { return this.request('/auth/login', { method: 'POST', @@ -688,6 +763,25 @@ class ApiClient implements ApiContract { return this.request('/auth/me'); } + async changePassword(payload: { + currentPassword: string; + newPassword: string; + }): Promise { + await this.request(ENDPOINTS.authChangePassword, { + method: 'POST', + body: { + current_password: payload.currentPassword, + new_password: payload.newPassword, + }, + }); + } + + async deleteMyAccount(): Promise { + await this.request(ENDPOINTS.userMeDelete, { + method: 'DELETE', + }); + } + async getTutorServices(tutorId: number): Promise { return this.request(ENDPOINTS.tutorServices(tutorId)); } @@ -958,10 +1052,25 @@ class ApiClient implements ApiContract { }); } - async registerPushToken(expoToken: string | null): Promise { + async registerPushToken(payload: PushTokenRegistrationPayload): Promise { await this.request(ENDPOINTS.userMePushToken, { method: 'POST', - body: { expo_push_token: expoToken }, + body: { + token: payload.token, + platform: payload.platform, + device_id: payload.device_id, + locale: payload.locale, + }, + }); + } + + async deregisterPushToken(payload: { token: string | null; device_id?: string }): Promise { + await this.request(ENDPOINTS.userMePushToken, { + method: 'DELETE', + body: { + token: payload.token, + device_id: payload.device_id, + }, }); } @@ -978,6 +1087,43 @@ class ApiClient implements ApiContract { }); } + async listMyNotifications(params?: { + limit?: number; + offset?: number; + }): Promise { + return this.request(ENDPOINTS.notificationsMeList, { + params: { + limit: params?.limit, + offset: params?.offset, + }, + }); + } + + async getUnreadNotificationsCount(): Promise { + return this.request(ENDPOINTS.notificationsMeUnreadCount); + } + + async markNotificationRead(notificationId: number): Promise { + return this.request(ENDPOINTS.notificationsMeReadById(notificationId), { + method: 'POST', + }); + } + + async markAllNotificationsRead(): Promise<{ updated_count: number }> { + return this.request<{ updated_count: number }>(ENDPOINTS.notificationsMeReadAll, { + method: 'POST', + }); + } + + async sendTestPush(): Promise<{ notification_id: number; queued: boolean }> { + return this.request<{ notification_id: number; queued: boolean }>( + ENDPOINTS.notificationsMeTestPush, + { + method: 'POST', + }, + ); + } + async listReleaseNotes(environment: string): Promise { return this.request('/release-notes', { params: { environment }, diff --git a/src/shared/api/contract.ts b/src/shared/api/contract.ts index 020a02a..2e34b6d 100644 --- a/src/shared/api/contract.ts +++ b/src/shared/api/contract.ts @@ -1,16 +1,24 @@ import type { AdminNotificationSendResponse, + BlacklistEntry, ChatMessage, ChatThread, NotificationSettings, NotificationSettingsPayload, + NotificationItem, + NotificationListResponse, + NotificationUnreadCountResponse, + SendTestPushResponse, + PushTokenRegistrationPayload, AuthTokenResponse, AuthUser, Feedback, FeedbackListResponse, + CanCreateReviewResponse, HealthResponse, ReleaseNotesListResponse, Review, + ReviewReportReason, Service, Slot, SlotStatus, @@ -122,6 +130,14 @@ interface ApiContract { rating: number; comment?: string; }): Promise; + canCreateReview(tutorId: number, slotId?: number): Promise; + updateReview(payload: { reviewId: number; studentId: number; rating?: number; comment?: string }): Promise; + deleteReview(reviewId: number, studentId: number): Promise; + reportReview(payload: { + reviewId: number; + reason: ReviewReportReason; + comment?: string; + }): Promise<{ id: number }>; listTutorReviews( tutorId: number, params?: { page?: number; pageSize?: number }, @@ -153,6 +169,9 @@ interface ApiContract { studentId: number; tutorId: number; }): Promise; + listMyBlacklist(): Promise; + addToMyBlacklist(blockedId: number): Promise; + removeFromMyBlacklist(blockedId: number): Promise; login(payload: { phone: string; password: string }): Promise; checkPhone(phone: string): Promise<{ exists: boolean }>; @@ -162,6 +181,8 @@ interface ApiContract { role: 'student' | 'tutor'; }): Promise; me(): Promise; + changePassword(payload: { currentPassword: string; newPassword: string }): Promise; + deleteMyAccount(): Promise; getTutorServices(tutorId: number): Promise; addTutorService(payload: { @@ -274,11 +295,20 @@ interface ApiContract { createFeedback(payload: { message: string }): Promise; listFeedback(params?: { page?: number; pageSize?: number }): Promise; - registerPushToken(expoToken: string | null): Promise; + registerPushToken(payload: PushTokenRegistrationPayload): Promise; + deregisterPushToken(payload: { + token: string | null; + device_id?: string; + }): Promise; getNotificationSettings(): Promise; updateNotificationSettings( data: Partial, ): Promise; + listMyNotifications(params?: { limit?: number; offset?: number }): Promise; + getUnreadNotificationsCount(): Promise; + markNotificationRead(notificationId: number): Promise; + markAllNotificationsRead(): Promise<{ updated_count: number }>; + sendTestPush(): Promise; listReleaseNotes(environment: string): Promise; dispatchLatestReleaseNote(payload?: { diff --git a/src/shared/api/endpoints.ts b/src/shared/api/endpoints.ts index b3d7e75..1347670 100644 --- a/src/shared/api/endpoints.ts +++ b/src/shared/api/endpoints.ts @@ -7,6 +7,9 @@ const ENDPOINTS = { chatsEnsure: '/chats/ensure', slots: '/slots', reviews: '/reviews', + reviewById: (reviewId: number) => `/reviews/${reviewId}`, + reviewCanCreate: '/reviews/can-create', + reviewReport: (reviewId: number) => `/reviews/${reviewId}/report`, serviceClicks: (serviceId: number) => `/services/${serviceId}/click`, tutorServices: (tutorId: number) => `/tutors/${tutorId}/services`, tutorServicesBulk: (tutorId: number) => `/tutors/${tutorId}/services/bulk`, @@ -31,7 +34,16 @@ const ENDPOINTS = { studentFavoriteTutorsDetails: (studentId: number) => `/students/${studentId}/favorite-tutors/details`, userMePushToken: '/users/me/push-token', + userMeDelete: '/users/me', userMeNotificationSettings: '/users/me/notification-settings', + notificationsMeUnreadCount: '/notifications/users/me/notifications/unread-count', + notificationsMeReadAll: '/notifications/users/me/notifications/read-all', + notificationsMeList: '/notifications/users/me/notifications', + notificationsMeTestPush: '/notifications/users/me/notifications/test-push', + notificationsMeReadById: (notificationId: number) => + `/notifications/users/me/notifications/${notificationId}/read`, + userMeBlacklist: '/users/me/blacklist', + userMeBlacklistById: (blockedId: number) => `/users/me/blacklist/${blockedId}`, userAvatar: (userId: number) => `/users/${userId}/avatar`, userAvatarUploadUrl: (userId: number) => `/users/${userId}/avatar/upload-url`, userAvatarMedia: (userId: number) => `/media/users/${userId}/avatar`, @@ -56,6 +68,7 @@ const ENDPOINTS = { chatThreadMessages: (threadId: number) => `/chats/${threadId}/messages`, chatThreadRead: (threadId: number) => `/chats/${threadId}/read`, mySlots: '/users/me/slots', + authChangePassword: '/auth/change-password', } as const; export { ENDPOINTS }; diff --git a/src/shared/api/mockClient.ts b/src/shared/api/mockClient.ts index ff4b834..3906393 100644 --- a/src/shared/api/mockClient.ts +++ b/src/shared/api/mockClient.ts @@ -4,6 +4,7 @@ import type { AdminNotificationSendResponse, AuthTokenResponse, AuthUser, + BlacklistEntry, ChatMessage, ChatThread, Feedback, @@ -11,6 +12,9 @@ import type { HealthResponse, NotificationSettings, NotificationSettingsPayload, + NotificationItem, + NotificationListResponse, + NotificationUnreadCountResponse, ReleaseNote, ReleaseNotesListResponse, Review, @@ -33,6 +37,7 @@ import type { TutorsQueryParams, UploadUrlResponse, UserAvatar, + PushTokenRegistrationPayload, } from './types'; type Credential = { @@ -52,6 +57,7 @@ type MockDb = { slots: Slot[]; slotHistory: SlotStatusHistory[]; reviews: Review[]; + blacklist: BlacklistEntry[]; favoriteTutors: Array<{ student_id: number; tutor_id: number; created_at: string }>; tutorRequests: TutorStudentRequest[]; tutorStudents: TutorStudent[]; @@ -62,6 +68,7 @@ type MockDb = { chatMessages: ChatMessage[]; feedback: Feedback[]; notificationSettingsByUser: Record; + notificationsByUser: Record; releaseNotes: ReleaseNote[]; serviceClicks: Map; nextIds: { @@ -70,6 +77,7 @@ type MockDb = { slot: number; slotHistory: number; review: number; + blacklist: number; tutorRequest: number; tutorStudent: number; userAvatar: number; @@ -690,6 +698,18 @@ const createMockDb = (): MockDb => { { student_id: 1, tutor_id: 102, created_at: nowIso() }, ]; + let blacklistId = 1; + const blacklist: BlacklistEntry[] = [ + { + id: blacklistId, + blocker_id: 1, + blocked_id: 102, + created_at: nowIso(), + updated_at: nowIso(), + }, + ]; + blacklistId += 1; + let tutorRequestId = 1; let tutorStudentId = 1; const tutorRequests: TutorStudentRequest[] = []; @@ -967,6 +987,7 @@ const createMockDb = (): MockDb => { slots, slotHistory, reviews, + blacklist, favoriteTutors, tutorRequests: ensureUniqueBy( tutorRequests, @@ -980,6 +1001,7 @@ const createMockDb = (): MockDb => { chatMessages, feedback, notificationSettingsByUser: {}, + notificationsByUser: {}, releaseNotes, serviceClicks: new Map(), nextIds: { @@ -988,6 +1010,7 @@ const createMockDb = (): MockDb => { slot: slotId, slotHistory: slotHistoryId, review: reviewId, + blacklist: blacklistId, tutorRequest: tutorRequestId, tutorStudent: tutorStudentId, userAvatar: userAvatarId, @@ -1091,6 +1114,14 @@ class MockApiClient implements ApiContract { return this.db.chatThreads.find((thread) => thread.id === threadId) ?? null; } + private hasBlacklistBetween(firstUserId: number, secondUserId: number) { + return this.db.blacklist.some( + (entry) => + (entry.blocker_id === firstUserId && entry.blocked_id === secondUserId) || + (entry.blocker_id === secondUserId && entry.blocked_id === firstUserId), + ); + } + private addSlotHistory(payload: { slotId: number; fromStatus: SlotStatus; @@ -1179,6 +1210,11 @@ class MockApiClient implements ApiContract { const minPrice = params?.minPrice; const maxPrice = params?.maxPrice; const minRating = params?.minRating; + const isOnlineOnly = params?.isOnlineOnly; + const hasSlotsThisWeek = params?.hasSlotsThisWeek; + const format = params?.format; + const now = Date.now(); + const weekEnd = now + 7 * 24 * 60 * 60 * 1000; const servicePoolByTutor = new Map(); this.db.tutorServices @@ -1210,6 +1246,28 @@ class MockApiClient implements ApiContract { if (minRating !== undefined && (tutor.rating ?? 0) < minRating) { return false; } + const acceptsOnline = tutor.formats?.includes('online') ?? false; + const acceptsOffline = tutor.formats?.includes('offline') ?? false; + const isOnline = tutor.id % 3 !== 0; + const tutorHasSlotsThisWeek = this.db.slots.some((slot) => { + if (slot.tutor_id !== tutor.id || slot.status !== SLOT_STATUS.FREE) { + return false; + } + const slotTimestamp = new Date(slot.start_at).getTime(); + return Number.isFinite(slotTimestamp) && slotTimestamp >= now && slotTimestamp <= weekEnd; + }); + if (isOnlineOnly && !isOnline) { + return false; + } + if (hasSlotsThisWeek && !tutorHasSlotsThisWeek) { + return false; + } + if (format === 'online' && !acceptsOnline) { + return false; + } + if (format === 'offline' && !acceptsOffline) { + return false; + } return true; }); @@ -1253,13 +1311,34 @@ class MockApiClient implements ApiContract { }); } - const mapped = tutors.map((tutor) => ({ - id: tutor.id, - name: tutor.name, - rating: tutor.rating ?? null, - experience: tutor.experience ?? null, - description: tutor.description ?? null, - })); + const mapped = tutors.map((tutor) => { + const tutorServices = servicePoolByTutor.get(tutor.id) ?? []; + const visiblePrices = tutorServices.map((item) => item.price_per_hour); + const isOnline = tutor.id % 3 !== 0; + const hasFreeSlotsThisWeek = this.db.slots.some((slot) => { + if (slot.tutor_id !== tutor.id || slot.status !== SLOT_STATUS.FREE) { + return false; + } + const slotTimestamp = new Date(slot.start_at).getTime(); + return Number.isFinite(slotTimestamp) && slotTimestamp >= now && slotTimestamp <= weekEnd; + }); + return { + id: tutor.id, + name: tutor.name, + rating: tutor.rating ?? null, + reviews_count: reviewsCountByTutor.get(tutor.id) ?? 0, + experience: tutor.experience ?? null, + description: tutor.description ?? null, + min_price: visiblePrices.length > 0 ? Math.min(...visiblePrices) : null, + max_price: visiblePrices.length > 0 ? Math.max(...visiblePrices) : null, + is_online: isOnline, + last_seen_at: isOnline ? null : new Date(now - ((tutor.id % 9) + 1) * 45 * 60_000).toISOString(), + accepts_online: tutor.formats?.includes('online') ?? false, + accepts_offline: tutor.formats?.includes('offline') ?? false, + services_count: tutorServices.length, + has_slots_this_week: hasFreeSlotsThisWeek, + }; + }); if ( typeof params?.page === 'number' && @@ -1910,6 +1989,12 @@ class MockApiClient implements ApiContract { if (!slot) { throw createApiError('Slot not found', { status: 404, code: 'slot_not_found' }); } + if (this.hasBlacklistBetween(studentId, slot.tutor_id)) { + throw createApiError('Booking is blocked by blacklist', { + status: 403, + code: 'slot_forbidden', + }); + } if (slot.status !== SLOT_STATUS.FREE) { throw createApiError('Slot is not available', { status: 409, code: 'slot_not_available' }); } @@ -1948,6 +2033,68 @@ class MockApiClient implements ApiContract { }); } + async canCreateReview(tutorId: number): Promise<{ eligible: boolean; reason?: string | null }> { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const eligible = this.db.reviews.every( + (review) => + !(review.tutor_id === tutorId && review.student_id === currentUser.id), + ); + return eligible ? { eligible: true, reason: null } : { eligible: false, reason: 'already_reviewed' }; + }); + } + + async updateReview(payload: { + reviewId: number; + studentId: number; + rating?: number; + comment?: string; + }): Promise { + return this.withLatency(() => { + const review = this.db.reviews.find((item) => item.id === payload.reviewId); + if (!review) { + throw createApiError('Review not found', { status: 404, code: 'review_not_found' }); + } + if (review.student_id !== payload.studentId) { + throw createApiError('Forbidden', { status: 403, code: 'review_forbidden' }); + } + if (typeof payload.rating === 'number') { + review.rating = payload.rating; + } + if (payload.comment !== undefined) { + review.comment = payload.comment ?? null; + } + return clone(review); + }); + } + + async deleteReview(reviewId: number, studentId: number): Promise { + return this.withLatency(() => { + const index = this.db.reviews.findIndex((item) => item.id === reviewId); + if (index < 0) { + throw createApiError('Review not found', { status: 404, code: 'review_not_found' }); + } + const review = this.db.reviews[index]; + if (review.student_id !== studentId) { + throw createApiError('Forbidden', { status: 403, code: 'review_forbidden' }); + } + this.db.reviews.splice(index, 1); + return clone(review); + }); + } + + async reportReview(payload: { + reviewId: number; + reason: 'spam' | 'offensive' | 'untruthful' | 'other'; + comment?: string; + }): Promise<{ id: number }> { + return this.withLatency(() => { + return { + id: payload.reviewId * 10 + 1, + }; + }); + } + async listTutorReviews( tutorId: number, params?: { page?: number; pageSize?: number }, @@ -2181,6 +2328,12 @@ class MockApiClient implements ApiContract { return this.withLatency(() => { this.requireUser(payload.studentId); this.requireUser(payload.tutorId); + if (this.hasBlacklistBetween(payload.studentId, payload.tutorId)) { + throw createApiError('User is blocked', { + status: 403, + code: 'chat_forbidden', + }); + } const existing = this.db.chatThreads.find( (item) => @@ -2206,6 +2359,75 @@ class MockApiClient implements ApiContract { }); } + async listMyBlacklist(): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + return this.db.blacklist + .filter((item) => item.blocker_id === currentUser.id) + .sort( + (left, right) => + new Date(right.created_at ?? 0).getTime() - new Date(left.created_at ?? 0).getTime(), + ) + .map(clone); + }); + } + + async addToMyBlacklist(blockedId: number): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + this.requireUser(blockedId); + if (currentUser.id === blockedId) { + throw createApiError('Cannot block yourself', { + status: 422, + code: 'blacklist_self', + }); + } + const existing = this.db.blacklist.find( + (item) => item.blocker_id === currentUser.id && item.blocked_id === blockedId, + ); + if (existing) { + throw createApiError('Already blocked', { + status: 409, + code: 'conflict', + }); + } + + const created: BlacklistEntry = { + id: this.nextId('blacklist'), + blocker_id: currentUser.id, + blocked_id: blockedId, + created_at: nowIso(), + updated_at: nowIso(), + }; + this.db.blacklist.push(created); + this.db.favoriteTutors = this.db.favoriteTutors.filter( + (item) => + !( + item.student_id === currentUser.id && + item.tutor_id === blockedId + ), + ); + return clone(created); + }); + } + + async removeFromMyBlacklist(blockedId: number): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const index = this.db.blacklist.findIndex( + (item) => item.blocker_id === currentUser.id && item.blocked_id === blockedId, + ); + if (index < 0) { + throw createApiError('Blacklist entry not found', { + status: 404, + code: 'not_found', + }); + } + const [removed] = this.db.blacklist.splice(index, 1); + return clone(removed); + }); + } + async login(payload: { phone: string; password: string }): Promise { return this.withLatency(() => { const normalized = normalizePhone(payload.phone); @@ -2301,6 +2523,49 @@ class MockApiClient implements ApiContract { return this.withLatency(() => clone(this.resolveCurrentUser())); } + async changePassword(payload: { + currentPassword: string; + newPassword: string; + }): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const credential = this.db.credentials.find((item) => item.userId === currentUser.id); + if (!credential || credential.password !== payload.currentPassword) { + throw createApiError('invalid_current_password', { + status: 400, + code: 'validation_error', + }); + } + if (payload.currentPassword === payload.newPassword) { + throw createApiError('new_password_must_differ', { + status: 400, + code: 'validation_error', + }); + } + credential.password = payload.newPassword; + }); + } + + async deleteMyAccount(): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + currentUser.full_name = 'Удалённый пользователь'; + currentUser.email = null; + currentUser.phone = null; + currentUser.telegram_id = null; + this.db.credentials = this.db.credentials.filter((item) => item.userId !== currentUser.id); + + Array.from(this.db.sessions.entries()).forEach(([token, userId]) => { + if (userId === currentUser.id) { + this.db.sessions.delete(token); + } + }); + if (this.accessToken && !this.db.sessions.has(this.accessToken)) { + this.accessToken = null; + } + }); + } + async getTutorServices(tutorId: number): Promise { return this.withLatency(() => { return this.db.tutorServices @@ -2899,21 +3164,39 @@ class MockApiClient implements ApiContract { }); } - async registerPushToken(expoToken: string | null): Promise { + async registerPushToken(payload: PushTokenRegistrationPayload): Promise { return this.withLatency(() => { const currentUser = this.resolveCurrentUser(); const user = this.requireUser(currentUser.id); - (user as AuthUser & { expo_push_token?: string | null }).expo_push_token = expoToken; + (user as AuthUser & { expo_push_token?: string | null }).expo_push_token = payload.token; }); } + async deregisterPushToken(_payload: { token: string | null; device_id?: string }): Promise { + return this.withLatency(() => undefined); + } + async getNotificationSettings(): Promise { return this.withLatency(() => { const currentUser = this.resolveCurrentUser(); return ( this.db.notificationSettingsByUser[currentUser.id] ?? { - retry_interval_minutes: 5, - max_attempts: 3, + user_id: currentUser.id, + category_prefs: { + lessons: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + chat: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + access: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + payments: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + reviews: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + system: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + marketing: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + }, + quiet_hours_enabled: false, + quiet_hours_start: null, + quiet_hours_end: null, + timezone: 'UTC', + locale: 'ru', + test_mode: false, } ); }); @@ -2926,18 +3209,114 @@ class MockApiClient implements ApiContract { const currentUser = this.resolveCurrentUser(); const existing = this.db.notificationSettingsByUser[currentUser.id] ?? { - retry_interval_minutes: 5, - max_attempts: 3, + user_id: currentUser.id, + category_prefs: { + lessons: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + chat: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + access: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + payments: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + reviews: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + system: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + marketing: { enabled: true, channels: ['push', 'telegram', 'inapp'] }, + }, + quiet_hours_enabled: false, + quiet_hours_start: null, + quiet_hours_end: null, + timezone: 'UTC', + locale: 'ru', + test_mode: false, }; const next: NotificationSettings = { - retry_interval_minutes: data.retry_interval_minutes ?? existing.retry_interval_minutes, - max_attempts: data.max_attempts ?? existing.max_attempts, + ...existing, + ...data, + category_prefs: data.category_prefs + ? Object.fromEntries( + Object.entries({ ...existing.category_prefs, ...data.category_prefs }).map( + ([key, value]) => [ + key, + { + enabled: value.enabled ?? true, + channels: value.channels ?? ['push', 'telegram', 'inapp'], + }, + ], + ), + ) as NotificationSettings['category_prefs'] + : existing.category_prefs, }; this.db.notificationSettingsByUser[currentUser.id] = next; return next; }); } + async listMyNotifications(params?: { limit?: number; offset?: number }): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const all = this.db.notificationsByUser[currentUser.id] ?? []; + const limit = Math.max(1, params?.limit ?? 20); + const offset = Math.max(0, params?.offset ?? 0); + const items = all.slice(offset, offset + limit); + const unread_count = all.filter((item) => !item.read_at).length; + return { + items: items.map(clone), + total: all.length, + unread_count, + }; + }); + } + + async getUnreadNotificationsCount(): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const all = this.db.notificationsByUser[currentUser.id] ?? []; + return { unread_count: all.filter((item) => !item.read_at).length }; + }); + } + + async markNotificationRead(notificationId: number): Promise { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const items = this.db.notificationsByUser[currentUser.id] ?? []; + const idx = items.findIndex((item) => item.id === notificationId); + if (idx < 0) { + throw createApiError('Notification not found', { status: 404, code: 'not_found' }); + } + items[idx] = { + ...items[idx], + status: 'read', + read_at: nowIso(), + }; + return clone(items[idx]); + }); + } + + async markAllNotificationsRead(): Promise<{ updated_count: number }> { + return this.withLatency(() => { + const currentUser = this.resolveCurrentUser(); + const items = this.db.notificationsByUser[currentUser.id] ?? []; + let updated = 0; + const now = nowIso(); + this.db.notificationsByUser[currentUser.id] = items.map((item) => { + if (item.read_at) { + return item; + } + updated += 1; + return { + ...item, + status: 'read', + read_at: now, + }; + }); + return { updated_count: updated }; + }); + } + + async sendTestPush(): Promise<{ notification_id: number; queued: boolean }> { + return this.withLatency(() => ({ + notification_id: 999, + queued: true, + })); + } + async listReleaseNotes(environment: string): Promise { return this.withLatency(() => { const normalized = environment.trim().toLowerCase(); diff --git a/src/shared/api/types.ts b/src/shared/api/types.ts index d818816..7ed1da5 100644 --- a/src/shared/api/types.ts +++ b/src/shared/api/types.ts @@ -11,8 +11,17 @@ type TutorSummary = { id: number; name: string; rating?: number | null; + reviews_count?: number | null; experience?: string | null; description?: string | null; + min_price?: number | null; + max_price?: number | null; + is_online?: boolean; + last_seen_at?: string | null; + accepts_online?: boolean; + accepts_offline?: boolean; + services_count?: number; + has_slots_this_week?: boolean; }; type TutorSortBy = 'price' | 'rating' | 'reviews' | 'name'; @@ -25,6 +34,9 @@ type TutorsQueryParams = { minRating?: number; sortBy?: TutorSortBy; sortDir?: SortDir; + isOnlineOnly?: boolean; + hasSlotsThisWeek?: boolean; + format?: 'online' | 'offline'; page?: number; pageSize?: number; }; @@ -63,6 +75,13 @@ type Review = { created_at?: string; }; +type CanCreateReviewResponse = { + eligible: boolean; + reason?: string | null; +}; + +type ReviewReportReason = 'spam' | 'offensive' | 'untruthful' | 'other'; + type SlotStatus = 'free' | 'booked_pending' | 'scheduled' | 'cancelled'; type SlotStatusHistory = { @@ -97,6 +116,14 @@ type ChatMessage = { status?: 'sent' | 'delivered' | 'read' | 'failed'; }; +type BlacklistEntry = { + id: number; + blocker_id: number; + blocked_id: number; + created_at?: string; + updated_at?: string | null; +}; + type AuthUser = { id: number; role: 'student' | 'tutor'; @@ -248,11 +275,68 @@ type AdminNotificationSendResponse = { }; type NotificationSettings = { - retry_interval_minutes: number; - max_attempts: number; + user_id: number; + category_prefs: Record; + quiet_hours_enabled: boolean; + quiet_hours_start: string | null; + quiet_hours_end: string | null; + timezone: string; + locale: string; + test_mode: boolean; + created_at?: string | null; + updated_at?: string | null; + deleted_at?: string | null; }; -type NotificationSettingsPayload = NotificationSettings; +type NotificationSettingsPayload = Partial<{ + category_prefs: Record; + quiet_hours_enabled: boolean; + quiet_hours_start: string | null; + quiet_hours_end: string | null; + timezone: string; + locale: string; + test_mode: boolean; +}>; + +type NotificationItem = { + id: number; + event_type: string; + channel: string; + recipient_user_id: number; + slot_id?: number | null; + payload: Record; + status: string; + retry_enabled: boolean; + scheduled_at: string; + sent_at?: string | null; + delivered_at?: string | null; + read_at?: string | null; + created_at: string; + updated_at?: string | null; + deleted_at?: string | null; +}; + +type NotificationListResponse = { + items: NotificationItem[]; + total: number; + unread_count: number; +}; + +type NotificationUnreadCountResponse = { + unread_count: number; +}; + +type SendTestPushResponse = { + notification_id: number; + queued: boolean; +}; + +type PushTokenRegistrationPayload = { + token: string | null; + platform?: string; + device_id?: string; + locale?: string; +}; type TutorAnalyticsSummary = { tutor_id: number; @@ -341,10 +425,13 @@ export type { TutorDetails, Slot, Review, + CanCreateReviewResponse, + ReviewReportReason, SlotStatus, SlotStatusHistory, ChatThread, ChatMessage, + BlacklistEntry, AuthUser, AuthTokenResponse, TutorService, @@ -370,4 +457,9 @@ export type { TutorAnalyticsPriceHistory, NotificationSettings, NotificationSettingsPayload, + NotificationItem, + NotificationListResponse, + NotificationUnreadCountResponse, + SendTestPushResponse, + PushTokenRegistrationPayload, }; diff --git a/src/shared/components/ServerStatusBanner.tsx b/src/shared/components/ServerStatusBanner.tsx index f117502..a0b609d 100644 --- a/src/shared/components/ServerStatusBanner.tsx +++ b/src/shared/components/ServerStatusBanner.tsx @@ -52,6 +52,7 @@ const createStyles = (theme: ReturnType, insetTop: number) => left: 0, right: 0, zIndex: 30, + elevation: 30, paddingTop: insetTop + spacing.xs, paddingBottom: spacing.xs, paddingHorizontal: spacing.lg, @@ -66,6 +67,7 @@ const createStyles = (theme: ReturnType, insetTop: number) => left: 0, right: 0, zIndex: 30, + elevation: 30, paddingTop: insetTop + spacing.xs, paddingBottom: spacing.xs, paddingHorizontal: spacing.lg, diff --git a/src/shared/config/i18n.ts b/src/shared/config/i18n.ts index 5facb83..896b93a 100644 --- a/src/shared/config/i18n.ts +++ b/src/shared/config/i18n.ts @@ -10,6 +10,8 @@ const resources = { servicesTitle: 'Services', tutorsTitle: 'Tutors', tutorProfileTitle: 'Tutor profile', + tutorProfileUnavailable: 'Profile is unavailable', + tutorProfileUnavailableSubtitle: 'The tutor may have deleted their account or hidden the profile.', onboardingTitle: 'Choose your role', onboardingStudent: 'Student', onboardingTutor: 'Tutor', @@ -32,6 +34,12 @@ const resources = { phoneNotFoundTitle: 'Account not found', phoneNotFoundMessage: 'Create new?', signUpAction: 'Create account', + signUpConsentPrefix: 'I accept', + signUpConsentJoiner: 'and', + signUpTermsLink: 'Terms of Service', + signUpPrivacyLink: 'Privacy Policy', + signUpConsentRequired: 'Please accept Terms of Service and Privacy Policy', + signUpLegalOpenError: 'Failed to open legal page', changePhoneAction: 'Change phone', createAccount: 'Create account', haveAccount: 'I already have an account', @@ -115,7 +123,17 @@ const resources = { holdToDeleteServiceHint: 'Hold the button to confirm deletion.', holdToDeleteAction: 'Hold to delete', deleteAction: 'Delete', + editAction: 'Edit', cancelAction: 'Cancel', + reviewUpdatedSuccess: 'Review updated', + reviewDeletedSuccess: 'Review deleted', + reviewReportedSuccess: 'Review sent for moderation', + reportReasonSpam: 'Spam', + reportReasonOffensive: 'Offensive', + reportReasonUntruthful: 'Untruthful', + reportReasonOther: 'Other', + reviewActionsMenu: 'Review actions', + reviewAlreadyReported: 'Reported', validationTitle: 'Check input', priceInvalid: 'Enter a valid price', errorTitle: 'Error', @@ -197,6 +215,7 @@ const resources = { chatsEmptySubtitle: 'Book a lesson or open tutor profile to start chatting.', chatsEmptySub: 'Open a tutor profile and tap “Message”', chatNoMessagesYet: 'No messages yet', + chatBlockedAlert: 'Chat with this user is blocked.', chatSendAction: 'Send', chatMessagePlaceholder: 'Write a message...', chatBackendNotReady: 'Chat backend is not ready yet.', @@ -224,14 +243,47 @@ const resources = { settingsSectionApp: 'App', settingsSectionAccount: 'Account', settingsSectionSupport: 'Support', + settingsSectionLegal: 'LEGAL', settingsSectionPrivacy: 'Privacy', + settingsSectionDanger: 'Danger zone', + openPrivacyAction: 'Privacy Policy', + openTermsAction: 'Terms of Service', contactMissing: 'Contact not specified', languageAndTheme: 'Language and theme', + openChangePasswordAction: 'Change password', + openDeleteAccountAction: 'Delete account', + changePasswordTitle: 'Change password', + changePasswordSubtitle: 'Use the new password on your next sign-in', + changePasswordCurrentPlaceholder: 'Current password', + changePasswordNewPlaceholder: 'New password (8 characters minimum)', + changePasswordConfirmPlaceholder: 'Repeat new password', + changePasswordAction: 'Change password', + changePasswordSuccess: 'Password changed', + changePasswordCurrentRequired: 'Enter current password', + changePasswordMinLengthError: 'Minimum 8 characters', + changePasswordSameAsCurrentError: 'New password must differ from the current one', + changePasswordMismatchError: 'Passwords do not match', + changePasswordCurrentInvalid: 'Wrong current password', + deleteAccountTitle: 'Delete account', + deleteAccountWarning: 'Your profile and personal data will be permanently removed.', + deleteAccountConsequences: + 'Chats are anonymized, lesson history is retained for accounting purposes.', + deleteAccountAction: 'Delete account', + deleteAccountHoldHint: 'Hold the button to confirm deletion.', + deleteAccountHoldAction: 'Hold to delete', + deleteAccountDeletedTitle: 'Account deleted', + deleteAccountDeletedMessage: 'Thanks for being with us.', + deleteAccountShortHint: 'Permanent account deletion', roleStudent: 'Student', roleTutor: 'Tutor', roleSwitchTitle: 'Role', serviceTitle: 'Service', notificationSettingsTitle: 'Notification settings', + notificationsInboxTitle: 'Notifications inbox', + notificationsUnreadCount: 'Unread: {{count}}', + notificationMessageFallback: 'Open details', + notificationsTestPushAction: 'Send test push', + notificationsTestPushQueued: 'Test notification queued — should arrive within a minute', openNotificationSettingsAction: 'Open notification settings', retryIntervalLabel: 'Remind every … minutes', maxAttemptsLabel: 'Number of reminders', @@ -249,6 +301,8 @@ const resources = { blacklistEmpty: 'Blacklist is empty', blacklistDescription: 'These users cannot message you or see you in search.', removeAction: 'Remove', + userBlockedSuccess: 'User blocked', + userUnblockedSuccess: 'User unblocked', photosTitle: 'Photos', addPhotoAction: 'Add photo', changePhotoAction: 'Change photo', @@ -346,6 +400,8 @@ const resources = { selectSlot: 'Select a slot', bookSlot: 'Book slot', confirmBooking: 'Confirm booking', + slotAlreadyBooked: 'Slot already taken — please choose another time', + slotGoneAlert: 'This slot is no longer available. Please pick another time.', bookingNoteTitle: 'Important', bookingNoteMessage: 'After confirmation, wait for tutor response in chats and notifications.', bookingNoteText: 'The tutor will receive your request and confirm the booking shortly.', @@ -355,6 +411,11 @@ const resources = { successBookingTitle: 'Request sent!', successBookingSub: 'The tutor will receive a notification and confirm your booking soon.', writeToTutor: 'Message tutor', + rescheduleAction: 'Reschedule', + rescheduleTitle: 'Reschedule lesson', + rescheduleCurrentLabel: 'Current time', + rescheduleNewDateLabel: 'New time (YYYY-MM-DDTHH:mm)', + rescheduleSuccess: 'Reschedule request sent. Please wait for confirmation.', successReview: 'Review submitted', reviewPlaceholder: 'Write your review', ratingLabel: 'Rating', @@ -422,6 +483,13 @@ const resources = { sortReviews: 'Most reviewed', sortLabel: 'Sort by', filterRatingLabel: 'Minimum rating', + filterFormatLabel: 'Lesson format', + format_any: 'Any', + format_online: 'Online', + format_offline: 'Offline', + filterAvailabilityLabel: 'Availability', + filterOnlineNow: 'Online now', + filterHasSlotsThisWeek: 'Has slots this week', ratingAny: 'Any', priceRangeLabel: 'Price (₽/h)', priceFrom: 'From', @@ -438,6 +506,8 @@ const resources = { myFavorites: 'Favorites', tutorServices: 'Services & Prices', priceOnRequest: 'Price on request', + foundTutors_one: '{{count}} tutor', + foundTutors_other: '{{count}} tutors', reviews: 'Reviews', showAllReviews: 'Show all ({{count}})', collapseAction: 'Collapse', @@ -468,6 +538,8 @@ const resources = { servicesTitle: 'Услуги', tutorsTitle: 'Преподаватели', tutorProfileTitle: 'Профиль преподавателя', + tutorProfileUnavailable: 'Профиль недоступен', + tutorProfileUnavailableSubtitle: 'Возможно, преподаватель удалил аккаунт или скрыл профиль.', onboardingTitle: 'Выберите роль', onboardingStudent: 'Ученик', onboardingTutor: 'Репетитор', @@ -490,6 +562,12 @@ const resources = { phoneNotFoundTitle: 'Аккаунт не найден', phoneNotFoundMessage: 'Создать новый?', signUpAction: 'Создать аккаунт', + signUpConsentPrefix: 'Я принимаю', + signUpConsentJoiner: 'и', + signUpTermsLink: 'Пользовательское соглашение', + signUpPrivacyLink: 'Политику конфиденциальности', + signUpConsentRequired: 'Необходимо принять условия и политику конфиденциальности', + signUpLegalOpenError: 'Не удалось открыть страницу с правовой информацией', changePhoneAction: 'Изменить телефон', createAccount: 'Создать аккаунт', haveAccount: 'Уже есть аккаунт', @@ -575,7 +653,17 @@ const resources = { holdToDeleteServiceHint: 'Удерживайте кнопку, чтобы подтвердить удаление.', holdToDeleteAction: 'Удерживать для удаления', deleteAction: 'Удалить', + editAction: 'Редактировать', cancelAction: 'Отмена', + reviewUpdatedSuccess: 'Отзыв обновлён', + reviewDeletedSuccess: 'Отзыв удалён', + reviewReportedSuccess: 'Жалоба отправлена', + reportReasonSpam: 'Спам', + reportReasonOffensive: 'Оскорбление', + reportReasonUntruthful: 'Неправда', + reportReasonOther: 'Другое', + reviewActionsMenu: 'Действия с отзывом', + reviewAlreadyReported: 'Жалоба отправлена', validationTitle: 'Проверьте данные', priceInvalid: 'Введите корректную цену', errorTitle: 'Ошибка', @@ -658,6 +746,7 @@ const resources = { 'Запишитесь на занятие или откройте профиль преподавателя, чтобы начать общение.', chatsEmptySub: 'Откройте профиль репетитора и нажмите «Написать»', chatNoMessagesYet: 'Сообщений пока нет', + chatBlockedAlert: 'Чат с этим пользователем заблокирован.', chatSendAction: 'Отправить', chatMessagePlaceholder: 'Напишите сообщение...', chatBackendNotReady: 'Бэкенд чатов пока не готов.', @@ -685,14 +774,47 @@ const resources = { settingsSectionApp: 'ПРИЛОЖЕНИЕ', settingsSectionAccount: 'АККАУНТ', settingsSectionSupport: 'ПОДДЕРЖКА', + settingsSectionLegal: 'ПРАВОВАЯ ИНФОРМАЦИЯ', settingsSectionPrivacy: 'ПРИВАТНОСТЬ', + settingsSectionDanger: 'ОПАСНАЯ ЗОНА', + openPrivacyAction: 'Политика конфиденциальности', + openTermsAction: 'Пользовательское соглашение', contactMissing: 'Контакт не указан', languageAndTheme: 'Язык и тема', + openChangePasswordAction: 'Сменить пароль', + openDeleteAccountAction: 'Удалить аккаунт', + changePasswordTitle: 'Смена пароля', + changePasswordSubtitle: 'Используйте новый пароль при следующем входе', + changePasswordCurrentPlaceholder: 'Текущий пароль', + changePasswordNewPlaceholder: 'Новый пароль (минимум 8 символов)', + changePasswordConfirmPlaceholder: 'Повторите новый пароль', + changePasswordAction: 'Сменить пароль', + changePasswordSuccess: 'Пароль изменён', + changePasswordCurrentRequired: 'Введите текущий пароль', + changePasswordMinLengthError: 'Минимум 8 символов', + changePasswordSameAsCurrentError: 'Новый пароль должен отличаться от текущего', + changePasswordMismatchError: 'Пароли не совпадают', + changePasswordCurrentInvalid: 'Неверный текущий пароль', + deleteAccountTitle: 'Удаление аккаунта', + deleteAccountWarning: 'Профиль и личные данные будут удалены безвозвратно.', + deleteAccountConsequences: + 'Чаты обезличиваются, история уроков сохраняется в учётных целях.', + deleteAccountAction: 'Удалить аккаунт', + deleteAccountHoldHint: 'Удерживайте кнопку, чтобы подтвердить удаление.', + deleteAccountHoldAction: 'Удерживать для удаления', + deleteAccountDeletedTitle: 'Аккаунт удалён', + deleteAccountDeletedMessage: 'Спасибо, что были с нами.', + deleteAccountShortHint: 'Безвозвратное удаление аккаунта', roleStudent: 'Ученик', roleTutor: 'Репетитор', roleSwitchTitle: 'Роль', serviceTitle: 'Служебное', notificationSettingsTitle: 'Настройки уведомлений', + notificationsInboxTitle: 'Центр уведомлений', + notificationsUnreadCount: 'Непрочитанные: {{count}}', + notificationMessageFallback: 'Открыть детали', + notificationsTestPushAction: 'Отправить тестовое push', + notificationsTestPushQueued: 'Тестовое уведомление в очереди — должно прийти в течение минуты', openNotificationSettingsAction: 'Открыть настройки уведомлений', retryIntervalLabel: 'Напоминать каждые … минут', maxAttemptsLabel: 'Количество напоминаний', @@ -710,6 +832,8 @@ const resources = { blacklistEmpty: 'Черный список пуст', blacklistDescription: 'Эти пользователи не могут писать вам и видеть вас в поиске.', removeAction: 'Удалить', + userBlockedSuccess: 'Пользователь заблокирован', + userUnblockedSuccess: 'Пользователь разблокирован', photosTitle: 'Фотографии', addPhotoAction: 'Добавить фото', changePhotoAction: 'Изменить фото', @@ -808,6 +932,8 @@ const resources = { selectSlot: 'Выберите слот', bookSlot: 'Записаться', confirmBooking: 'Подтвердить запись', + slotAlreadyBooked: 'Слот уже занят — выберите другое время', + slotGoneAlert: 'Слот больше недоступен. Выберите другое время.', bookingNoteTitle: 'Важно', bookingNoteMessage: 'После подтверждения дождитесь ответа репетитора в чатах и уведомлениях.', bookingNoteText: 'Репетитор получит вашу заявку и подтвердит запись в ближайшее время.', @@ -818,6 +944,11 @@ const resources = { successBookingSub: 'Репетитор получит уведомление и подтвердит вашу запись в ближайшее время.', writeToTutor: 'Написать репетитору', + rescheduleAction: 'Перенести', + rescheduleTitle: 'Перенос занятия', + rescheduleCurrentLabel: 'Текущее время', + rescheduleNewDateLabel: 'Новое время (YYYY-MM-DDTHH:mm)', + rescheduleSuccess: 'Запрос на перенос отправлен. Ожидайте подтверждения.', successReview: 'Отзыв отправлен', reviewPlaceholder: 'Ваш отзыв', ratingLabel: 'Оценка', @@ -885,6 +1016,13 @@ const resources = { sortReviews: 'По отзывам', sortLabel: 'Сортировка', filterRatingLabel: 'Минимальный рейтинг', + filterFormatLabel: 'Формат занятий', + format_any: 'Любой', + format_online: 'Онлайн', + format_offline: 'Офлайн', + filterAvailabilityLabel: 'Доступность', + filterOnlineNow: 'Сейчас онлайн', + filterHasSlotsThisWeek: 'Есть слоты на неделе', ratingAny: 'Любой', priceRangeLabel: 'Цена (₽/ч)', priceFrom: 'От', @@ -901,6 +1039,10 @@ const resources = { myFavorites: 'Избранные', tutorServices: 'Услуги и цены', priceOnRequest: 'По договорённости', + foundTutors_one: '{{count}} репетитор', + foundTutors_few: '{{count}} репетитора', + foundTutors_many: '{{count}} репетиторов', + foundTutors_other: '{{count}} репетиторов', reviews: 'Отзывы', showAllReviews: 'Показать все ({{count}})', collapseAction: 'Свернуть', diff --git a/src/shared/constants/routes.ts b/src/shared/constants/routes.ts index fc3b6fb..59db6f9 100644 --- a/src/shared/constants/routes.ts +++ b/src/shared/constants/routes.ts @@ -18,7 +18,10 @@ const ROUTES = { SETTINGS_STACK: 'SettingsStack', APP_SETTINGS: 'AppSettings', NOTIFICATION_SETTINGS: 'NotificationSettings', + NOTIFICATIONS_INBOX: 'NotificationsInbox', BLACKLIST: 'Blacklist', + CHANGE_PASSWORD: 'ChangePassword', + DELETE_ACCOUNT: 'DeleteAccount', FEEDBACK: 'Feedback', RELEASE_NOTES: 'ReleaseNotes', ADMIN: 'Admin', @@ -40,6 +43,7 @@ const ROUTES = { PROFILE: 'Profile', STUDENT_SCHEDULE: 'StudentSchedule', STUDENT_SLOT_DETAIL: 'StudentSlotDetail', + RESCHEDULE_SLOT: 'RescheduleSlot', } as const; export { ROUTES }; diff --git a/src/shared/state/authStore.ts b/src/shared/state/authStore.ts index 7ea3e00..3fff1f0 100644 --- a/src/shared/state/authStore.ts +++ b/src/shared/state/authStore.ts @@ -1,9 +1,9 @@ import { create } from 'zustand'; -import * as SecureStore from 'expo-secure-store'; import type { Role } from '../constants/roles'; import { api } from '../api/client'; import { AUTH_TOKEN_KEY, AUTH_USER_KEY } from '../constants/config'; import type { AuthUser } from '../api/types'; +import { storage } from '../utils/storage'; import { isSessionInvalid, isTransientServerError @@ -41,8 +41,8 @@ const useAuthStore = create((set, get) => ({ if (!primaryToken && phone) { throw new Error('Auth token missing'); } - await SecureStore.setItemAsync(AUTH_TOKEN_KEY, response.access_token); - await SecureStore.setItemAsync(AUTH_USER_KEY, JSON.stringify(response.user)); + await storage.setItem(AUTH_TOKEN_KEY, response.access_token); + await storage.setItem(AUTH_USER_KEY, JSON.stringify(response.user)); api.setAccessToken(response.access_token); set({ isAuthenticated: true, @@ -62,8 +62,8 @@ const useAuthStore = create((set, get) => ({ if (shouldRetry) { try { const response = await api.login({ phone: trimmedPhone, password }); - await SecureStore.setItemAsync(AUTH_TOKEN_KEY, response.access_token); - await SecureStore.setItemAsync(AUTH_USER_KEY, JSON.stringify(response.user)); + await storage.setItem(AUTH_TOKEN_KEY, response.access_token); + await storage.setItem(AUTH_USER_KEY, JSON.stringify(response.user)); api.setAccessToken(response.access_token); set({ isAuthenticated: true, @@ -87,8 +87,8 @@ const useAuthStore = create((set, get) => ({ set({ isLoading: true, error: null }); try { const response = await api.register({ phone, password, role }); - await SecureStore.setItemAsync(AUTH_TOKEN_KEY, response.access_token); - await SecureStore.setItemAsync(AUTH_USER_KEY, JSON.stringify(response.user)); + await storage.setItem(AUTH_TOKEN_KEY, response.access_token); + await storage.setItem(AUTH_USER_KEY, JSON.stringify(response.user)); api.setAccessToken(response.access_token); set({ isAuthenticated: true, @@ -107,14 +107,14 @@ const useAuthStore = create((set, get) => ({ restore: async () => { set({ isRestoring: true, error: null }); try { - const stored = await SecureStore.getItemAsync(AUTH_TOKEN_KEY); + const stored = await storage.getItem(AUTH_TOKEN_KEY); if (!stored) { set({ isRestoring: false }); return; } api.setAccessToken(stored); const user = await api.me(); - await SecureStore.setItemAsync(AUTH_USER_KEY, JSON.stringify(user)); + await storage.setItem(AUTH_USER_KEY, JSON.stringify(user)); set({ isAuthenticated: true, role: user.role, @@ -125,8 +125,8 @@ const useAuthStore = create((set, get) => ({ } catch (error) { const message = error instanceof Error ? error.message : null; if (isSessionInvalid(message)) { - await SecureStore.deleteItemAsync(AUTH_TOKEN_KEY); - await SecureStore.deleteItemAsync(AUTH_USER_KEY); + await storage.removeItem(AUTH_TOKEN_KEY); + await storage.removeItem(AUTH_USER_KEY); api.setAccessToken(null); set({ isAuthenticated: false, @@ -138,8 +138,8 @@ const useAuthStore = create((set, get) => ({ return; } if (isTransientServerError(message)) { - const storedToken = await SecureStore.getItemAsync(AUTH_TOKEN_KEY); - const fallbackUser = parseStoredUser(await SecureStore.getItemAsync(AUTH_USER_KEY)); + const storedToken = await storage.getItem(AUTH_TOKEN_KEY); + const fallbackUser = parseStoredUser(await storage.getItem(AUTH_USER_KEY)); set({ isAuthenticated: Boolean(storedToken), role: fallbackUser?.role ?? null, @@ -153,8 +153,8 @@ const useAuthStore = create((set, get) => ({ } }, signOut: async () => { - await SecureStore.deleteItemAsync(AUTH_TOKEN_KEY); - await SecureStore.deleteItemAsync(AUTH_USER_KEY); + await storage.removeItem(AUTH_TOKEN_KEY); + await storage.removeItem(AUTH_USER_KEY); api.setAccessToken(null); set({ isAuthenticated: false, role: null, token: null, user: null, error: null }); }, @@ -165,7 +165,7 @@ const useAuthStore = create((set, get) => ({ } try { const user = await api.me(); - await SecureStore.setItemAsync(AUTH_USER_KEY, JSON.stringify(user)); + await storage.setItem(AUTH_USER_KEY, JSON.stringify(user)); set({ isAuthenticated: true, role: user.role, user }); } catch (error) { const message = error instanceof Error ? error.message : 'Unknown error'; diff --git a/src/shared/state/slotsStore.test.ts b/src/shared/state/slotsStore.test.ts index 126100a..bf891d9 100644 --- a/src/shared/state/slotsStore.test.ts +++ b/src/shared/state/slotsStore.test.ts @@ -76,6 +76,15 @@ describe('slotsStore', () => { expect(useSlotsStore.getState().error).toBe('boom'); }); + it('maps booking conflict to slot_already_booked sentinel', async () => { + apiMock.bookSlot.mockRejectedValue( + Object.assign(new Error('Slot is not available'), { status: 409, code: 'slot_not_available' }), + ); + const result = await useSlotsStore.getState().book(1, 2); + expect(result).toBeNull(); + expect(useSlotsStore.getState().error).toBe('slot_already_booked'); + }); + it('handles unknown booking error', async () => { apiMock.bookSlot.mockRejectedValue('fail'); const result = await useSlotsStore.getState().book(1, 2); diff --git a/src/shared/state/slotsStore.ts b/src/shared/state/slotsStore.ts index ccf6ae0..761ecae 100644 --- a/src/shared/state/slotsStore.ts +++ b/src/shared/state/slotsStore.ts @@ -57,7 +57,13 @@ const useSlotsStore = create((set) => ({ set({ error: null, isLoading: false }); return null; } - set({ error: message, isLoading: false }); + const status = + typeof error === 'object' && error && 'status' in error + ? Number((error as { status?: unknown }).status) + : NaN; + const displayMessage = + status === 410 ? 'slot_gone' : status === 409 ? 'slot_already_booked' : message; + set({ error: displayMessage, isLoading: false }); return null; } }, diff --git a/src/shared/utils/storage.ts b/src/shared/utils/storage.ts new file mode 100644 index 0000000..e2e9ff7 --- /dev/null +++ b/src/shared/utils/storage.ts @@ -0,0 +1,44 @@ +import * as SecureStore from 'expo-secure-store'; + +const isWeb = typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'; + +const getItem = async (key: string): Promise => { + if (isWeb) { + try { + return window.localStorage.getItem(key); + } catch { + return null; + } + } + return SecureStore.getItemAsync(key); +}; + +const setItem = async (key: string, value: string): Promise => { + if (isWeb) { + try { + window.localStorage.setItem(key, value); + } catch { + // ignore write failures (private mode / quota) + } + return; + } + await SecureStore.setItemAsync(key, value); +}; + +const removeItem = async (key: string): Promise => { + if (isWeb) { + try { + window.localStorage.removeItem(key); + } catch { + // ignore delete failures + } + return; + } + await SecureStore.deleteItemAsync(key); +}; + +export const storage = { + getItem, + setItem, + removeItem, +}; diff --git a/src/shared/utils/toast.ts b/src/shared/utils/toast.ts new file mode 100644 index 0000000..b4a9733 --- /dev/null +++ b/src/shared/utils/toast.ts @@ -0,0 +1,11 @@ +import { Alert, Platform, ToastAndroid } from 'react-native'; + +const showToast = (message: string) => { + if (Platform.OS === 'android') { + ToastAndroid.show(message, ToastAndroid.SHORT); + return; + } + Alert.alert('', message); +}; + +export { showToast }; From 712bf1b5cc83910e14eec4dd7f0304269e93c8cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80=20?= =?UTF-8?q?=D0=9F=D0=BE=D1=80=D1=8F=D0=B4=D0=B8=D0=BD?= Date: Tue, 12 May 2026 17:26:48 +0300 Subject: [PATCH 02/12] =?UTF-8?q?feat(mobile):=20student=20flows=20?= =?UTF-8?q?=E2=80=94=20tutors,=20booking,=20edge-cases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Закрывает Student Flows phase 2 (tutor enrichment + filters), phase 3 (booking race-condition + reschedule + cancel reason), edge-cases (404/410/403). - TutorsListScreen: убрана синтетика, реальные поля TutorSummary (min_price, last_seen, accepts_online/offline, reviews_count), фильтры format/availability через API, счётчик найденных - TutorProfileScreen: фото, отзывы, цены, избранное, EmptyState на 404 (tutor_not_found), block/report через useBlacklist - TutorFilterSheet: новые секции Формат/Доступность - BookingConfirmScreen: race-condition guard (409 → slot_already_booked, 410 → slot_gone с refresh + alert + idempotency через handledSlotGone) - SlotDetailScreen: поле причины отмены, кнопка Reschedule для scheduled - RescheduleSlotScreen: новый экран переноса с валидацией (пусто/в прошлом) - ChatThreadScreen: chat_blocked alert, peerBlocked composer disable - ProfileScreen: TODO phone-verify (deferred до backend OTP) - Smoke-тесты для 5 экранов --- .../calendar/screens/CalendarScreen.tsx | 8 +- .../screens/ChatThreadScreen.smoke.test.tsx | 125 ++++++++ .../chat/screens/ChatThreadScreen.tsx | 76 ++++- .../profile/screens/ProfileScreen.tsx | 1 + .../services/screens/ServiceDetailsScreen.tsx | 6 +- .../BookingConfirmScreen.smoke.test.tsx | 143 +++++++++ .../slots/screens/BookingConfirmScreen.tsx | 35 +- .../RescheduleSlotScreen.smoke.test.tsx | 248 +++++++++++++++ .../slots/screens/RescheduleSlotScreen.tsx | 231 ++++++++++++++ .../screens/SlotDetailScreen.smoke.test.tsx | 88 +++++ .../slots/screens/SlotDetailScreen.tsx | 69 +++- .../tutors/components/TutorFilterSheet.tsx | 80 +++++ src/features/tutors/hooks/useTutors.ts | 9 + .../screens/TutorProfileScreen.smoke.test.tsx | 255 +++++++++++++++ .../tutors/screens/TutorProfileScreen.tsx | 300 +++++++++++++++++- .../screens/TutorsListScreen.smoke.test.tsx | 158 +++++++-- .../tutors/screens/TutorsListScreen.tsx | 247 +++++++------- 17 files changed, 1907 insertions(+), 172 deletions(-) create mode 100644 src/features/chat/screens/ChatThreadScreen.smoke.test.tsx create mode 100644 src/features/slots/screens/RescheduleSlotScreen.smoke.test.tsx create mode 100644 src/features/slots/screens/RescheduleSlotScreen.tsx diff --git a/src/features/calendar/screens/CalendarScreen.tsx b/src/features/calendar/screens/CalendarScreen.tsx index c89a672..1074272 100644 --- a/src/features/calendar/screens/CalendarScreen.tsx +++ b/src/features/calendar/screens/CalendarScreen.tsx @@ -15,7 +15,6 @@ import Animated, { useSharedValue, withTiming } from 'react-native-reanimated'; -import PagerView from 'react-native-pager-view'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import { useTranslation } from 'react-i18next'; import Text from '../../../shared/components/Text'; @@ -24,6 +23,7 @@ import Button from '../../../shared/components/Button'; import StatusChip from '../../../shared/components/StatusChip'; import EmptyState from '../../../shared/components/EmptyState'; import PlusIcon from '../../../shared/components/icons/PlusIcon'; +import PagerViewCompat, { type PagerViewCompatHandle } from '../../../shared/components/PagerViewCompat'; import { spacing } from '../../../shared/constants/tokens'; import { useTheme } from '../../../shared/theme'; import { useAuth } from '../../auth/hooks/useAuth'; @@ -179,7 +179,7 @@ const CalendarScreen = ({ navigation }: Props) => { const [studentFilter, setStudentFilter] = useState(null); const [isRefreshing, setIsRefreshing] = useState(false); - const pagerRef = useRef(null); + const pagerRef = useRef(null); const gridScrollRefs = useRef>({}); const hasAutoScrolledToNow = useRef(false); const [gridViewportHeight, setGridViewportHeight] = useState(0); @@ -895,7 +895,7 @@ const CalendarScreen = ({ navigation }: Props) => { - handlePageChange(event.nativeEvent.position)} @@ -941,7 +941,7 @@ const CalendarScreen = ({ navigation }: Props) => { ); })} - + )} diff --git a/src/features/chat/screens/ChatThreadScreen.smoke.test.tsx b/src/features/chat/screens/ChatThreadScreen.smoke.test.tsx new file mode 100644 index 0000000..c6f7322 --- /dev/null +++ b/src/features/chat/screens/ChatThreadScreen.smoke.test.tsx @@ -0,0 +1,125 @@ +import React from 'react'; +import TestRenderer, { act } from 'react-test-renderer'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ROUTES } from '../../../shared/constants/routes'; +import ChatThreadScreen from './ChatThreadScreen'; + +const mocks = vi.hoisted(() => ({ + useAuth: vi.fn(), + useChats: vi.fn(), + useChatThread: vi.fn(), + useUserLookup: vi.fn(), + useBlacklist: vi.fn(), + showAlert: vi.fn(), + showToast: vi.fn(), +})); + +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ + t: (key: string) => key, + }), +})); + +vi.mock('../../auth/hooks/useAuth', () => ({ + useAuth: () => mocks.useAuth(), +})); + +vi.mock('../hooks/useChats', () => ({ + useChats: (...args: unknown[]) => mocks.useChats(...args), + useChatThread: (...args: unknown[]) => mocks.useChatThread(...args), +})); + +vi.mock('../../../shared/hooks/useUserLookup', () => ({ + useUserLookup: () => mocks.useUserLookup(), +})); + +vi.mock('../../settings/hooks/useBlacklist', () => ({ + useBlacklist: () => mocks.useBlacklist(), +})); + +vi.mock('../../../shared/utils/alert', () => ({ + showAlert: (...args: unknown[]) => mocks.showAlert(...args), +})); + +vi.mock('../../../shared/utils/toast', () => ({ + showToast: (...args: unknown[]) => mocks.showToast(...args), +})); + +describe('ChatThreadScreen smoke', () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.useAuth.mockReturnValue({ + effectiveRole: 'student', + user: { id: 501, role: 'student' }, + }); + mocks.useChats.mockReturnValue({ + threads: [], + ensureThread: vi.fn().mockResolvedValue({ id: 77, tutor_id: 101, student_id: 501 }), + error: null, + }); + mocks.useChatThread.mockReturnValue({ + messages: [], + isLoading: false, + isSending: false, + error: null, + refresh: vi.fn(), + send: vi.fn().mockResolvedValue(true), + }); + mocks.useUserLookup.mockReturnValue({ + users: { 101: { full_name: 'Demo Tutor' } }, + getUser: vi.fn().mockResolvedValue(undefined), + }); + mocks.useBlacklist.mockReturnValue({ + blockUser: vi.fn().mockResolvedValue(true), + unblockUser: vi.fn().mockResolvedValue(true), + isBlocked: vi.fn().mockReturnValue(false), + }); + }); + + it('shows chat_blocked alert', async () => { + mocks.useChatThread.mockReturnValue({ + messages: [], + isLoading: false, + isSending: false, + error: 'chat_blocked', + refresh: vi.fn(), + send: vi.fn().mockResolvedValue(true), + }); + + await act(async () => { + TestRenderer.create( + , + ); + }); + + expect(mocks.showAlert).toHaveBeenCalled(); + expect(mocks.showAlert.mock.calls[0][0]).toBe('errorTitle'); + expect(mocks.showAlert.mock.calls[0][1]).toBe('chatBlockedAlert'); + }); + + it('does not show blocked alert on normal thread and composer stays available', async () => { + let renderer: TestRenderer.ReactTestRenderer; + await act(async () => { + renderer = TestRenderer.create( + , + ); + }); + + expect(mocks.showAlert).not.toHaveBeenCalled(); + expect(JSON.stringify(renderer!.toJSON())).toContain('chatMessagePlaceholder'); + }); +}); diff --git a/src/features/chat/screens/ChatThreadScreen.tsx b/src/features/chat/screens/ChatThreadScreen.tsx index 9d80f86..7b282d7 100644 --- a/src/features/chat/screens/ChatThreadScreen.tsx +++ b/src/features/chat/screens/ChatThreadScreen.tsx @@ -13,6 +13,7 @@ import type { NativeStackScreenProps } from '@react-navigation/native-stack'; import Text from '../../../shared/components/Text'; import Card from '../../../shared/components/Card'; import Avatar from '../../../shared/components/Avatar'; +import ActionSheetModal from '../../../shared/components/ActionSheetModal'; import Input from '../../../shared/components/Input'; import SendIcon from '../../../shared/components/icons/SendIcon'; import BackArrowIcon from '../../../shared/components/icons/BackArrowIcon'; @@ -23,6 +24,9 @@ import { useAuth } from '../../auth/hooks/useAuth'; import { ROLES } from '../../../shared/constants/roles'; import { useChats, useChatThread } from '../hooks/useChats'; import { useUserLookup } from '../../../shared/hooks/useUserLookup'; +import { showAlert } from '../../../shared/utils/alert'; +import { showToast } from '../../../shared/utils/toast'; +import { useBlacklist } from '../../settings/hooks/useBlacklist'; type Props = NativeStackScreenProps; @@ -42,6 +46,9 @@ const normalizeChatError = (error: string | null, fallback: string) => { return null; } const lower = error.toLowerCase(); + if (lower.includes('chat_blocked')) { + return 'chat_blocked'; + } if ( lower.includes('request failed: 404') || lower.includes('chat_not_found') || @@ -61,12 +68,14 @@ const ChatThreadScreen = ({ route, navigation }: Props) => { const userId = user?.id ?? null; const [draft, setDraft] = useState(''); const [ensuredThreadId, setEnsuredThreadId] = useState(null); + const [menuVisible, setMenuVisible] = useState(false); + const { blockUser, unblockUser, isBlocked } = useBlacklist(); const { users, getUser } = useUserLookup(); const routeThreadId = route.params?.threadId ?? null; const activeThreadId = routeThreadId ?? ensuredThreadId; - const { threads, ensureThread } = useChats({ + const { threads, ensureThread, error: chatsError } = useChats({ userId, role: chatRole, enabled: typeof userId === 'number', @@ -141,6 +150,32 @@ const ChatThreadScreen = ({ route, navigation }: Props) => { return users[peerUserId]?.full_name || users[peerUserId]?.phone || `${t('userFallback')} #${peerUserId}`; }, [peerUserId, route.params?.peerName, t, users]); + const peerBlocked = typeof peerUserId === 'number' ? isBlocked(peerUserId) : false; + + useEffect(() => { + if (chatsError !== 'chat_blocked' && shownError !== 'chat_blocked') { + return; + } + showAlert(t('errorTitle'), t('chatBlockedAlert'), [ + { + text: t('back'), + onPress: () => navigation.goBack(), + }, + ]); + }, [chatsError, navigation, shownError, t]); + + const handleBlockToggle = async () => { + if (typeof peerUserId !== 'number') { + return; + } + const ok = peerBlocked ? await unblockUser(peerUserId) : await blockUser(peerUserId); + if (!ok) { + showAlert(t('errorTitle'), t('errorGeneric')); + return; + } + showToast(peerBlocked ? t('userUnblockedSuccess') : t('userBlockedSuccess')); + }; + const handleSend = async () => { const normalized = draft.trim(); if (!normalized || typeof activeThreadId !== 'number') { @@ -182,9 +217,17 @@ const ChatThreadScreen = ({ route, navigation }: Props) => { {peerName} + setMenuVisible(true)} + style={styles.menuButton} + accessibilityRole="button" + accessibilityLabel={t('chatMenuAction')} + > + ⋮ + - {shownError ? ( + {shownError && shownError !== 'chat_blocked' ? ( {shownError} void refresh()} style={styles.retryBtn} accessibilityRole="button"> @@ -260,6 +303,22 @@ const ChatThreadScreen = ({ route, navigation }: Props) => { )} + + setMenuVisible(false)} + items={[ + { + key: peerBlocked ? 'unblock' : 'block', + label: peerBlocked ? t('unblockAction') : t('blockAction'), + destructive: !peerBlocked, + onPress: () => { + void handleBlockToggle(); + }, + }, + ]} + /> ); }; @@ -286,6 +345,19 @@ const createStyles = (theme: ReturnType) => alignItems: 'center', justifyContent: 'center', }, + menuButton: { + width: 44, + height: 44, + borderRadius: 22, + alignItems: 'center', + justifyContent: 'center', + }, + menuText: { + fontSize: 20, + lineHeight: 22, + color: theme.textPrimary, + fontWeight: '700', + }, headerMeta: { flex: 1, }, diff --git a/src/features/profile/screens/ProfileScreen.tsx b/src/features/profile/screens/ProfileScreen.tsx index 644c857..6a7b091 100644 --- a/src/features/profile/screens/ProfileScreen.tsx +++ b/src/features/profile/screens/ProfileScreen.tsx @@ -13,6 +13,7 @@ import { useAuth } from '../../auth/hooks/useAuth'; import { useUserAvatar } from '../hooks/useUserAvatar'; const ProfileScreen = () => { + // Phone verification UI deferred until backend OTP endpoint and `phone_verified_at` field are available. const { t } = useTranslation(); const navigation = useNavigation(); const { diff --git a/src/features/services/screens/ServiceDetailsScreen.tsx b/src/features/services/screens/ServiceDetailsScreen.tsx index 8c8df83..8413f85 100644 --- a/src/features/services/screens/ServiceDetailsScreen.tsx +++ b/src/features/services/screens/ServiceDetailsScreen.tsx @@ -11,7 +11,6 @@ import { useWindowDimensions, } from 'react-native'; import { Image } from 'react-native'; -import PagerView from 'react-native-pager-view'; import { useTranslation } from 'react-i18next'; import { useIsFocused } from '@react-navigation/native'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'; @@ -21,6 +20,7 @@ import Input from '../../../shared/components/Input'; import MarkdownText from '../../../shared/components/MarkdownText'; import StatusChip from '../../../shared/components/StatusChip'; import HoldToConfirmModal from '../../../shared/components/HoldToConfirmModal'; +import PagerViewCompat from '../../../shared/components/PagerViewCompat'; import BackArrowIcon from '../../../shared/components/icons/BackArrowIcon'; import CheckIcon from '../../../shared/components/icons/CheckIcon'; import PencilIcon from '../../../shared/components/icons/PencilIcon'; @@ -282,7 +282,7 @@ const ServiceDetailsScreen = ({ navigation, route }: Props) => { > {isFocused ? ( - setActiveSlide(event.nativeEvent.position)} @@ -301,7 +301,7 @@ const ServiceDetailsScreen = ({ navigation, route }: Props) => { ); })} - + ) : ( diff --git a/src/features/slots/screens/BookingConfirmScreen.smoke.test.tsx b/src/features/slots/screens/BookingConfirmScreen.smoke.test.tsx index e943c18..1e93b0e 100644 --- a/src/features/slots/screens/BookingConfirmScreen.smoke.test.tsx +++ b/src/features/slots/screens/BookingConfirmScreen.smoke.test.tsx @@ -6,6 +6,8 @@ import BookingConfirmScreen from './BookingConfirmScreen'; const mocks = vi.hoisted(() => ({ book: vi.fn(), + load: vi.fn(), + showAlert: vi.fn(), navigate: vi.fn(), parentNavigate: vi.fn(), useSelectedSlot: vi.fn(), @@ -22,6 +24,15 @@ vi.mock('../hooks/useSlots', () => ({ useSelectedSlot: () => mocks.useSelectedSlot(), })); +vi.mock('../../../shared/state/slotsStore', () => ({ + useSlotsStore: (selector: (state: { load: typeof mocks.load }) => unknown) => + selector({ load: mocks.load }), +})); + +vi.mock('../../../shared/utils/alert', () => ({ + showAlert: (...args: unknown[]) => mocks.showAlert(...args), +})); + vi.mock('../../auth/hooks/useAuth', () => ({ useAuth: () => mocks.useAuth(), })); @@ -41,6 +52,7 @@ describe('BookingConfirmScreen smoke', () => { beforeEach(() => { vi.clearAllMocks(); mocks.book.mockResolvedValue(true); + mocks.load.mockResolvedValue(undefined); mocks.useAuth.mockReturnValue({ user: { id: 501, role: 'student' }, }); @@ -104,4 +116,135 @@ describe('BookingConfirmScreen smoke', () => { tutorName: 'Demo Tutor', }); }); + + it('renders translated sentinel for already booked slot', async () => { + mocks.useSelectedSlot.mockReturnValue({ + selected: { + id: 77, + tutor_id: 101, + service_id: 3, + start_at: '2026-03-01T10:00:00.000Z', + duration_min: 60, + price_per_hour: 1500, + paid: false, + status: 'booked_pending', + }, + book: mocks.book, + isLoading: false, + error: 'slot_already_booked', + }); + + let renderer: TestRenderer.ReactTestRenderer; + await act(async () => { + renderer = TestRenderer.create( + ({ navigate: mocks.parentNavigate }) } as never} + route={ + { + key: 'BookingConfirm', + name: ROUTES.BOOKING_CONFIRM, + params: { slotId: 77, tutorId: 101, tutorName: 'Demo Tutor' }, + } as never + } + />, + ); + }); + + expect(JSON.stringify(renderer!.toJSON())).toContain('slotAlreadyBooked'); + }); + + it('renders raw booking error text for non-sentinel errors', async () => { + mocks.useSelectedSlot.mockReturnValue({ + selected: { + id: 77, + tutor_id: 101, + service_id: 3, + start_at: '2026-03-01T10:00:00.000Z', + duration_min: 60, + price_per_hour: 1500, + paid: false, + status: 'booked_pending', + }, + book: mocks.book, + isLoading: false, + error: 'some_other_error', + }); + + let renderer: TestRenderer.ReactTestRenderer; + await act(async () => { + renderer = TestRenderer.create( + ({ navigate: mocks.parentNavigate }) } as never} + route={ + { + key: 'BookingConfirm', + name: ROUTES.BOOKING_CONFIRM, + params: { slotId: 77, tutorId: 101, tutorName: 'Demo Tutor' }, + } as never + } + />, + ); + }); + + expect(JSON.stringify(renderer!.toJSON())).toContain('some_other_error'); + }); + + it('handles slot_gone with refresh, alert and back once', async () => { + const goBack = vi.fn(); + mocks.useSelectedSlot.mockReturnValue({ + selected: { + id: 77, + tutor_id: 101, + service_id: 3, + start_at: '2026-03-01T10:00:00.000Z', + duration_min: 60, + price_per_hour: 1500, + paid: false, + status: 'booked_pending', + }, + book: mocks.book, + isLoading: false, + error: 'slot_gone', + }); + + const navigation = { + navigate: mocks.navigate, + goBack, + getParent: () => ({ navigate: mocks.parentNavigate }), + }; + const route = { + key: 'BookingConfirm', + name: ROUTES.BOOKING_CONFIRM, + params: { + slotId: 77, + tutorId: 101, + tutorName: 'Demo Tutor', + }, + }; + + let renderer: TestRenderer.ReactTestRenderer; + await act(async () => { + renderer = TestRenderer.create( + , + ); + }); + + expect(mocks.load).toHaveBeenCalledWith({ + tutorId: 101, + serviceId: 3, + studentId: 501, + }); + expect(mocks.showAlert).toHaveBeenCalledTimes(1); + expect(mocks.showAlert.mock.calls[0][1]).toBe('slotGoneAlert'); + + const buttons = mocks.showAlert.mock.calls[0][2] as Array<{ onPress?: () => void }> | undefined; + expect(buttons?.[0]?.onPress).toBeTypeOf('function'); + buttons?.[0]?.onPress?.(); + expect(goBack).toHaveBeenCalledTimes(1); + + await act(async () => { + renderer!.update(); + }); + expect(mocks.showAlert).toHaveBeenCalledTimes(1); + }); }); diff --git a/src/features/slots/screens/BookingConfirmScreen.tsx b/src/features/slots/screens/BookingConfirmScreen.tsx index e38b722..11e0753 100644 --- a/src/features/slots/screens/BookingConfirmScreen.tsx +++ b/src/features/slots/screens/BookingConfirmScreen.tsx @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { Modal, ScrollView, StyleSheet, View } from 'react-native'; import { useTranslation } from 'react-i18next'; import type { NativeStackScreenProps } from '@react-navigation/native-stack'; @@ -13,6 +13,8 @@ import { useSelectedSlot } from '../hooks/useSlots'; import { useAuth } from '../../auth/hooks/useAuth'; import { DEMO_STUDENT_ID } from '../../../shared/constants/ids'; import { formatSlotDate } from '../../../shared/utils/date'; +import { showAlert } from '../../../shared/utils/alert'; +import { useSlotsStore } from '../../../shared/state/slotsStore'; type Props = NativeStackScreenProps; @@ -33,14 +35,35 @@ const BookingConfirmScreen = ({ route, navigation }: Props) => { const { slotId, tutorId, tutorName } = route.params; const { user } = useAuth(); const { selected, book, isLoading, error } = useSelectedSlot(); + const refreshSlots = useSlotsStore((state) => state.load); const [success, setSuccess] = useState(false); + const [handledSlotGone, setHandledSlotGone] = useState(false); const theme = useTheme(); const styles = createStyles(theme); const studentId = user?.id ?? DEMO_STUDENT_ID; + useEffect(() => { + if (error !== 'slot_gone' || handledSlotGone) { + return; + } + setHandledSlotGone(true); + void refreshSlots({ + tutorId, + serviceId: selected?.service_id, + studentId, + }); + showAlert(t('errorTitle'), t('slotGoneAlert'), [ + { + text: t('back'), + onPress: () => navigation.goBack(), + }, + ]); + }, [error, handledSlotGone, navigation, refreshSlots, selected?.service_id, studentId, t, tutorId]); + const handleConfirm = async () => { const booked = await book(slotId, studentId); if (booked) { + setHandledSlotGone(false); setSuccess(true); } }; @@ -105,7 +128,15 @@ const BookingConfirmScreen = ({ route, navigation }: Props) => { {t('bookingNoteText')} - {error ? {error} : null} + {error ? ( + + {error === 'slot_already_booked' + ? t('slotAlreadyBooked') + : error === 'slot_gone' + ? t('slotGoneAlert') + : error} + + ) : null}