diff --git a/PROJECT.md b/PROJECT.md index 599a0df7..7a9c274f 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -213,6 +213,63 @@ themed through `useTheme()` so a host's theme applies: `onError({source, error})` reports an image the default renderer could not load (a lapsed signed URL). - `DecisionDialog` — Paper `Dialog` in a `Portal` (the host needs Paper's `Provider`). - `Timeline` — `history` and `steps`. +- Document requirements (contract request #117, 0.5.4), fed by a `getMyStatus` checklist item, so no host keeps a + document type of its own: + - `Partner/DocumentRequirementCard` (portable) — a Paper `Card` composed as Paper composes one: the title is + `requirementTitle(item)` (the rule's name for the market, else the catalogue's), `subtitle` is the host's, + then, in its `Card.Content`, `covers` (the photos taken and not sent, in order, each `{ uri, label }` with the + name a screen reader says), `note` and the rule's explanation, and `actions` + (`{ label, onPress, isDisabled?, mode?, loading?, testID? }`) as Paper `Button`s straight inside `Card.Actions`, + which keeps a `mode` given and gives the rest theirs; `loading` is the Button's own. Without `actions` it only + reads (the console). The note sits in a polite live region (`aria-live`: Android's live region, the web's + `aria-live`) that stays mounted, so a screen reader announces each next step. `Card.Actions` gets, through its + `style`, `flexWrap` and a `spacing.x2` row gap (it does not wrap by itself; its alignment and padding stay), and + its buttons are keyed by position, as `Card.Actions` itself tells them apart (a label changes as photos are taken). + - `Partner/DocumentCovers` (portable, not exported) — the card's photos: one is a `Card.Cover`; more are a + Material 3 hero carousel (a horizontal `ScrollView`: `snapToInterval` on the phone, `pagingEnabled`'s CSS scroll + snap on the web; items `spacing.x2` apart, the next peeking `spacing.x14`, Material's 8 dp and 56 dp), or all whole + side by side where the measured width fits them at Material's largest large item (twice the cover's height, which + the first cover reports, plus the gap). On the web the carousel's scrollbar shows (a mouse has no swipe). The item + it rests on is followed from `onScroll`, and a new width (rotation, resize) scrolls back to it. Each photo is an + image button (`imagebutton`; `button` + `aria-label` on the web, where react-native-web maps no role for it) named + by its `label`; it opens `DocumentViewer` full screen (Paper `Portal` + `Modal`, its height the window's between + the safe-area insets; the internal `SheetHeader` with its `global.close`) on that page, with the document's sides + (the covers' labels) when there are two. testIDs: `-covers`, `-carousel`, `-cover-`, `-viewer`, + `-viewer-header-close`, `-viewer-document`. + - `Partner/DocumentVersionList` (portable) — `item.versions` as `ListRow`s from `documentVersionRows`; they open + nothing, so no chevron. A row's description: when it was sent, the scan's catalogue label while the scan is not + `SCAN_STATUS.CLEAN` (pending, and partner 0.2.54's infected, never spelled here), the details code's label, and + `documentExpiresOn` («Expires Nov 23, 2026»): `expires_at` is a calendar day, formatted by `formatDateTime` in UTC + so no reader's zone moves it. `documentExpires` stays for the app's older list. + - `Partner/DocumentCaptureCard` (barrel only: the picker is native) — the card with the way to send it, as + `item.capture` says (`pages` 1, or 2 = the front then the back). Controlled: `{ item, subtitle?, pages = [], + onPagesChange(pages), onSend(), isSending = false, testID = 'document-requirement' }` — the host owns the pages + (the picker's assets, in order) and clears them only once its send succeeded, so a failed send keeps them; the + card never clears them. Taking a photo sends nothing: the pages show as covers; its first action, a text button, + takes a photo («Add», or «Add the front»/«Add the back»; «Retake» once every page is there, when a photo starts + the document again), and the last, «Send to review», the only one with a border (outlined) and disabled until + every page is taken, calls `onSend()`. While `isSending` every action is disabled and «Send to review» shows the + Button's `loading`. The note asks for the back (`documentAddBackPrompt`) or, every page there and nothing sending, + says the photos are not sent yet (`documentNotSent`). Every photo is taken with `DOCUMENT_CAPTURE_OPTIONS`: + `maxWidth`/`maxHeight` 5,120 (an ID-1 card's PDF417 at ISO/IEC 15415's 5 px per module over AAMVA's 0.170 mm X + needs 3,597 px at 70% of the frame; an A4/Letter page at 300 ppi, 5,011 px; both bounds or the picker does not + resize), `quality` 1, `assetRepresentationMode: 'compatible'` (iOS JPEG, not HEIC) and `conversionQuality` 1 + (Android's HEIC → JPEG). Photos only: it offers no PDF (owner, 2026-11-04). + - `ImagePicker.Avatar` `variant="sheet"` renders no control of its own; the caller opens the sheet with the + ref's `show()`, so its own Paper `Button` can sit inside a `Card.Actions`. `avatar` and `button` are as before. + Every variant: `captureOptions` (react-native-image-picker's options) are laid over the defaults (a photo, quality + 1, base64), so callers that pass none behave as before; `onChange(asset)` is called only with a photo; the sheet + ignores taps while a pick is in progress; where it would offer a single choice (the web, which has no camera + option) `show()` takes that choice. `ImagePickerAPI`'s `takePhoto(options)` / `chooseFromLibrary(options)` always + resolve, never reject: the asset, or `null` — cancelled (silently), a permission refused (the permission alert, + with Settings) or any other picker error, read from its `errorCode` (`global.somethingWentWrong` / + `global.tryAgainLater`). The library asks for no permission: image-picker 8 opens Android's Photo Picker and iOS's + PHPicker, which need none (asking blocked Android 13+ and iOS limited access); the camera keeps its permission. + - Their fixed words (`documentAddFront`, `documentAddBack`, `documentAddBackPrompt`, `documentRetake` — moved here + from the app with its values —, `documentNotSent`, `documentFront`, `documentBack`, `documentSuperseded`, + `documentExpiresOn`) live in `Translations/*.json`, in the catalogue's «Agregar»; the stories + (`Partner/DocumentRequirement.stories.js`) use the local circuit's real items, and render the capture card itself + with `pages` for the photo states. - `Partner/viewModel.js` (barrel/portable: `PartnerViewModel`, because `statusLabel` is the Order one): the key is the package's `statusLabelKey(group, value)` resolved with `localized`; a value outside the vocabulary, or a key the registered catalogue lacks, renders the raw value. Each kind's group is read diff --git a/packages/components/package-lock.json b/packages/components/package-lock.json index 0321dfff..093f6fb4 100644 --- a/packages/components/package-lock.json +++ b/packages/components/package-lock.json @@ -1,15 +1,15 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.5.3", + "version": "0.5.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.5.3", + "version": "0.5.4", "license": "ISC", "devDependencies": { - "@jmstechnologiesinc/partner": "0.2.48", + "@jmstechnologiesinc/partner": "0.2.54", "prettier": "^2.5.1", "rimraf": "^3.0.2" }, @@ -19,7 +19,7 @@ "@jmstechnologiesinc/commons": "^0.1.5", "@jmstechnologiesinc/order": "^0.6.0", "@jmstechnologiesinc/order-narration": "^0.0.9", - "@jmstechnologiesinc/partner": "^0.2.47", + "@jmstechnologiesinc/partner": "^0.2.54", "@jmstechnologiesinc/react-native-google-places-autocomplete": "^2.4.14", "@jmstechnologiesinc/react-native-image-blur-loading": "^1.2.5", "@jmstechnologiesinc/react-native-paper": "^5.12.12", @@ -1267,9 +1267,9 @@ } }, "node_modules/@jmstechnologiesinc/partner": { - "version": "0.2.48", - "resolved": "https://npm.pkg.github.com/download/@jmstechnologiesinc/partner/0.2.48/1e770b470a95642089fd06190f732f39b4faabdc", - "integrity": "sha512-VI5+m3Vlxt2D7Z/A0OWhGji+0XjG7rxKQtQ1008vYhwFCchdTdU6P/D0JcpfYQMLhCZSnmatHAvoUZcPf8n0zQ==", + "version": "0.2.54", + "resolved": "https://npm.pkg.github.com/download/@jmstechnologiesinc/partner/0.2.54/9932111297bbe3c3efa290abaa4894ca001b9917", + "integrity": "sha512-pejgHzr0q34Ssq1c5cgDeF4Ge+/Z8Mqcini0vR4mjb3eGJApE8j60yXXx6L/bIS+MApyhAeoilOIAAOCUH/zmw==", "license": "ISC" }, "node_modules/@jmstechnologiesinc/react-native-components": { diff --git a/packages/components/package.json b/packages/components/package.json index 788d5a7b..6e6afe64 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -1,6 +1,6 @@ { "name": "@jmstechnologiesinc/react-native-components", - "version": "0.5.3", + "version": "0.5.4", "description": "Biblioteca de componentes de interfaz compartida por las aplicaciones de Daxir.", "author": "yerloveraaa ", "homepage": "https://github.com/jmstechnologiesinc/react-native-components#readme", @@ -26,7 +26,7 @@ "url": "https://github.com/jmstechnologiesinc/react-native-components/issues" }, "devDependencies": { - "@jmstechnologiesinc/partner": "0.2.48", + "@jmstechnologiesinc/partner": "0.2.54", "prettier": "^2.5.1", "rimraf": "^3.0.2" }, @@ -36,7 +36,7 @@ "@jmstechnologiesinc/commons": "^0.1.5", "@jmstechnologiesinc/order": "^0.6.0", "@jmstechnologiesinc/order-narration": "^0.0.9", - "@jmstechnologiesinc/partner": "^0.2.47", + "@jmstechnologiesinc/partner": "^0.2.54", "@jmstechnologiesinc/react-native-google-places-autocomplete": "^2.4.14", "@jmstechnologiesinc/react-native-image-blur-loading": "^1.2.5", "@jmstechnologiesinc/react-native-paper": "^5.12.12", diff --git a/packages/components/src/ImagePicker/ImagePickerAPI.js b/packages/components/src/ImagePicker/ImagePickerAPI.js index c490e71f..25e13f84 100644 --- a/packages/components/src/ImagePicker/ImagePickerAPI.js +++ b/packages/components/src/ImagePicker/ImagePickerAPI.js @@ -1,7 +1,28 @@ import { Linking, Alert } from 'react-native'; import { launchCamera, launchImageLibrary } from 'react-native-image-picker'; -import { checkAndAskForPermissionCamara, checkAndAskForPermissionMediaLibrary } from './utils'; +import { RESULTS } from 'react-native-permissions'; +import { checkAndAskForPermissionCamara } from './utils'; +// What every pick asked for before a caller could pass options of its own (`takePhoto(options)`): a photo at full +// quality, with its base64. A caller's options are laid over these. +const DEFAULT_OPTIONS = Object.freeze({ mediaType: 'photo', quality: 1, includeBase64: true }); + +// react-native-image-picker's `errorCode` for a pick its platform refused for want of a permission; its other codes +// (`camera_unavailable`, `others`) are failures a setting cannot fix. +const PERMISSION_ERROR = 'permission'; + +// The answers of a camera permission request that Settings can change; anything else (`unavailable`, a request that +// threw) is a failure, not a refusal. +const PERMISSION_REFUSED = Object.freeze([RESULTS.DENIED, RESULTS.BLOCKED]); + +/** + * Takes one photo with the camera or picks one from the library. + * + * `takePhoto(options)` and `chooseFromLibrary(options)` always resolve, and never reject, so a caller never waits on + * a pick that ended: with the picked asset, or with `null` when nothing was picked — cancelled (silently), refused a + * permission (the permission alert, with a way to Settings) or failed (the generic failure alert). `options` are + * react-native-image-picker's, laid over `DEFAULT_OPTIONS`. + */ class ImagePickerAPI { constructor({ titlePermissionCamera, @@ -10,6 +31,9 @@ class ImagePickerAPI { descriptionPermissionPhotos, cancelPermission, settingPermission, + titleFailure, + descriptionFailure, + closeFailure, }) { this.titlePermissionCamera = titlePermissionCamera; this.titlePermissionPhotos = titlePermissionPhotos; @@ -17,6 +41,9 @@ class ImagePickerAPI { this.descriptionPermissionPhotos = descriptionPermissionPhotos; this.cancelPermission = cancelPermission; this.settingPermission = settingPermission; + this.titleFailure = titleFailure; + this.descriptionFailure = descriptionFailure; + this.closeFailure = closeFailure; } catchPermissionStatusCamara() { @@ -24,15 +51,8 @@ class ImagePickerAPI { this.titlePermissionCamera, this.descriptionPermissionCamera, [ - { - text: this.cancelPermission, - onPress: () => console.log('Cancel Pressed'), - style: 'cancel', - }, - { - text: this.settingPermission, - onPress: () => Linking.openSettings(), - }, + { text: this.cancelPermission, style: 'cancel' }, + { text: this.settingPermission, onPress: () => Linking.openSettings() }, ], { cancelable: false } ); @@ -43,65 +63,56 @@ class ImagePickerAPI { this.titlePermissionPhotos, this.descriptionPermissionPhotos, [ - { - text: this.cancelPermission, - onPress: () => console.log('Cancel Pressed'), - style: 'cancel', - }, - { - text: this.settingPermission, - onPress: () => Linking.openSettings(), - }, + { text: this.cancelPermission, style: 'cancel' }, + { text: this.settingPermission, onPress: () => Linking.openSettings() }, ], { cancelable: false } ); } - takePhoto() { - return new Promise((resolve) => { - checkAndAskForPermissionCamara() - .then(() => launchCamera({ mediaType: 'photo', quality: 1, includeBase64: true })) - .then((response) => { - if (response.didCancel) { - console.log('User cancelled image picker'); - } else if (response.error) { - Alert(response.error); - console.log('ImagePicker Error: ', response.error); - } else if (response.customButton) { - console.log('User tapped custom button: ', response.customButton); - } else { - resolve(response?.assets[0]); - } - }) - .catch(() => this.catchPermissionStatusCamara()); - }); + // The button is named here: without one Android's alert falls back to an English «OK». + alertFailure() { + Alert.alert(this.titleFailure, this.descriptionFailure, [{ text: this.closeFailure }]); + } + + /** The asset `launcher` picked, or null once the user has been told why there is none. */ + launch(launcher, options, alertPermission) { + return launcher({ ...DEFAULT_OPTIONS, ...options }) + .then((response) => { + if (response.didCancel) return null; + if (response.errorCode === PERMISSION_ERROR) { + alertPermission(); + return null; + } + if (response.errorCode) { + this.alertFailure(); + return null; + } + return response.assets?.[0] ?? null; + }) + .catch(() => { + this.alertFailure(); + return null; + }); + } + + takePhoto(options) { + return checkAndAskForPermissionCamara().then( + () => this.launch(launchCamera, options, () => this.catchPermissionStatusCamara()), + (status) => { + if (PERMISSION_REFUSED.includes(status)) this.catchPermissionStatusCamara(); + else this.alertFailure(); + return null; + } + ); } - chooseFromLibrary() { - return new Promise((resolve) => { - checkAndAskForPermissionMediaLibrary() - .then(() => - launchImageLibrary({ - mediaType: 'photo', - quality: 1, - includeBase64: true, - allowsMultipleSelection: true, - }) - ) - .then((response) => { - if (response.didCancel) { - console.log('User cancelled image picker'); - } else if (response.error) { - Alert(response.error); - console.log('ImagePicker Error: ', response.error); - } else if (response.customButton) { - console.log('User tapped custom button: ', response.customButton); - } else { - resolve(response?.assets[0]); - } - }) - .catch(() => this.catchPermissionStatusPhotos()); - }); + // No permission is asked: react-native-image-picker 8 opens Android's Photo Picker and iOS's PHPicker, which run + // outside the app and hand back only what the user picks. Asking for the library permission blocked the pick where + // it cannot be granted: Android 13+ (the app declares no READ_EXTERNAL_STORAGE) and iOS limited access. The picker + // still reports `permission` where its platform checks one (iOS with `includeExtra`). + chooseFromLibrary(options) { + return this.launch(launchImageLibrary, options, () => this.catchPermissionStatusPhotos()); } } diff --git a/packages/components/src/ImagePicker/ImagePickerAvatar.js b/packages/components/src/ImagePicker/ImagePickerAvatar.js index d262e22d..9254faf4 100644 --- a/packages/components/src/ImagePicker/ImagePickerAvatar.js +++ b/packages/components/src/ImagePicker/ImagePickerAvatar.js @@ -1,4 +1,4 @@ -import React, { useEffect, useRef } from 'react'; +import React, { forwardRef, useEffect, useImperativeHandle, useRef } from 'react'; import { moderateScale } from '@jmstechnologiesinc/react-native-size-matters'; import { Avatar as PaperAvatar, MD3LightTheme, TouchableRipple, List } from '@jmstechnologiesinc/react-native-paper'; @@ -19,19 +19,32 @@ export const IMAGE_PICKER_ACTIONS = { cancel: 'cancel', }; -const Avatar = ({ - photo, - onChange, - onRemove, - title, - variant = 'avatar', - icon = 'account', - size = moderateScale(150), - options = [], - isDisabled, -}) => { +/** + * The photo picker: a camera / library / cancel sheet, opened by an avatar (`variant="avatar"`), by a text button + * (`variant="button"`), or, with `variant="sheet"`, by the caller's own control through the ref's `show()` — so a + * caller can put a Paper `Button` straight inside its own container (a `Card.Actions` styles only its direct children). + * Where the sheet would offer a single choice (the web, which has no camera option, without extra `options`), opening + * it takes that choice instead. `onChange(asset)` gets each photo picked; a pick cancelled or refused calls nothing. + * `captureOptions` (react-native-image-picker's options, e.g. a maximum size) are laid over the picker's defaults. + */ +const Avatar = forwardRef(function Avatar( + { + photo, + onChange, + onRemove, + title, + variant = 'avatar', + icon = 'account', + size = moderateScale(150), + options = [], + isDisabled, + captureOptions, + }, + ref +) { const imagePickerRef = useRef(); const actionSheetRef = useRef(); + const launching = useRef(false); const insets = useSafeAreaInsets(); @@ -43,24 +56,34 @@ const Avatar = ({ descriptionPermissionPhotos: localized('enablePhotosPermission'), cancelPermission: localized('global.cancel'), settingPermission: localized('goToSettings'), + titleFailure: localized('global.somethingWentWrong'), + descriptionFailure: localized('global.tryAgainLater'), + closeFailure: localized('global.close'), }); }, []); - const showActionSheet = () => { - actionSheetRef.current.show(); + // The sheet stays open after a pick cancelled or refused, so another source can be chosen. The pick ends after the + // picker's own screen closes, by when the caller may have taken this sheet away. + const launch = async (pick) => { + launching.current = true; + try { + const asset = await pick(); + if (asset) { + onChange(asset); + actionSheetRef.current?.hide(); + } + } finally { + launching.current = false; + } }; - const onActionDone = async (value) => { + const onActionDone = (value) => { + // A tap while the picker is still opening would launch it a second time. + if (launching.current) return; if (value === IMAGE_PICKER_ACTIONS.launchCamera) { - imagePickerRef.current.takePhoto().then((rep) => { - onChange(rep); - actionSheetRef.current.hide(); - }); + launch(() => imagePickerRef.current.takePhoto(captureOptions)); } else if (value === IMAGE_PICKER_ACTIONS.launchImageLibrary) { - imagePickerRef.current.chooseFromLibrary().then((rep) => { - onChange(rep); - actionSheetRef.current.hide(); - }); + launch(() => imagePickerRef.current.chooseFromLibrary(captureOptions)); } else if (value === IMAGE_PICKER_ACTIONS.removeImage) { onRemove(); actionSheetRef.current.hide(); @@ -87,30 +110,48 @@ const Avatar = ({ ...options, { title: localized('cancel'), value: IMAGE_PICKER_ACTIONS.cancel, icon: 'cancel' }, ]; + const choices = OPTIONS.filter(({ value }) => value !== IMAGE_PICKER_ACTIONS.cancel); + + const showActionSheet = () => { + if (choices.length === 1) onActionDone(choices[0].value); + else actionSheetRef.current.show(); + }; + + // Recreated on every render: `show()` may launch the picker itself, and must hand the photo to the current + // `onChange`, not the first render's. + useImperativeHandle(ref, () => ({ show: showActionSheet })); + + // What opens the sheet: the avatar, the text button, or nothing of its own (`sheet`: the caller's control, `show()`). + let trigger = null; + if (variant === 'avatar') { + trigger = ( + + + {photo ? ( + + ) : ( + + )} + + + ); + } else if (variant !== 'sheet') { + trigger = ( + + ); + } return ( <> - {variant === 'avatar' ? ( - - - {photo ? ( - - ) : ( - - )} - - - ) : ( - - )} + {trigger} ); -}; +}); export default Avatar; diff --git a/packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js b/packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js new file mode 100644 index 00000000..aee5e099 --- /dev/null +++ b/packages/components/src/ImagePicker/__tests__/ImagePickerAPI.test.js @@ -0,0 +1,126 @@ +import { Alert, Linking } from 'react-native'; +import { launchCamera, launchImageLibrary } from 'react-native-image-picker'; +import { PERMISSIONS, RESULTS, request } from 'react-native-permissions'; + +import ImagePickerAPI from '../ImagePickerAPI'; + +// Both are native modules. The permissions library publishes its own jest mock (every request granted unless a test +// says otherwise); the picker publishes none, so its two launchers are stand-ins that answer what a test gives them. +jest.mock('react-native-permissions', () => require('react-native-permissions/mock')); +jest.mock('react-native-image-picker', () => ({ launchCamera: jest.fn(), launchImageLibrary: jest.fn() })); + +const LABELS = { + titlePermissionCamera: 'Camera permission denied', + titlePermissionPhotos: 'Allow access to photos', + descriptionPermissionCamera: 'Enable the camera permission', + descriptionPermissionPhotos: 'Enable the photos permission', + cancelPermission: 'Cancel', + settingPermission: 'Go to settings', + titleFailure: 'Something went wrong', + descriptionFailure: 'Please try again later.', + closeFailure: 'Close', +}; +const ASSET = { uri: 'file:///photo.jpg', base64: 'photo' }; +const DEFAULTS = { mediaType: 'photo', quality: 1, includeBase64: true }; + +const picker = () => new ImagePickerAPI(LABELS); + +let alert; +beforeEach(() => { + jest.clearAllMocks(); + alert = jest.spyOn(Alert, 'alert').mockImplementation(() => {}); + launchCamera.mockResolvedValue({ assets: [ASSET] }); + launchImageLibrary.mockResolvedValue({ assets: [ASSET] }); +}); + +afterEach(() => alert.mockRestore()); + +describe('ImagePickerAPI.chooseFromLibrary', () => { + it('opens the library without asking for any permission, and resolves the photo picked', async () => { + await expect(picker().chooseFromLibrary()).resolves.toBe(ASSET); + expect(request).not.toHaveBeenCalled(); + expect(launchImageLibrary).toHaveBeenCalledWith(DEFAULTS); + expect(Alert.alert).not.toHaveBeenCalled(); + }); + + it("lays the caller's capture options over the defaults", async () => { + const options = { maxWidth: 5120, maxHeight: 5120, assetRepresentationMode: 'compatible' }; + await picker().chooseFromLibrary(options); + expect(launchImageLibrary).toHaveBeenCalledWith({ ...DEFAULTS, ...options }); + }); + + it('resolves nothing, and says nothing, when the pick is cancelled', async () => { + launchImageLibrary.mockResolvedValue({ didCancel: true }); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).not.toHaveBeenCalled(); + }); + + it("shows the photos permission alert only for the picker's permission error", async () => { + launchImageLibrary.mockResolvedValue({ errorCode: 'permission' }); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith( + LABELS.titlePermissionPhotos, + LABELS.descriptionPermissionPhotos, + expect.any(Array), + { cancelable: false } + ); + }); + + it('shows the generic failure when the library cannot open', async () => { + launchImageLibrary.mockResolvedValue({ errorCode: 'others', errorMessage: 'Activity error' }); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, [ + { text: LABELS.closeFailure }, + ]); + }); + + it('resolves nothing, after the generic failure, when the launcher itself throws', async () => { + launchImageLibrary.mockRejectedValue(new Error('no native module')); + await expect(picker().chooseFromLibrary()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, expect.any(Array)); + }); +}); + +describe('ImagePickerAPI.takePhoto', () => { + it('asks for the camera permission, then takes the photo with the capture options', async () => { + const options = { maxWidth: 5120, maxHeight: 5120, conversionQuality: 1 }; + await expect(picker().takePhoto(options)).resolves.toBe(ASSET); + expect(request).toHaveBeenCalledWith(PERMISSIONS.IOS.CAMERA); + expect(launchCamera).toHaveBeenCalledWith({ ...DEFAULTS, ...options }); + }); + + it.each([RESULTS.DENIED, RESULTS.BLOCKED])( + 'shows the camera permission alert, with a way to Settings, when the permission is %s', + async (status) => { + request.mockResolvedValueOnce(status); + const openSettings = jest.spyOn(Linking, 'openSettings').mockImplementation(() => Promise.resolve()); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(launchCamera).not.toHaveBeenCalled(); + const [title, description, buttons] = Alert.alert.mock.calls[0]; + expect([title, description]).toEqual([LABELS.titlePermissionCamera, LABELS.descriptionPermissionCamera]); + expect(buttons.map(({ text }) => text)).toEqual([LABELS.cancelPermission, LABELS.settingPermission]); + buttons[1].onPress(); + expect(openSettings).toHaveBeenCalled(); + openSettings.mockRestore(); + } + ); + + it('shows the generic failure, not the permission alert, when the device has no camera', async () => { + request.mockResolvedValueOnce(RESULTS.UNAVAILABLE); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, expect.any(Array)); + }); + + it('shows the generic failure for the camera_unavailable error code', async () => { + launchCamera.mockResolvedValue({ errorCode: 'camera_unavailable' }); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(Alert.alert).toHaveBeenCalledTimes(1); + expect(Alert.alert).toHaveBeenCalledWith(LABELS.titleFailure, LABELS.descriptionFailure, expect.any(Array)); + }); + + it('resolves nothing, and says nothing, when the photo is cancelled', async () => { + launchCamera.mockResolvedValue({ didCancel: true }); + await expect(picker().takePhoto()).resolves.toBeNull(); + expect(Alert.alert).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js b/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js new file mode 100644 index 00000000..6c324c9d --- /dev/null +++ b/packages/components/src/ImagePicker/__tests__/ImagePickerAvatar.test.js @@ -0,0 +1,144 @@ +import React, { createRef } from 'react'; +import { Platform } from 'react-native'; +import renderer, { act } from 'react-test-renderer'; + +import { MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; + +import ButtonWrapper from '../../ButtonWrapper/ButtonWrapper'; +import { localized } from '../../Localization/Localization'; +import ImagePickerAvatar from '../ImagePickerAvatar'; + +// The sheet is native; a stand-in records being opened and closed through the same ref the picker uses. +const mockSheet = { shown: 0, hidden: 0 }; +jest.mock('react-native-actions-sheet', () => { + const React = require('react'); + const ActionSheet = React.forwardRef(({ children }, ref) => { + React.useImperativeHandle(ref, () => ({ + show: () => { + mockSheet.shown += 1; + }, + hide: () => { + mockSheet.hidden += 1; + }, + })); + return children; + }); + return { __esModule: true, default: ActionSheet }; +}); +// Insets of zero, and the context Paper's Provider reads them from (the library's own jest mock ships as TypeScript +// in the root install, which this config does not transform). +jest.mock('react-native-safe-area-context', () => { + const React = require('react'); + const insets = { top: 0, bottom: 0, left: 0, right: 0 }; + const frame = { x: 0, y: 0, width: 390, height: 844 }; + return { + SafeAreaProvider: ({ children }) => children, + SafeAreaInsetsContext: React.createContext(insets), + SafeAreaFrameContext: React.createContext(frame), + useSafeAreaInsets: () => insets, + useSafeAreaFrame: () => frame, + initialWindowMetrics: { insets, frame }, + }; +}); +// The camera and the library are ImagePickerAPI's (its own suite); here each pick answers what a test gives it. +const mockPicks = { takePhoto: jest.fn(), chooseFromLibrary: jest.fn() }; +jest.mock('../ImagePickerAPI', () => jest.fn().mockImplementation(() => mockPicks)); + +jest.useFakeTimers(); + +const mounted = []; +const render = (element) => { + let tree; + act(() => { + tree = renderer.create({element}); + }); + mounted.push(tree); + return tree; +}; + +beforeEach(() => { + mockSheet.shown = 0; + mockSheet.hidden = 0; + mockPicks.takePhoto.mockReset(); + mockPicks.chooseFromLibrary.mockReset(); +}); + +afterEach(() => { + act(() => { + mounted.splice(0).forEach((tree) => tree.unmount()); + jest.runOnlyPendingTimers(); + }); + jest.restoreAllMocks(); +}); + +const optionOf = (tree, title) => + tree.root.findAll((node) => node.props.title === title && typeof node.props.onPress === 'function')[0]; +const ASSET = { uri: 'file:///photo.jpg' }; + +describe('ImagePicker.Avatar', () => { + it('opens its sheet from its own text button, as before', () => { + const tree = render(); + const [button] = tree.root.findAllByType(ButtonWrapper); + act(() => button.props.onPress()); + expect(mockSheet.shown).toBe(1); + }); + + it('with variant="sheet", renders no control of its own and opens through the ref', () => { + const ref = createRef(); + const tree = render(); + expect(tree.root.findAllByType(ButtonWrapper)).toHaveLength(0); + act(() => ref.current.show()); + expect(mockSheet.shown).toBe(1); + }); + + it("hands each photo picked to onChange with the caller's capture options, and closes the sheet", async () => { + const onChange = jest.fn(); + const captureOptions = { maxWidth: 5120, maxHeight: 5120 }; + mockPicks.chooseFromLibrary.mockResolvedValue(ASSET); + const tree = render(); + await act(async () => optionOf(tree, localized('chooseFromLibrary')).props.onPress()); + expect(mockPicks.chooseFromLibrary).toHaveBeenCalledWith(captureOptions); + expect(onChange).toHaveBeenCalledWith(ASSET); + expect(mockSheet.hidden).toBe(1); + }); + + it('calls nothing and keeps the sheet open when a pick ends without a photo', async () => { + const onChange = jest.fn(); + mockPicks.takePhoto.mockResolvedValue(null); + const tree = render(); + await act(async () => optionOf(tree, localized('takePhoto')).props.onPress()); + expect(onChange).not.toHaveBeenCalled(); + expect(mockSheet.hidden).toBe(0); + }); + + it('ignores the sheet while a pick is in progress, and listens again once it ends', async () => { + let finish; + mockPicks.takePhoto.mockReturnValue( + new Promise((resolve) => { + finish = resolve; + }) + ); + mockPicks.chooseFromLibrary.mockResolvedValue(ASSET); + const tree = render(); + act(() => optionOf(tree, localized('takePhoto')).props.onPress()); + act(() => optionOf(tree, localized('takePhoto')).props.onPress()); + act(() => optionOf(tree, localized('chooseFromLibrary')).props.onPress()); + expect(mockPicks.takePhoto).toHaveBeenCalledTimes(1); + expect(mockPicks.chooseFromLibrary).not.toHaveBeenCalled(); + + await act(async () => finish(null)); + await act(async () => optionOf(tree, localized('chooseFromLibrary')).props.onPress()); + expect(mockPicks.chooseFromLibrary).toHaveBeenCalledTimes(1); + }); + + it('on the web, where the library is the only choice, opens it straight from show()', async () => { + jest.replaceProperty(Platform, 'OS', 'web'); + const onChange = jest.fn(); + mockPicks.chooseFromLibrary.mockResolvedValue(ASSET); + const ref = createRef(); + render(); + await act(async () => ref.current.show()); + expect(mockSheet.shown).toBe(0); + expect(onChange).toHaveBeenCalledWith(ASSET); + }); +}); diff --git a/packages/components/src/Localization/Translations/en.json b/packages/components/src/Localization/Translations/en.json index a5862c47..d0982667 100644 --- a/packages/components/src/Localization/Translations/en.json +++ b/packages/components/src/Localization/Translations/en.json @@ -803,7 +803,16 @@ "accountDeactivatedWithDate": "Your account will be deleted on", "contactSupportForHelp": "Contact support for help.", "documentExpires": "Expires", + "documentExpiresOn": "Expires %{date}", "documentExpired": "Expired", + "documentAddFront": "Add the front", + "documentAddBack": "Add the back", + "documentAddBackPrompt": "Now take a photo of the back of the document.", + "documentRetake": "Retake", + "documentNotSent": "These photos are not sent yet. Tap «Send to review».", + "documentFront": "Front", + "documentBack": "Back", + "documentSuperseded": "Superseded", "documentExpiryDate": "Expiry date", "documentExpiryInvalid": "Enter a valid future date (MM/DD/YYYY).", "reactivate": "Reactivate", diff --git a/packages/components/src/Localization/Translations/es.json b/packages/components/src/Localization/Translations/es.json index 41a583ce..548b69d5 100644 --- a/packages/components/src/Localization/Translations/es.json +++ b/packages/components/src/Localization/Translations/es.json @@ -803,7 +803,16 @@ "accountDeactivatedWithDate": "Tu cuenta se eliminará el", "contactSupportForHelp": "Contacta a soporte para más información.", "documentExpires": "Vence", + "documentExpiresOn": "Vence el %{date}", "documentExpired": "Vencido", + "documentAddFront": "Agregar el anverso", + "documentAddBack": "Agregar el reverso", + "documentAddBackPrompt": "Ahora toma una foto del reverso del documento.", + "documentRetake": "Repetir", + "documentNotSent": "Estas fotos aún no se han enviado. Toca «Enviar a revisión».", + "documentFront": "Anverso", + "documentBack": "Reverso", + "documentSuperseded": "Sustituido", "documentExpiryDate": "Fecha de vencimiento", "documentExpiryInvalid": "Ingresa una fecha válida y futura (MM/DD/YYYY).", "reactivate": "Reactivar", diff --git a/packages/components/src/Partner/DocumentCaptureCard.js b/packages/components/src/Partner/DocumentCaptureCard.js new file mode 100644 index 00000000..d13610a8 --- /dev/null +++ b/packages/components/src/Partner/DocumentCaptureCard.js @@ -0,0 +1,117 @@ +import React, { useRef } from 'react'; + +import ImagePickerAvatar from '../ImagePicker/ImagePickerAvatar'; +import { localized } from '../Localization/Localization'; +import DocumentRequirementCard from './DocumentRequirementCard'; + +/** + * How every document photo is taken (react-native-image-picker options), whatever the document: the highest + * resolution any of them needs, at full quality, as JPEG. + * - 5,120 px on the long side at most. A barcode on an ID-1 card (the AAMVA driver's licence PDF417) reads at + * ISO/IEC 15415's 5 px per module over AAMVA's minimum module of 0.170 mm: 3,597 px for a card filling 70% of the + * frame; an A4 or Letter page at 300 ppi needs 5,011 px. The highest applies. The picker resizes only when both + * bounds are set, and never enlarges. + * - quality 1: no standard backs a lower one, and ICAO asks for no visible compression artefacts. + * - `compatible`: iOS hands a JPEG instead of a HEIC, which the server does not take (JPEG and PNG only); + * `conversionQuality` 1: Android converts a HEIC to JPEG at full quality. + */ +const DOCUMENT_CAPTURE_OPTIONS = Object.freeze({ + maxWidth: 5120, + maxHeight: 5120, + quality: 1, + assetRepresentationMode: 'compatible', + conversionQuality: 1, +}); + +/** + * Contract request #117: a document requirement's card with the way to send it, as the server says one version of it + * is taken (`item.capture`, K-32): one photo, or the front and then the back (§9.8.1 step 1). Photos only (owner, + * 2026-11-04): the card offers no PDF. Taking a photo sends nothing (owner, 2026-11-04): the pages taken show as the + * card's covers (both sides in a carousel, owner 2026-11-04), and «Send to review» sends them once every page is + * there. The card only sends (owner, 2026-11-04): it says nothing of where the requirement stands, which its versions + * and its row in the lists say. The photo sheet is the library's picker, opened by the card's own button + * (`variant="sheet"`). Not portable: the picker is native. + * + * Controlled: the host owns `pages` (the picker's assets, in order) and gets each change through + * `onPagesChange(pages)`. «Send to review» calls `onSend()`; the card never clears the pages itself, so a send that + * fails keeps them, and the host clears them once its send succeeds. While `isSending`, every action is disabled and + * «Send to review» shows its progress. + * + * @param {{item: object, subtitle?: ?string, pages?: Array, onPagesChange: (pages: Array) => void, + * onSend: () => void, isSending?: boolean, testID?: string}} props + */ +const DocumentCaptureCard = ({ + item, + subtitle, + pages = [], + onPagesChange, + onSend, + isSending = false, + testID = 'document-requirement', +}) => { + const pickerRef = useRef(); + const pageCount = item.capture?.pages === 2 ? 2 : 1; + const twoSided = pageCount === 2; + const complete = pages.length === pageCount; + + // A photo taken once every page is there starts the document again: that is how a wrong one is replaced. + const take = (photo) => onPagesChange(pages.length < pageCount ? [...pages, photo] : [photo]); + + // What a screen reader names each photo: the front and the back of a two-sided document, else the document. + const covers = pages.map((page, index) => { + let label = localized('global.document'); + if (twoSided) label = localized(index === 0 ? 'documentFront' : 'documentBack'); + return { uri: page.uri, label }; + }); + + // Once every page is there the photo button starts the document again, so it says so. + let takeLabel = localized('add'); + if (complete) takeLabel = localized('documentRetake'); + else if (twoSided) takeLabel = localized(pages.length === 1 ? 'documentAddBack' : 'documentAddFront'); + + // What to do now: the back, or — every page there and nothing sending — that the photos are not sent yet. + let note = null; + if (complete && !isSending) note = localized('documentNotSent'); + else if (twoSided && pages.length === 1) note = localized('documentAddBackPrompt'); + + // The way to take a photo stays, a text button; the main action, sending, is last and the only one with a border + // (owner, 2026-11-04); it waits, disabled, until every page is taken. + const actions = [ + { + label: takeLabel, + onPress: () => pickerRef.current?.show(), + isDisabled: isSending, + mode: 'text', + testID: `${testID}-add`, + }, + { + label: localized('sendToReview'), + onPress: onSend, + mode: 'outlined', + isDisabled: isSending || !complete, + loading: isSending, + testID: `${testID}-send`, + }, + ]; + + return ( + <> + + + + ); +}; + +export default DocumentCaptureCard; diff --git a/packages/components/src/Partner/DocumentCovers.js b/packages/components/src/Partner/DocumentCovers.js new file mode 100644 index 00000000..f198081b --- /dev/null +++ b/packages/components/src/Partner/DocumentCovers.js @@ -0,0 +1,164 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { ScrollView, View, useWindowDimensions } from 'react-native'; +import { useSafeAreaInsets } from 'react-native-safe-area-context'; + +import { Card, Modal, Portal, TouchableRipple, useTheme } from '@jmstechnologiesinc/react-native-paper'; + +import { accessibilityProps, isWeb } from '../accessibility'; +import DocumentViewer from '../DocumentViewer/DocumentViewer'; +import SheetHeader from '../Layout/SheetHeader'; +import { localized } from '../Localization/Localization'; + +/** + * Two covers or more: a Material 3 hero carousel, one large item with the next one peeking, or all of them whole, side + * by side, where the width fits them at Material's largest large item (twice as wide as the cover is tall, the + * cover's height measured from the first one). + * + * The carousel's measures are Material's (material-components-android carousel): it snaps to an item, items stand + * 8 dp apart, and the item that peeks is a small item of at most 56 dp (`m3_carousel_small_item_size_max`), here the + * theme's `spacing.x2` and `spacing.x14`. The large item is what the measured width leaves. Paper has no carousel, so + * a horizontal ScrollView snaps item by item: on iOS and Android by `snapToInterval`, which overrides `pagingEnabled` + * there, and on the web by `pagingEnabled`, the one snapping prop react-native-web implements (CSS scroll snap). On + * the web its scrollbar shows: a mouse has no swipe, and the scrollbar is its way to the next item. The item it rests + * on is followed from the scroll position, so a new width (a rotation, a resized window) scrolls back to it. + */ +const CoverCarousel = ({ covers, renderCover, testID }) => { + const { spacing } = useTheme(); + const [width, setWidth] = useState(0); + const [coverHeight, setCoverHeight] = useState(0); + const carouselRef = useRef(null); + const restingItem = useRef(0); + + const gap = spacing.x2; + // Until the carousel is measured its items are 0 wide; their height is the cover's, so nothing below moves. + const itemWidth = Math.max(0, width - spacing.x14 - gap); + const interval = itemWidth + gap; + // An item rests where it starts, but the scroll view stops at its end, where the last item shows whole and the + // one before it peeks. + const lastOffset = Math.max(0, covers.length * interval - gap - width); + const restOf = (index) => Math.min(index * interval, lastOffset); + const itemAt = (offset) => + covers.reduce( + (nearest, _cover, index) => + Math.abs(restOf(index) - offset) < Math.abs(restOf(nearest) - offset) ? index : nearest, + 0 + ); + + const largeItemMax = 2 * coverHeight; + const fitWhole = coverHeight > 0 && width >= covers.length * largeItemMax + (covers.length - 1) * gap; + + // `restOf` changes only with these two. + useEffect(() => { + carouselRef.current?.scrollTo({ x: restOf(restingItem.current), animated: false }); + }, [interval, lastOffset]); + + const measureCover = (event) => setCoverHeight(event.nativeEvent.layout.height); + const coversAt = (coverWidth) => + covers.map((cover, index) => + renderCover(cover, index, { + style: { width: coverWidth }, + onLayout: index === 0 ? measureCover : undefined, + }) + ); + + return ( + setWidth(event.nativeEvent.layout.width)} testID={`${testID}-covers`}> + {fitWhole ? ( + {coversAt(largeItemMax)} + ) : ( + { + restingItem.current = itemAt(event.nativeEvent.contentOffset.x); + }} + // Every event (16 ms or less turns throttling off on the phone): the handler only notes an index. + // react-native-web, without it, reports only the first one. + scrollEventThrottle={16} + contentContainerStyle={{ gap }} + testID={`${testID}-carousel`} + > + {coversAt(itemWidth)} + + )} + + ); +}; + +/** + * The photos of a document the partner has taken and not sent yet (DocumentRequirementCard `covers`), in order: one is + * the card's cover; more are a carousel, or side by side where they fit (CoverCarousel). Each photo is an image button + * a screen reader names by its `label`: it opens the library's DocumentViewer full screen, on that page, to check it + * before sending (zoom, rotation, and the sides of a two-page document, named by their labels). + * + * @param {{covers: Array<{uri: string, label: string}>, testID: string}} props + */ +const DocumentCovers = ({ covers, testID }) => { + const { colors } = useTheme(); + const window = useWindowDimensions(); + const insets = useSafeAreaInsets(); + const [viewing, setViewing] = useState(false); + const [page, setPage] = useState(0); + + const open = (index) => { + setPage(index); + setViewing(true); + }; + const close = () => setViewing(false); + const shown = covers[page] ?? covers[0]; + const sides = covers.length > 1 ? covers.map(({ label }, index) => ({ value: String(index), label })) : undefined; + + // react-native-web gives `imagebutton` no web role; there an image that opens is a button named by its label. + const renderCover = ({ uri, label }, index, props) => ( + open(index)} + {...accessibilityProps({ role: isWeb() ? 'button' : 'imagebutton', label })} + {...props} + testID={`${testID}-cover-${index}`} + > + + + ); + + return ( + <> + {covers.length < 2 ? ( + covers.map((cover, index) => renderCover(cover, index)) + ) : ( + + )} + + + + setPage(Number(value))} + testID={`${testID}-viewer-document`} + /> + + + + ); +}; + +export default DocumentCovers; diff --git a/packages/components/src/Partner/DocumentRequirement.stories.js b/packages/components/src/Partner/DocumentRequirement.stories.js new file mode 100644 index 00000000..d32b7a76 --- /dev/null +++ b/packages/components/src/Partner/DocumentRequirement.stories.js @@ -0,0 +1,225 @@ +import React, { useState } from 'react'; +import { ScrollView, View } from 'react-native'; + +import { EN, ES, formatVehicleValue, vehicleValueParts } from '@jmstechnologiesinc/partner'; +import { MD3LightTheme } from '@jmstechnologiesinc/react-native-paper'; + +import { localized, registerFlatCatalog, setI18nConfig } from '../Localization/Localization'; +import DocumentCaptureCard from './DocumentCaptureCard'; +import DocumentRequirementCard from './DocumentRequirementCard'; +import DocumentVersionList from './DocumentVersionList'; +import { requirementTitle } from './viewModel'; + +// The library's own words, then the `partner.*` catalogue, which belongs to `@jmstechnologiesinc/partner` (R2): a +// host sets both up once, as here. +setI18nConfig(); +registerFlatCatalog({ en: EN, es: ES }); + +export default { + title: 'packages/Partner/DocumentRequirement', +}; + +// Real items, nothing made up: the two drivers of the local circuit (US → US-MA, Boxford), as getMyStatus answers +// their checklist (read from the emulators on 2026-11-03), with the five fields of contract request #117 filled from +// what the server holds for them — the composed rules persisted beside their state (`label`, `explanation`), the +// server's capture table, and their versions in `…/partner_documents`. +const HONDA = { vehicleType: 'car', color: 'BLK', make: 'Honda', model: 'Accord', licensePlate: '123456' }; +const CIVIC = { vehicleType: 'car', color: 'BGE', make: 'cifid', model: 'civic', licensePlate: '123445' }; +const ONE_PAGE = { pages: 1, pdf: true }; + +const US_LICENCE = { + en: "The valid driver's license of whoever drives a motor vehicle. Not asked for a store's own deliveries: the store's declaration stands in for it there.", + es: 'La licencia de conducir vigente de quien conduce un vehículo de motor. No se pide para las entregas de una tienda: ahí la sustituye la declaración de la tienda.', +}; +const US_INSURANCE = { + en: "The valid insurance policy of each motor vehicle they work with. Not asked for a store's own deliveries: the store's declaration stands in for it there.", + es: 'La póliza de seguro vigente de cada vehículo de motor con el que trabaja. No se pide para las entregas de una tienda: ahí la sustituye la declaración de la tienda.', +}; + +const LICENCE_NOTHING_SENT = { + id: 'driver_license', + requirementKey: 'driver_license', + bucket: 'currently_due', + cause: 'missing', + evidence: 'document', + explanation: US_LICENCE, + documentType: 'driver_licence', + capture: { pages: 2, pdf: true }, + versions: [], +}; + +const INSPECTION_DUE_SOON = { + id: 'lhmawbh2rCiMmzcoY5Om.vehicle_inspection', + requirementKey: 'vehicle_inspection', + vehicleId: 'lhmawbh2rCiMmzcoY5Om', + vehicle: HONDA, + bucket: 'eventually_due', + cause: 'expiring_within_notice', + evidence: 'document', + expiresAt: 1795478400000, + label: { en: 'Annual vehicle safety inspection', es: 'Inspección anual de seguridad del vehículo' }, + explanation: { + en: 'The current Massachusetts safety inspection of each vehicle they drive passengers in, done every year at an RMV-licensed station.', + es: 'La inspección de seguridad vigente de Massachusetts de cada vehículo con el que lleva pasajeros, hecha cada año en una estación autorizada por el RMV.', + }, + documentType: 'state_safety_inspection_report', + capture: ONE_PAGE, + versions: [ + { + versionId: '6WoqFfmibiFIgv6Ko6nh', + cause: 'satisfied', + verification: { status: 'verified' }, + expires_at: '2026-11-23', + scan: { status: 'clean' }, + submittedTime: 1793249082020, + }, + ], +}; + +const INSURANCE_WITH_HISTORY = { + id: 'lhmawbh2rCiMmzcoY5Om.vehicle_insurance', + requirementKey: 'vehicle_insurance', + vehicleId: 'lhmawbh2rCiMmzcoY5Om', + vehicle: HONDA, + bucket: null, + cause: 'satisfied', + evidence: 'document', + expiresAt: 1893456000000, + explanation: US_INSURANCE, + documentType: 'insurance', + capture: ONE_PAGE, + versions: [ + { + versionId: '3p9wgxM49qaibuOFC9KT', + cause: 'satisfied', + verification: { status: 'verified' }, + expires_at: '2029-12-31', + scan: { status: 'clean' }, + submittedTime: 1793249519602, + }, + { + versionId: 'VjNKwrsZCIt1uEiYJS1F', + verification: { status: 'unverified', details_code: 'document_not_readable' }, + scan: { status: 'clean' }, + supersededBy: '3p9wgxM49qaibuOFC9KT', + submittedTime: 1793249040678, + }, + ], +}; + +const INSURANCE_JUST_SENT = { + id: 'krb6NkPk2R9LLukYD1bj.vehicle_insurance', + requirementKey: 'vehicle_insurance', + vehicleId: 'krb6NkPk2R9LLukYD1bj', + vehicle: CIVIC, + bucket: 'currently_due', + cause: 'missing', + evidence: 'document', + explanation: US_INSURANCE, + documentType: 'insurance', + capture: ONE_PAGE, + versions: [ + { + versionId: 'kOFizggUFsNliTITk3fW', + cause: 'pending_review', + verification: { status: 'pending' }, + scan: { status: 'pending' }, + submittedTime: 1793675729952, + }, + ], +}; + +const DPU_CERTIFICATE = { + id: 'ma_dpu_clearance_certificate', + requirementKey: 'ma_dpu_clearance_certificate', + bucket: null, + cause: 'satisfied', + evidence: 'document', + expiresAt: 1893456000000, + label: { en: 'DPU background check clearance certificate', es: 'Certificado de antecedentes del DPU' }, + explanation: { + en: 'The certificate the Massachusetts Department of Public Utilities issues once it has checked their criminal, sex offender and driving records.', + es: 'El certificado que emite el Departamento de Servicios Públicos de Massachusetts tras revisar sus antecedentes penales, de delitos sexuales y de manejo.', + }, + documentType: 'ma_dpu_clearance_certificate', + capture: ONE_PAGE, + versions: [ + { + versionId: 'yzu7Y8MIxmmwb7jHFseI', + cause: 'satisfied', + verification: { status: 'verified' }, + expires_at: '2029-12-31', + scan: { status: 'clean' }, + submittedTime: 1793249092768, + }, + ], +}; + +// The subtitle is the host's: the app names the vehicle, and not where the requirement stands (the card only sends; +// owner, 2026-11-04). The stories say it the same way. +const subtitleOf = (item) => (item.vehicle ? formatVehicleValue(vehicleValueParts(item.vehicle), localized) : null); + +const pane = { padding: MD3LightTheme.spacing.x4, gap: MD3LightTheme.spacing.x2 }; + +// The app's document screen: the card with its capture, then the versions. The screen owns the pages taken; a story +// sends nothing, so «Send to review» clears them as the app does once its send succeeds. +const Screen = ({ item }) => { + const [pages, setPages] = useState([]); + return ( + + setPages([])} + /> + + + ); +}; + +export const LicenceNothingSent = () => ; + +export const InspectionDueSoonMassachusetts = () => ; + +export const InsuranceWithHistory = () => ; + +export const InsuranceJustSent = () => ; + +export const MassachusettsOnlyCertificate = () => ; + +// What the console shows of it («Así lo ve el socio»): the card reads, nothing is sent. +export const ReadOnlyInTheConsole = () => ( + + + + +); + +// What the partner has taken shows on the card before anything is sent (owner, 2026-11-04): the front waiting for the +// back, «Send to review» still disabled; both sides ready to send, in a carousel, with the note that they are not sent +// yet; and both sides on their way. The pages are the partner's own photos, which a story does not have: empty ones +// show where they go. +const PHOTO = { uri: 'data:,' }; + +const Taken = ({ pages, isSending = false }) => ( + + {}} + onSend={() => {}} + isSending={isSending} + /> + +); + +export const LicenceFrontTaken = () => ; + +export const LicenceReadyToSend = () => ; + +export const LicenceSending = () => ; diff --git a/packages/components/src/Partner/DocumentRequirementCard.js b/packages/components/src/Partner/DocumentRequirementCard.js new file mode 100644 index 00000000..bdf1a005 --- /dev/null +++ b/packages/components/src/Partner/DocumentRequirementCard.js @@ -0,0 +1,101 @@ +import React from 'react'; +import { View } from 'react-native'; + +import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; +import { Avatar, Button, Card, Text, useTheme } from '@jmstechnologiesinc/react-native-paper'; + +import DocumentCovers from './DocumentCovers'; +import { requirementTitle, ruleText } from './viewModel'; + +/** + * Contract request #117: one requirement of the partner as the server states it (a `getMyStatus` checklist item), in + * a Paper `Card` composed the way Paper composes one, with no style of its own: + * - the title is the composed rule's name for the partner's market, else the catalogue's (`requirementTitle`); + * - `subtitle` is what the host names it by besides its title (its vehicle, in the host's words); + * - the content is `covers`, the photos the partner has taken and not sent yet, in order (the front, then the back), + * each with the `label` a screen reader names it by (one is the cover, more a carousel: DocumentCovers), then + * `note` (what to do now, announced by a screen reader when it changes) and the rule's plain explanation for the + * market. The photos sit in the Card.Content, not beside it: Card.Content takes its top padding from a Card.Cover or + * Card.Title just above it, so one carousel between them would leave the text against the photos; + * - `actions` are `{ label, onPress, isDisabled?, mode?, loading?, testID? }`, Paper `Button`s straight inside + * `Card.Actions`, which keeps a `mode` given (a Paper Button mode) and gives the rest its own (the first outlined, + * the next contained); `loading` is the Button's progress indicator. Actions that do not fit on one line wrap. + * Without `actions` (the console showing what the partner sees) the card only reads. + * + * @param {{item: object, subtitle?: ?string, covers?: Array<{uri: string, label: string}>, note?: ?string, + * actions?: Array<{label: string, onPress: () => void, isDisabled?: boolean, mode?: string, loading?: boolean, + * testID?: string}>, testID?: string}} props + */ +const DocumentRequirementCard = ({ + item, + subtitle, + covers = [], + note, + actions = [], + testID = 'document-requirement', +}) => { + const { spacing } = useTheme(); + const explanation = ruleText(item.explanation); + const hasCovers = covers.length > 0; + let explanationSpacing; + if (note) explanationSpacing = { marginTop: spacing.x2 }; + else if (hasCovers) explanationSpacing = { marginTop: spacing.x4 }; + return ( + + } + /> + {hasCovers || note || explanation ? ( + + {hasCovers ? : null} + {/* A polite live region (Android's, and `aria-live` on the web) announces the next step. It stays + mounted, empty without a note: a region that appears together with its text is not announced + on the web. */} + + {/* After the photos, the space Card.Content puts after a cover; between texts, the note's. */} + {note ? ( + + {note} + + ) : null} + + {explanation ? ( + + {explanation} + + ) : null} + + ) : null} + {actions.length > 0 ? ( + // Card.Actions lays its buttons in one row that does not wrap, so a long label pushed the others out + // of the card; its own alignment and padding stay. Card.Actions tells its buttons apart by position (the + // first is outlined), and so does the key: a label changes as photos are taken, and keyed by it the + // button would remount. + + {actions.map(({ label, onPress, isDisabled, mode, loading, testID: actionTestID }, index) => ( + + ))} + + ) : null} + + ); +}; + +export default DocumentRequirementCard; diff --git a/packages/components/src/Partner/DocumentVersionList.js b/packages/components/src/Partner/DocumentVersionList.js new file mode 100644 index 00000000..e002cf3c --- /dev/null +++ b/packages/components/src/Partner/DocumentVersionList.js @@ -0,0 +1,36 @@ +import React from 'react'; +import { View } from 'react-native'; + +import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; + +import ListRow from '../ListRow/ListRow'; +import { documentVersionRows } from './viewModel'; + +/** + * Contract request #117: a document requirement's versions as the server sent them (`checklistItem.versions`, newest + * first), one `ListRow` (a Paper `List.Item`) each: when it was sent is the title, its state and what the server says + * of it the description. The rows are the view model's (`documentVersionRows`) and open nothing, so they carry no + * chevron. No versions, no list. + * + * @param {{versions: ?Array, accessibilityLabel: string, testID?: string}} props + * `accessibilityLabel` names the list (the requirement it belongs to); each row's testID is `-` + */ +const DocumentVersionList = ({ versions, accessibilityLabel, testID = 'document-versions' }) => { + const rows = documentVersionRows(versions); + if (rows.length === 0) return null; + return ( + + {rows.map(({ key, title, description }) => ( + + ))} + + ); +}; + +export default DocumentVersionList; diff --git a/packages/components/src/Partner/__tests__/documentRequirement.test.js b/packages/components/src/Partner/__tests__/documentRequirement.test.js new file mode 100644 index 00000000..78a4f8bf --- /dev/null +++ b/packages/components/src/Partner/__tests__/documentRequirement.test.js @@ -0,0 +1,413 @@ +import React, { useState } from 'react'; +import { Platform, ScrollView } from 'react-native'; +import renderer, { act } from 'react-test-renderer'; + +import { EN, ES } from '@jmstechnologiesinc/partner'; +import { Card, MD3LightTheme, Provider } from '@jmstechnologiesinc/react-native-paper'; + +import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization'; +import DocumentCaptureCard from '../DocumentCaptureCard'; +import DocumentRequirementCard from '../DocumentRequirementCard'; +import DocumentVersionList from '../DocumentVersionList'; +import { requirementTitle } from '../viewModel'; + +// The photo sheet is the native picker; here it is a stand-in that records being opened and the capture options it was +// given, and hands back the photo a test gives it, through the same ref and `onChange` the card uses. +const mockPicker = { shown: 0, take: null, captureOptions: null }; +jest.mock('../../ImagePicker/ImagePickerAvatar', () => { + const React = require('react'); + const Sheet = React.forwardRef(({ onChange, captureOptions }, ref) => { + React.useImperativeHandle(ref, () => ({ + show: () => { + mockPicker.shown += 1; + }, + })); + mockPicker.take = onChange; + mockPicker.captureOptions = captureOptions; + return null; + }); + return { __esModule: true, default: Sheet }; +}); + +// Paper animates on timers; fake ones, and unmounting after each test, keep those animations from firing after the +// environment is torn down. +jest.useFakeTimers(); + +const mounted = []; +const render = (element) => { + let tree; + act(() => { + tree = renderer.create({element}); + }); + mounted.push(tree); + return tree; +}; + +beforeAll(() => { + setI18nConfig(); + registerFlatCatalog({ en: EN, es: ES }); +}); + +beforeEach(() => { + mockPicker.shown = 0; + mockPicker.take = null; + mockPicker.captureOptions = null; +}); + +afterEach(() => { + act(() => { + mounted.splice(0).forEach((tree) => tree.unmount()); + jest.runOnlyPendingTimers(); + }); + jest.restoreAllMocks(); +}); + +// Every string a host Text renders, in order. +const textsOf = (tree) => + tree.root + .findAll((node) => node.type === 'Text' && typeof node.props.children === 'string') + .map((node) => node.props.children); +const buttonOf = (tree, testID) => + tree.root.findAll((node) => node.props.testID === testID && typeof node.props.onPress === 'function')[0]; +const hasTestID = (tree, testID) => tree.root.findAll((node) => node.props.testID === testID).length > 0; +const propsOf = (tree, testID) => tree.root.findAll((node) => node.props.testID === testID)[0].props; +const press = (tree, testID) => act(() => buttonOf(tree, testID).props.onPress()); +const take = (photo) => act(() => mockPicker.take(photo)); + +const INSPECTION = { + id: 'car1.vehicle_inspection', + requirementKey: 'vehicle_inspection', + vehicleId: 'car1', + bucket: 'eventually_due', + cause: 'expiring_within_notice', + evidence: 'document', + label: { en: 'Annual vehicle safety inspection', es: 'Inspección anual de seguridad del vehículo' }, + explanation: { en: 'The current Massachusetts safety inspection.', es: 'La inspección de seguridad vigente.' }, + documentType: 'state_safety_inspection_report', + capture: { pages: 1, pdf: true }, + versions: [], +}; +const LICENCE = { + id: 'driver_license', + requirementKey: 'driver_license', + bucket: 'currently_due', + cause: 'missing', + evidence: 'document', + documentType: 'driver_licence', + capture: { pages: 2, pdf: true }, + versions: [], +}; +const AT = 1793249082020; +const BOTH_SIDES = [ + { uri: 'file:///front.jpg', label: 'Front' }, + { uri: 'file:///back.jpg', label: 'Back' }, +]; +// The cover's height, as the first cover reports it (Card.Cover's own), and the width the covers are laid out in. +const COVER_HEIGHT = 195; +const layOut = (tree, width) => + act(() => { + propsOf(tree, 'document-requirement-cover-0').onLayout({ nativeEvent: { layout: { height: COVER_HEIGHT } } }); + propsOf(tree, 'document-requirement-covers').onLayout({ nativeEvent: { layout: { width } } }); + }); + +describe('requirementTitle', () => { + it("is the rule's own name for the market, in the reader's language", () => { + expect(requirementTitle(INSPECTION)).toBe('Annual vehicle safety inspection'); + }); + + it("is the catalogue's name when the rule has none", () => { + expect(requirementTitle(LICENCE)).toBe(EN['partner.requirement.driver_license']); + expect(requirementTitle({ requirementKey: 'car1.vehicle_insurance' })).toBe( + EN['partner.requirement.vehicle_insurance'] + ); + }); +}); + +describe('DocumentRequirementCard', () => { + it("reads the rule's name, the host's subtitle and the rule's explanation, and offers nothing by itself", () => { + const tree = render(); + expect(textsOf(tree)).toEqual([ + 'Annual vehicle safety inspection', + 'Black Honda Accord · 123456', + 'The current Massachusetts safety inspection.', + ]); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); + expect(tree.root.findAll((node) => typeof node.props.onPress === 'function')).toHaveLength(0); + }); + + it('shows a photo taken, named for a screen reader, what to do next, and the actions the host gives it', () => { + const onPress = jest.fn(); + const tree = render( + + ); + expect(propsOf(tree, 'document-requirement-cover-0')).toEqual( + expect.objectContaining({ accessibilityRole: 'imagebutton', accessibilityLabel: 'Front' }) + ); + // One photo is the cover, not a carousel. + expect(hasTestID(tree, 'document-requirement-covers')).toBe(false); + expect(textsOf(tree)).toContain('Now take a photo of the back of your licence.'); + press(tree, 'cancel'); + expect(onPress).toHaveBeenCalledTimes(1); + }); + + it('keeps a polite live region for the note, so a screen reader announces each next step', () => { + const liveRegionOf = (tree) => tree.root.findAll((node) => node.props['aria-live'] === 'polite')[0]; + // Mounted before there is anything to say: a region that appears together with its text is not announced. + const empty = render(); + expect(liveRegionOf(empty)).toBeDefined(); + expect(hasTestID(empty, 'document-requirement-note')).toBe(false); + + const tree = render(); + const note = liveRegionOf(tree).findAll((node) => node.props.testID === 'document-requirement-note'); + expect(note.length).toBeGreaterThan(0); + }); + + it("lets its actions wrap, keeping Card.Actions' own alignment, and shows an action in progress", () => { + const tree = render( + + ); + expect(tree.root.findByType(Card.Actions).props.style).toEqual({ + flexWrap: 'wrap', + rowGap: MD3LightTheme.spacing.x2, + }); + expect(buttonOf(tree, 'send').props).toEqual(expect.objectContaining({ loading: true, disabled: true })); + }); + + it('shows both sides as a carousel that snaps item by item, the next one peeking (Material 3 hero)', () => { + const { spacing } = MD3LightTheme; + const tree = render(); + expect(propsOf(tree, 'document-requirement-carousel')).toEqual( + expect.objectContaining({ + horizontal: true, + pagingEnabled: true, + decelerationRate: 'fast', + showsHorizontalScrollIndicator: false, + }) + ); + expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Front'); + expect(propsOf(tree, 'document-requirement-cover-1').accessibilityLabel).toBe('Back'); + + layOut(tree, 400); + // The large item is what the width leaves after the small item that peeks (56 dp) and the gap (8 dp). + const itemWidth = 400 - spacing.x14 - spacing.x2; + expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: itemWidth }); + expect(propsOf(tree, 'document-requirement-carousel').snapToInterval).toBe(itemWidth + spacing.x2); + expect(propsOf(tree, 'document-requirement-carousel').contentContainerStyle).toEqual({ gap: spacing.x2 }); + }); + + it('scrolls back to the item it rested on when its width changes', () => { + const { spacing } = MD3LightTheme; + const tree = render(); + layOut(tree, 400); + // At its end the carousel rests with the back whole and the front peeking. + const interval = 400 - spacing.x14; + act(() => + propsOf(tree, 'document-requirement-carousel').onScroll({ + nativeEvent: { contentOffset: { x: 2 * interval - spacing.x2 - 400 } }, + }) + ); + const { scrollTo } = tree.root.findAllByType(ScrollView)[0].instance; + scrollTo.mockClear(); + + layOut(tree, 600); + const wider = 600 - spacing.x14; + expect(scrollTo).toHaveBeenCalledWith({ x: 2 * wider - spacing.x2 - 600, animated: false }); + }); + + it('shows both sides whole, without a carousel, where they fit at the largest large item', () => { + const { spacing } = MD3LightTheme; + const tree = render(); + // Twice as wide as the cover is tall, each, and the gap between them. + layOut(tree, 2 * (2 * COVER_HEIGHT) + spacing.x2); + expect(hasTestID(tree, 'document-requirement-carousel')).toBe(false); + expect(propsOf(tree, 'document-requirement-cover-0').style).toEqual({ width: 2 * COVER_HEIGHT }); + expect(propsOf(tree, 'document-requirement-cover-1').style).toEqual({ width: 2 * COVER_HEIGHT }); + }); + + it('on the web, shows the scrollbar and makes each photo a button named by its label', () => { + jest.replaceProperty(Platform, 'OS', 'web'); + const tree = render(); + expect(propsOf(tree, 'document-requirement-carousel').showsHorizontalScrollIndicator).toBe(true); + expect(propsOf(tree, 'document-requirement-cover-1')).toEqual( + expect.objectContaining({ role: 'button', 'aria-label': 'Back' }) + ); + }); + + it('opens a photo full screen in the document viewer, on its side, before anything is sent', () => { + const tree = render(); + expect(propsOf(tree, 'document-requirement-viewer').visible).toBe(false); + + press(tree, 'document-requirement-cover-1'); + expect(propsOf(tree, 'document-requirement-viewer').visible).toBe(true); + const viewer = propsOf(tree, 'document-requirement-viewer-document'); + expect(viewer.source).toEqual({ uri: 'file:///back.jpg' }); + expect(viewer.sides.map(({ label }) => label)).toEqual(['Front', 'Back']); + + act(() => viewer.onSideChange(viewer.sides[0].value)); + expect(propsOf(tree, 'document-requirement-viewer-document').source).toEqual({ uri: 'file:///front.jpg' }); + + press(tree, 'document-requirement-viewer-header-close'); + expect(propsOf(tree, 'document-requirement-viewer').visible).toBe(false); + }); + + it('opens a one-page document with no sides to choose', () => { + const tree = render( + + ); + press(tree, 'document-requirement-cover-0'); + const viewer = propsOf(tree, 'document-requirement-viewer-document'); + expect(viewer.source).toEqual({ uri: 'file:///page.jpg' }); + expect(viewer.sides).toBeUndefined(); + }); +}); + +describe('DocumentVersionList', () => { + it('lists one row per version, and nothing without versions', () => { + const versions = [{ versionId: 'v1', verification: { status: 'verified' }, submittedTime: AT }]; + const tree = render(); + expect(hasTestID(tree, 'document-versions-v1')).toBe(true); + expect( + hasTestID(render(), 'document-versions') + ).toBe(false); + }); +}); + +// A host as the app is one: it owns the pages, hands them to its send, and clears them only once the send succeeded. +const host = { clear: null }; +const Host = ({ item, onSend = jest.fn(), isSending = false }) => { + const [pages, setPages] = useState([]); + host.clear = () => setPages([]); + return ( + onSend(pages)} + isSending={isSending} + /> + ); +}; +const NOT_SENT = 'These photos are not sent yet. Tap «Send to review».'; +const BACK_PROMPT = 'Now take a photo of the back of the document.'; +const actionKeysOf = (tree) => tree.root.findByType(Card.Actions).props.children.map((button) => button.key); + +describe('DocumentCaptureCard', () => { + it('takes one photo of a one-page document, shows it, and hands it to the host only on «Send to review»', () => { + const onSend = jest.fn(); + const tree = render(); + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Add', 'Send to review'])); + // Photos only (owner, 2026-11-04): no PDF, even where the server takes one. + expect(textsOf(tree)).not.toContain('Upload a PDF'); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); + // A text button takes the photo; sending is the only one with a border (owner, 2026-11-04). + expect(buttonOf(tree, 'document-requirement-add').props.mode).toBe('text'); + expect(buttonOf(tree, 'document-requirement-send').props.mode).toBe('outlined'); + press(tree, 'document-requirement-add'); + expect(mockPicker.shown).toBe(1); + + take({ uri: 'file:///page.jpg' }); + expect(onSend).not.toHaveBeenCalled(); + expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Document'); + // The way to take a photo stays, and now says it starts again; the note says nothing is sent yet. + expect(textsOf(tree)).toEqual(expect.arrayContaining(['Retake', 'Send to review', NOT_SENT])); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); + + press(tree, 'document-requirement-send'); + expect(onSend).toHaveBeenCalledWith([{ uri: 'file:///page.jpg' }]); + // The card never clears the pages itself: a send that fails keeps them. + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + act(() => host.clear()); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(false); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); + }); + + it('keeps the front of a two-sided document, then the back, and hands over both on «Send to review»', () => { + const onSend = jest.fn(); + const tree = render(); + expect(textsOf(tree)).toContain('Add the front'); + + take({ uri: 'file:///front.jpg' }); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(textsOf(tree)).toEqual(expect.arrayContaining([BACK_PROMPT, 'Add the back'])); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(true); + + take({ uri: 'file:///back.jpg' }); + expect(onSend).not.toHaveBeenCalled(); + expect(propsOf(tree, 'document-requirement-cover-0').accessibilityLabel).toBe('Front'); + expect(propsOf(tree, 'document-requirement-cover-1').accessibilityLabel).toBe('Back'); + expect(textsOf(tree)).not.toContain(BACK_PROMPT); + expect(textsOf(tree)).toEqual(expect.arrayContaining([NOT_SENT, 'Retake'])); + expect(buttonOf(tree, 'document-requirement-send').props.disabled).toBe(false); + + press(tree, 'document-requirement-send'); + expect(onSend).toHaveBeenCalledWith([{ uri: 'file:///front.jpg' }, { uri: 'file:///back.jpg' }]); + act(() => host.clear()); + expect(textsOf(tree)).toContain('Add the front'); + }); + + it('replaces what was taken with a photo taken once every page is there', () => { + const onSend = jest.fn(); + const single = render(); + take({ uri: 'file:///wrong.jpg' }); + take({ uri: 'file:///right.jpg' }); + press(single, 'document-requirement-send'); + expect(onSend).toHaveBeenCalledWith([{ uri: 'file:///right.jpg' }]); + + // The sheet stand-in now hands photos to this card, the last one rendered. + const licence = render(); + take({ uri: 'file:///front.jpg' }); + take({ uri: 'file:///back.jpg' }); + expect(textsOf(licence)).toContain('Retake'); + take({ uri: 'file:///front-again.jpg' }); + expect(hasTestID(licence, 'document-requirement-cover-1')).toBe(false); + expect(textsOf(licence)).toContain('Add the back'); + expect(buttonOf(licence, 'document-requirement-send').props.disabled).toBe(true); + }); + + it('while the host sends, shows the progress on «Send to review», disables every action and keeps the photos', () => { + const tree = render( + + ); + expect(buttonOf(tree, 'document-requirement-add').props.disabled).toBe(true); + expect(buttonOf(tree, 'document-requirement-send').props).toEqual( + expect.objectContaining({ disabled: true, loading: true }) + ); + expect(hasTestID(tree, 'document-requirement-cover-0')).toBe(true); + expect(textsOf(tree)).not.toContain(NOT_SENT); + }); + + it('keys its buttons by position, so a label that changes does not remount the button', () => { + const tree = render(); + const keys = actionKeysOf(tree); + take({ uri: 'file:///front.jpg' }); + expect(actionKeysOf(tree)).toEqual(keys); + }); + + it('takes every document at the resolution its standards need, at full quality, as JPEG', () => { + render(); + expect(mockPicker.captureOptions).toEqual({ + maxWidth: 5120, + maxHeight: 5120, + quality: 1, + assetRepresentationMode: 'compatible', + conversionQuality: 1, + }); + }); +}); diff --git a/packages/components/src/Partner/__tests__/documentVersionRow.test.js b/packages/components/src/Partner/__tests__/documentVersionRow.test.js new file mode 100644 index 00000000..b53a17d4 --- /dev/null +++ b/packages/components/src/Partner/__tests__/documentVersionRow.test.js @@ -0,0 +1,105 @@ +// A document version's list row and the labels a reviewer reads: pure, with the package's catalogue registered as a +// host does (no native module, so this suite runs on its own). +jest.mock('react-native-localize', () => ({ + findBestLanguageTag: jest.fn(() => ({ languageTag: 'en', isRTL: false })), +})); + +import { EN, ES } from '@jmstechnologiesinc/partner'; + +import { formatDateTime } from '../../Localization/format'; +import { registerFlatCatalog, setI18nConfig } from '../../Localization/Localization'; +import { + detailsCodeLabel, + documentVersionRow, + documentVersionRows, + staffDetailsCodeLabel, + staffScanLabel, +} from '../viewModel'; + +const AT = 1793249082020; + +beforeAll(() => { + setI18nConfig(); + registerFlatCatalog({ en: EN, es: ES }); +}); + +describe('documentVersionRows', () => { + it('titles a version by when it was sent, and opens its description with its state, in the cause\'s words', () => { + const rows = documentVersionRows([ + { + versionId: 'v3', + cause: 'pending_review', + verification: { status: 'pending' }, + scan: { status: 'pending' }, + submittedTime: AT, + }, + { + versionId: 'v2', + cause: 'expiring_within_notice', + verification: { status: 'verified' }, + expires_at: '2026-11-23', + scan: { status: 'clean' }, + submittedTime: AT, + }, + { + versionId: 'v1', + verification: { status: 'unverified', details_code: 'document_not_readable' }, + scan: { status: 'clean' }, + supersededBy: 'v2', + submittedTime: AT, + }, + ]); + const sent = formatDateTime(AT); + expect(rows).toEqual([ + { + key: 'v3', + title: sent, + description: `${EN['partner.requirement_cause.pending_review']} · ${EN['partner.scan_status.pending']}`, + }, + { + key: 'v2', + title: sent, + // The calendar day the server sent, in the app's locale, in no reader's zone. + description: `${EN['partner.requirement_cause.expiring_within_notice']} · Expires Nov 23, 2026`, + }, + { + key: 'v1', + title: sent, + description: `Superseded · ${EN['partner.details_code.document_not_readable']}`, + }, + ]); + }); + + it('never names a version by its verification: that is the reviewer\'s word', () => { + const row = documentVersionRow({ versionId: 'v2', verification: { status: 'verified' }, submittedTime: AT }); + expect(row).toEqual({ key: 'v2', title: formatDateTime(AT), description: '' }); + }); + + it('says the scan of a version while it is not clean, by its catalogue label', () => { + const row = documentVersionRow({ + versionId: 'v4', + verification: { status: 'pending' }, + scan: { status: 'infected' }, + submittedTime: AT, + }); + expect(row.description).toBe(EN['partner.scan_status.infected']); + }); + + it('has no rows without versions', () => { + expect(documentVersionRows(undefined)).toEqual([]); + expect(documentVersionRows([])).toEqual([]); + }); + + it('is one version row for every page that lists versions', () => { + const version = { versionId: 'v2', cause: 'satisfied', expires_at: '2026-11-23' }; + expect(documentVersionRow(version)).toEqual(documentVersionRows([version])[0]); + }); +}); + +describe('staff labels (owner, 2026-11-04)', () => { + it('a reviewer reads a code and a scan in the staff\'s words, the partner keeps hers', () => { + expect(staffDetailsCodeLabel('document_failed_copy')).toBe(EN['partner.details_code_staff.document_failed_copy']); + expect(detailsCodeLabel('document_failed_copy')).toBe(EN['partner.details_code.document_failed_copy']); + expect(staffScanLabel('infected')).toBe(EN['partner.scan_status_staff.infected']); + }); +}); diff --git a/packages/components/src/Partner/viewModel.js b/packages/components/src/Partner/viewModel.js index 7de70171..ff702370 100644 --- a/packages/components/src/Partner/viewModel.js +++ b/packages/components/src/Partner/viewModel.js @@ -1,4 +1,4 @@ -import { MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; +import { interpunct, MATERIAL_ICONS } from '@jmstechnologiesinc/commons'; import { CHECKR_REPORT_ADJUDICATION, CHECKR_REPORT_RESULT, @@ -24,12 +24,14 @@ import { RULE_CLAUSE, RULE_ERROR_CODE, RULE_REFERENCE_SUBJECT, + SCAN_STATUS, SCREENING_PACKAGE, STAFF_INTENT, VERIFICATION_STATUS, statusLabelKey, } from '@jmstechnologiesinc/partner'; +import { formatDateTime } from '../Localization/format'; import { currentLocale, localized } from '../Localization/Localization'; import { STATUS_TONES } from '../tones'; @@ -92,6 +94,13 @@ const GROUP = Object.freeze({ disabledReason: groupOf(DISABLED_REASON), intent: groupOf(STAFF_INTENT), refusal: groupOf(REFUSAL_REASON), + scan: groupOf(SCAN_STATUS), +}); + +// A vocabulary labelled twice, once per audience: the partner's group is the one `groupOf` finds, these the staff's. +const STAFF_GROUP = Object.freeze({ + detailsCode: 'details_code_staff', + scan: 'scan_status_staff', }); const { success, warning, danger, neutral, info } = STATUS_TONES; @@ -228,9 +237,15 @@ export const requirementLabel = (key) => { return labelOf(GROUP.requirement, key, member); }; -/** The label of a Stripe `details_code` (canon §7.4). */ +/** The label of a Stripe `details_code` (canon §7.4), in the words the partner reads. */ export const detailsCodeLabel = (code) => labelOf(GROUP.detailsCode, code); +/** The same code in the words a reviewer reads (owner, 2026-11-04: each audience its own text). */ +export const staffDetailsCodeLabel = (code) => labelOf(STAFF_GROUP.detailsCode, code); + +/** A version's scan in the words a reviewer reads. */ +export const staffScanLabel = (scan) => labelOf(STAFF_GROUP.scan, scan); + /** The label of a `disabled_reason` (canon §7.2); the values are dotted, and * the flat catalogue resolves them by exact match. */ export const reasonLabel = (reason) => labelOf(GROUP.disabledReason, reason); @@ -296,6 +311,11 @@ export const CLAUSE_VALUE_KIND = Object.freeze({ export const RULE_CLAUSE_PRESENTATION = Object.freeze([ { clause: RULE_CLAUSE.LABEL, kind: CLAUSE_VALUE_KIND.RULE_TEXT, valueOf: (rule) => rule.label }, { clause: RULE_CLAUSE.EXPLANATION, kind: CLAUSE_VALUE_KIND.RULE_TEXT, valueOf: (rule) => rule.explanation }, + { + clause: RULE_CLAUSE.PARTNER_EXPLANATION, + kind: CLAUSE_VALUE_KIND.RULE_TEXT, + valueOf: (rule) => rule.partnerExplanation, + }, { clause: RULE_CLAUSE.EVIDENCE, kind: CLAUSE_VALUE_KIND.LABEL, @@ -384,6 +404,42 @@ const COUNT_WORD = Object.freeze({ /** A rule's own text (`{en, es}`, written in the rules editor) in the reader's language, else the package's first. */ export const ruleText = (text) => (text ? text[currentLocale().split('-')[0]] ?? text[LOCALES[0]] : null); +/** + * Contract request #117: a requirement's name — the composed rule's own for the partner's market (`label`, #97) when + * it has one, else the catalogue's — so the hub, the lists and the document screen name one requirement one way. + */ +export const requirementTitle = (item) => ruleText(item?.label) ?? requirementLabel(item?.requirementKey); + +// `expires_at` is a calendar day (`YYYY-MM-DD`), which `Date` reads as that day at 00:00 UTC: formatted in UTC it is +// the same day for every reader, where the reader's zone would move it to the day before west of Greenwich. +const CALENDAR_DAY = Object.freeze({ dateStyle: 'medium', timeZone: 'UTC' }); + +/** + * One document version as the server sends it, as a list row `{ key, title, description }`, in the shape of a + * requirement's row (owner, 2026-11-04): the title names it, by when it was sent (in the app's locale), and the + * description opens with its state, in the words of a requirement's cause — «Superseded» once a newer one replaced it, + * else the `cause` the server sends with it. Then its scan while it is not clean (being scanned, or quarantined), why it + * was not accepted and until when it counts (that day, in the app's locale) — each only when the version says it. + */ +export const documentVersionRow = (version) => { + const scan = version.scan?.status; + return { + key: version.versionId, + title: formatDateTime(version.submittedTime), + description: interpunct([ + version.supersededBy ? localized('documentSuperseded') : statusLabel('requirement_cause', version.cause), + scan && scan !== SCAN_STATUS.CLEAN ? labelOf(GROUP.scan, scan) : null, + detailsCodeLabel(version.verification?.details_code), + version.expires_at + ? localized('documentExpiresOn', { date: formatDateTime(version.expires_at, CALENDAR_DAY) }) + : null, + ]), + }; +}; + +/** Contract request #117: a document requirement's versions (`checklistItem.versions`, newest first) as those rows. */ +export const documentVersionRows = (versions) => (Array.isArray(versions) ? versions : []).map(documentVersionRow); + /** «24 h», «30 días»: the catalogue's word for the count, or the bare count while no catalogue carries it. */ const countText = (kind, count) => { const key = statusLabelKey(CLAUSE_WORD, COUNT_WORD[kind]); diff --git a/packages/components/src/index.js b/packages/components/src/index.js index 882bd035..578027ed 100644 --- a/packages/components/src/index.js +++ b/packages/components/src/index.js @@ -80,6 +80,10 @@ export { localizedAuthError } from './Localization/authErrors'; // K-22 — also served by `portable.js`, the entry a web host imports. export { default as StatusChip, SlaChip, LabelChip } from './Partner/StatusChip'; export { default as RuleClauseList } from './Partner/RuleClauseList'; +export { default as DocumentRequirementCard } from './Partner/DocumentRequirementCard'; +export { default as DocumentVersionList } from './Partner/DocumentVersionList'; +// Contract request #117: the card with its capture; native (the photo picker), so not in portable.js. +export { default as DocumentCaptureCard } from './Partner/DocumentCaptureCard'; export { default as DocumentViewer } from './DocumentViewer/DocumentViewer'; export { default as DecisionDialog } from './DecisionDialog/DecisionDialog'; export { default as Timeline } from './Timeline/Timeline'; diff --git a/packages/components/src/portable.js b/packages/components/src/portable.js index 50a6823a..28033742 100644 --- a/packages/components/src/portable.js +++ b/packages/components/src/portable.js @@ -73,6 +73,9 @@ export { orderViewModel, fromDescriptor, statusLabel } from './Order/viewModel'; // K-22 export { default as StatusChip, SlaChip, LabelChip } from './Partner/StatusChip'; export { default as RuleClauseList } from './Partner/RuleClauseList'; +// Contract request #117: a document requirement and its versions, read-only (the capture card is native). +export { default as DocumentRequirementCard } from './Partner/DocumentRequirementCard'; +export { default as DocumentVersionList } from './Partner/DocumentVersionList'; export { default as DocumentViewer, ZOOM } from './DocumentViewer/DocumentViewer'; export { default as DecisionDialog } from './DecisionDialog/DecisionDialog'; // The web keyboard contract of a modal surface (focus in, Tab trap, Esc,