diff --git a/.env.local b/.env.local index 9e3fd6931e9..09bc595fd18 100644 --- a/.env.local +++ b/.env.local @@ -20,8 +20,6 @@ FETCH_PAYMENT_MANAGER_TIMEOUT_MS=16000 FETCH_MAX_RETRIES=3 # number of workers to fetch message TOT_MESSAGE_FETCH_WORKERS=5 -# number of workers to fetch service -TOT_SERVICE_FETCH_WORKERS=5 # shuffle pin pad to proceed with the payment SHUFFLE_PINPAD_ON_PAYMENT=NO # Repository of app content @@ -41,8 +39,6 @@ PLAYGROUNDS_ENABLED=YES BONUS_API_URL_PREFIX='http://127.0.0.1:3000/bonus' BONUS_API_SIT_BASEURL='https://api-io.dev.cstar.pagopa.it' BONUS_API_UAT_BASEURL='https://api-io.uat.cstar.pagopa.it' -# local services web url -LOCAL_SERVICE_WEB_URL='http://127.0.0.1:3000/services_web_view' # EU Covid Certificate EU_COVID_CERT_ENABLED=YES # Zendesk configuration diff --git a/.env.production b/.env.production index f5c7a007cc5..4c4075ebff7 100644 --- a/.env.production +++ b/.env.production @@ -20,8 +20,6 @@ FETCH_PAYMENT_MANAGER_TIMEOUT_MS=16000 FETCH_MAX_RETRIES=3 # number of workers to fetch message TOT_MESSAGE_FETCH_WORKERS=5 -# number of workers to fetch service -TOT_SERVICE_FETCH_WORKERS=5 # shuffle pin pad to proceed with the payment SHUFFLE_PINPAD_ON_PAYMENT=NO # Repository of app content @@ -41,8 +39,6 @@ PLAYGROUNDS_ENABLED=YES BONUS_API_URL_PREFIX=https://api-io.cstar.pagopa.it BONUS_API_SIT_BASEURL='https://api-io.dev.cstar.pagopa.it' BONUS_API_UAT_BASEURL='https://api-io.uat.cstar.pagopa.it' -# local services web url -LOCAL_SERVICE_WEB_URL='https://io.italia.it/app-content/enti-servizi.html' # EU Covid Certificate EU_COVID_CERT_ENABLED=YES # Zendesk configuration diff --git a/img/services/icon-loading-services.png b/img/services/icon-loading-services.png deleted file mode 100644 index b0f6e89ba41..00000000000 Binary files a/img/services/icon-loading-services.png and /dev/null differ diff --git a/img/services/icon-loading-services@2x.png b/img/services/icon-loading-services@2x.png deleted file mode 100644 index 32bdeb58d24..00000000000 Binary files a/img/services/icon-loading-services@2x.png and /dev/null differ diff --git a/img/services/icon-loading-services@3x.png b/img/services/icon-loading-services@3x.png deleted file mode 100644 index 95102e0e653..00000000000 Binary files a/img/services/icon-loading-services@3x.png and /dev/null differ diff --git a/locales/de/index.yml b/locales/de/index.yml index 1ef7f3b3923..4c918515fd1 100644 --- a/locales/de/index.yml +++ b/locales/de/index.yml @@ -1830,8 +1830,6 @@ biometric_recognition: send_email_messages: title: "Mitteilungen mittels E-Mail weiterleiten" services: - accessibility: - edit: "Ändere die Einstellung der Dienste" optIn: preferences: completed: @@ -1862,40 +1860,7 @@ services: title: "Wenn du bestätigst, erhältst du keine Mitteilungen" body: "Bei einer manuellen Konfiguration können dir weder aktuelle noch zukünftige IO-Dienste Mitteilungen senden. Damit Dienste, an denen du interessiert bist, dich kontaktieren können, musst du sie einzeln konfigurieren, indem du den Punkt “In der App kontaktieren” auf jeder Registerkarte des Dienstes aktivierst." title: "Dienste" - subTitle: "Aktiviere oder deaktiviere die Dienste, die dir Mitteilungen senden dürfen" contextualHelpTitle: "Was du in deinen Diensten machen kannst" - serviceIsEnabled: "In der App kontaktieren" - serviceNotEnabled: "Der Dienst ist nicht aktiv" - pushNotifications: "Push-Benachrichtigungen senden" - messageReadStatus: "Lesebestätigungen erhalten" - emailForwarding: "E-Mails senden" - tosAndPrivacy: "Nutzungsbedingungen und Datenschutzbestimmungen" - tosLink: "Nutzungsbedingungen" - privacyLink: "Informationen zum Datenschutz" - otherAppsInfo: "Du findest diesen Dienst auch" - otherAppWeb: "online auf" - otherAppIos: "iOS-App" - otherAppAndroid: "Android-App" - contactsAndInfo: "Kontakte und Informationen" - visitWebsite: "Website" - askForAssistance: "Hilfe anfordern" - contactAddress: "Adresse" - contactPhone: "Telefon" - contactSupport: "Support" - tab: - locals: "Lokal" - national: "National" - all: "Alle" - loading: - title: "Lade die Liste der Dienste" - subtitle: "Warte ein paar Sekunden..." - enableAll: "Schnelleinrichtung verwenden" - disableAll: "Manuelle Konfiguration verwenden" - updatingServiceMode: "Bitte warten..." - disableAllTitle: "Möchtest du wirklich alle Dienste deaktivieren?" - disableAllMsg: "Bedenke, dass du nur von Diensten angeschrieben wirst, die tatsächlich über persönliche Informationen verfügen, die sie dir mitteilen möchten. Du wirst keine Spam-Mitteilungen erhalten. Wenn du alle Dienste deaktivierst, können diese dich nicht mehr über IO kontaktieren (bis du sie wieder aktivierst). Du kannst die Dienste weiterhin über andere Kanäle nutzen (Schalter, Website usw.)." - close: "Schließen" - emptyListMessage: "Zurzeit sind keine Dienste verfügbar, zum Aktualisieren ziehe auf dem Bildschirm nach unten" home: institutions: title: "National" @@ -1925,22 +1890,6 @@ services: title: "Nutzungsbedingungen und Datenschutzbestimmungen" tosLink: "Nutzungsbedingungen" privacyLink: "Datenschutzerklärung" -serviceDetail: - fiscalCode: "Steuernummer Körperschaft" - fiscalCodeAccessibility: "Steuernummer Körperschaft" - fiscalCodeAccessibilityCopy: "Kopiere Steuernummer Körperschaft" - contacts: - title: "Dieser Dienst kann:" - headerTitle: "Details zum Dienst" - onUpdateEnabledChannelsFailure: "Beim Speichern der Einstellungen ist ein temporärer Fehler aufgetreten. Bitte versuche es erneut." - disableTitle: "Möchtest du den Dienst wirklich deaktivieren?" - disableMsg: "Bedenke, dass du nur von Diensten angeschrieben wirst, die tatsächlich über persönliche Informationen verfügen, die sie dir mitteilen möchten. Du wirst keine Spam-Mitteilungen erhalten. Wenn du diesen Dienst deaktivierst, kann dieser dich nicht mehr über IO kontaktieren (bis du ihn wieder aktivierst). Du kannst diesen Dienst weiterhin über andere Kanäle nutzen (Schalter, Website usw.)." - lockedMailAlert: "Die E-Mail-Weiterleitung von Mitteilungen ist global {{enabled}}:" - updatePreferences: "Einstellungen ändern" - goTo: "Geh zu den Einstellungen" - enabled: "aktiviert" - disabled: "deaktiviert" - notValidated: "Um die E-Mail-Weiterleitung zu aktivieren, musst du deine E-Mail-Adresse bestätigen." identification: instructions: unlockCode: "Entsperrcode" diff --git a/locales/en/index.yml b/locales/en/index.yml index d9255c956c9..8f9febda12a 100644 --- a/locales/en/index.yml +++ b/locales/en/index.yml @@ -2110,8 +2110,6 @@ send_email_messages: title: Email a preview subtitle: You will get a preview of the message at your email address if the service allows. services: - accessibility: - edit: Edit services setup optIn: preferences: completed: @@ -2142,41 +2140,8 @@ services: title: "If you confirm, you won't receive any message" body: "With manual configuration the services on IO, present and future, will not be able to contact you. To allow the services you are interested in to contact you, you will have to configure them one by one by enabling “Contact you in app” in each service detail page." title: Services - subTitle: Enable or disable the services that are allowed to send you messages contextualHelpTitle: About this section contextualHelpContent: !include services/services_home.md - serviceIsEnabled: Contact you in app - serviceNotEnabled: The service is not enabled - pushNotifications: Send you push notifications - messageReadStatus: Receive read receipts - emailForwarding: Send you e-mail - tosAndPrivacy: Terms of use and Privacy - tosLink: Terms and conditions - privacyLink: Privacy information - otherAppsInfo: You can find this service also - otherAppWeb: Online on - otherAppIos: iOS App - otherAppAndroid: Android App - contactsAndInfo: Contacts and info - visitWebsite: Browse Website - askForAssistance: Get support - contactAddress: Address - contactPhone: Phone - contactSupport: Support - tab: - locals: Local - national: National - all: All - loading: - title: Loading the services list - subtitle: Please wait... - enableAll: Use quick setup - disableAll: Use manual setup - updatingServiceMode: Please wait... - disableAllTitle: "Do you really want to disable all the services?" - disableAllMsg: "Remember, on IO you will receive messages only from services having some personalized information to communicate to you. You will not receive spam messages. If you disable all the services, they can no longer contact you through the app (until you enable it again). You can use the services through other channels (front office, website, etc.)" - close: Close - emptyListMessage: There are no services available at this time, pull down to refresh new: New home: featured: @@ -2230,23 +2195,6 @@ services: title: "Terms of use and Privacy" tosLink: "Terms and conditions" privacyLink: "Privacy information" -serviceDetail: - fiscalCode: "Institution's fiscal code" - fiscalCodeAccessibility: "Institution's fiscal code" - fiscalCodeAccessibilityCopy: "Copy Institution's fiscal code" - contacts: - title: "This service can:" - headerTitle: "Service details" - contextualHelpContent: !include services/service_detail.md - onUpdateEnabledChannelsFailure: "There was a temporary problem while saving preferences, please retry." - disableTitle: "Do you really want to disable the service?" - disableMsg: "Remember, on IO you will receive messages only from services having some personalized information to communicate to you. You will not receive spam messages. If you disable the service, it can no longer contact you by IO (until you enable it again). You will be able to use the service by other channels (front office, website, etc.)" - lockedMailAlert: "The email forwarding of messages is globally {{enabled}}:" - updatePreferences: Update your preferences - goTo: Go to preferences - enabled: enabled - disabled: disabled - notValidated: To enable the email forwarding you must validate your email address. identification: instructions: unlockCode: unlock code diff --git a/locales/it/index.yml b/locales/it/index.yml index 3f5238578d7..5f26b52e682 100644 --- a/locales/it/index.yml +++ b/locales/it/index.yml @@ -2110,8 +2110,6 @@ send_email_messages: title: Invia un’anteprima via email subtitle: Riceverai un'anteprima del messaggio al tuo indirizzo email, se il servizio lo consente. services: - accessibility: - edit: Modifica l'impostazione dei servizi optIn: preferences: completed: @@ -2142,41 +2140,8 @@ services: title: "Se confermi, non riceverai alcun messaggio" body: "Con la configurazione manuale i servizi di IO, presenti o futuri, non possono inviarti messaggi. Per permettere ai servizi che ti interessano di contattarti, dovrai configurarli uno a uno abilitando la voce “Contattarti in app” che trovi in ogni scheda servizio." title: Servizi - subTitle: Attiva o disattiva i servizi da cui puoi ricevere messaggi contextualHelpTitle: Cosa puoi fare nei tuoi Servizi contextualHelpContent: !include services/services_home.md - serviceIsEnabled: Contattarti in app - serviceNotEnabled: Il servizio non è attivo - pushNotifications: Inviarti notifiche push - messageReadStatus: Ricevere conferme di lettura - emailForwarding: Inviarti e-mail - tosAndPrivacy: Termini e Privacy - tosLink: Termini e condizioni d'uso - privacyLink: Informativa sulla privacy - otherAppsInfo: Puoi usare questo servizio anche - otherAppWeb: Online su - otherAppIos: App iOS - otherAppAndroid: App Android - contactsAndInfo: Contatti ed informazioni - visitWebsite: Visita il sito - askForAssistance: Richiedi assistenza - contactAddress: Indirizzo - contactPhone: Telefono - contactSupport: Assistenza - tab: - locals: Locali - national: Nazionali - all: Tutti - loading: - title: Sto caricando l'elenco dei servizi - subtitle: attendi qualche secondo... - enableAll: Usa configurazione rapida - disableAll: Usa configurazione manuale - updatingServiceMode: Attendi... - disableAllTitle: Vuoi davvero disattivare tutti i servizi? - disableAllMsg: "Ricorda che su IO ti scriveranno solo i servizi che effettivamente hanno qualche informazione personalizzata da comunicarti. Non riceverai messaggi di spam. Se disattivi tutti i servizi, questi non potranno più contattarti tramite IO (finché non li riattiverai). Potrai continuare a fruire i servizi attraverso altri canali (sportello, sito, etc.)" - close: Chiudi - emptyListMessage: Non ci sono servizi disponibili al momento, trascina in basso per aggiornare new: Nuovo home: featured: @@ -2230,23 +2195,6 @@ services: title: "Termini e Privacy" tosLink: "Termini e condizioni d'uso" privacyLink: "Informativa sulla privacy" -serviceDetail: - fiscalCode: "C.F. Ente" - fiscalCodeAccessibility: "Codice fiscale Ente" - fiscalCodeAccessibilityCopy: "Copia codice fiscale Ente" - contacts: - title: "Questo servizio può:" - headerTitle: "Dettagli del Servizio" - contextualHelpContent: !include services/service_detail.md - onUpdateEnabledChannelsFailure: "Si è verificato un errore temporaneo nel salvataggio delle preferenze, riprova per piacere." - disableTitle: "Vuoi davvero disattivare il servizio?" - disableMsg: "Ricorda che su IO ti scriveranno solo i servizi che effettivamente hanno qualche informazione personalizzata da comunicarti. Non riceverai messaggi di spam. Se disattivi il servizio, questo non potrà più contattarti tramite IO (finché non lo riattiverai). Potrai continuare a fruire il servizio attraverso altri canali (sportello, sito, etc.)" - lockedMailAlert: "L'inoltro dei messaggi via email è {{enabled}} globalmente:" - updatePreferences: Modifica le preferenze - goTo: Vai alle preferenze - enabled: abilitato - disabled: disabilitato - notValidated: Per poter abilitare le notifiche via email devi validare il tuo indirizzo email." identification: instructions: unlockCode: codice di sblocco diff --git a/ts/api/backend.ts b/ts/api/backend.ts index aa8259716c9..3894af40905 100644 --- a/ts/api/backend.ts +++ b/ts/api/backend.ts @@ -42,8 +42,6 @@ import { getUserMetadataDefaultDecoder, GetUserMetadataT, GetUserProfileT, - getVisibleServicesDefaultDecoder, - GetVisibleServicesT, StartEmailValidationProcessT, updateProfileDefaultDecoder, UpdateProfileT, @@ -181,14 +179,6 @@ export function BackendClient( response_decoder: upsertServicePreferencesDefaultDecoder() }; - const getVisibleServicesT: GetVisibleServicesT = { - method: "get", - url: () => "/api/v1/services", - query: _ => ({}), - headers: tokenHeaderProducer, - response_decoder: getVisibleServicesDefaultDecoder() - }; - const getMessagesT: GetUserMessagesT = { method: "get", url: _ => "/api/v1/messages", @@ -385,9 +375,6 @@ export function BackendClient( upsertServicePreference: withBearerToken( createFetchRequestForApi(upsertServicePreferenceT, options) ), - getVisibleServices: withBearerToken( - createFetchRequestForApi(getVisibleServicesT, options) - ), getMessages: withBearerToken( createFetchRequestForApi(getMessagesT, options) ), diff --git a/ts/boot/__tests__/__snapshots__/persistedStore.test.ts.snap b/ts/boot/__tests__/__snapshots__/persistedStore.test.ts.snap index dc483927d4a..8c16d4224f4 100644 --- a/ts/boot/__tests__/__snapshots__/persistedStore.test.ts.snap +++ b/ts/boot/__tests__/__snapshots__/persistedStore.test.ts.snap @@ -49,20 +49,6 @@ Object { "nameByFiscalCode": Object {}, }, "paymentByRptId": Object {}, - "services": Object { - "byId": Object {}, - "byOrgFiscalCode": Object {}, - "firstLoading": Object { - "isFirstServicesLoadingCompleted": false, - }, - "readState": Object {}, - "servicePreference": Object { - "kind": "PotNone", - }, - "visible": Object { - "kind": "PotNone", - }, - }, } `; diff --git a/ts/boot/configureStoreAndPersistor.ts b/ts/boot/configureStoreAndPersistor.ts index 588dd63430f..13acad3e92a 100644 --- a/ts/boot/configureStoreAndPersistor.ts +++ b/ts/boot/configureStoreAndPersistor.ts @@ -158,16 +158,7 @@ const migrations: MigrationManifest = { // Version 7 // we empty the services list to get both services list and services metadata being reloaded and persisted - "7": (state: PersistedState) => ({ - ...state, - entities: { - ...(state as PersistedGlobalState).entities, - services: { - ...(state as PersistedGlobalState).entities.services, - byId: {} - } - } - }), + "7": (state: PersistedState) => _.set(state, "entities.services.byId", {}), // Version 8 // we load services scope in an specific view. So now it is uselss to hold (old) services metadata diff --git a/ts/components/screens/BadgeComponent.tsx b/ts/components/screens/BadgeComponent.tsx index 315aabdffc9..fd4f3dd4b78 100644 --- a/ts/components/screens/BadgeComponent.tsx +++ b/ts/components/screens/BadgeComponent.tsx @@ -1,6 +1,6 @@ /** * A component to render the circolar badge - * TODO: use the same component on all lists (messages, services, transaction): https://www.pivotaltracker.com/story/show/167064275 + * TODO: use the same component on all lists (messages, transaction): https://www.pivotaltracker.com/story/show/167064275 */ import * as React from "react"; import { Circle, Svg } from "react-native-svg"; diff --git a/ts/components/screens/SectionHeaderComponent.tsx b/ts/components/screens/SectionHeaderComponent.tsx deleted file mode 100644 index 7c8870d39c8..00000000000 --- a/ts/components/screens/SectionHeaderComponent.tsx +++ /dev/null @@ -1,87 +0,0 @@ -/** - * A component to render a custom section header - * TODO: use the same component for: - * - message list https://www.pivotaltracker.com/story/show/165716236 - * - service lists https://www.pivotaltracker.com/story/show/166792020 - */ -import { pipe } from "fp-ts/lib/function"; -import * as O from "fp-ts/lib/Option"; -import * as React from "react"; -import { - View, - AccessibilityRole, - StyleProp, - StyleSheet, - ViewStyle -} from "react-native"; -import { IOColors, VSpacer } from "@pagopa/io-app-design-system"; -import customVariables from "../../theme/variables"; -import { H2 } from "../core/typography/H2"; -import { IOStyles } from "../core/variables/IOStyles"; -import OrganizationLogo from "../services/OrganizationLogo"; -import { MultiImage } from "../ui/MultiImage"; - -type Props = Readonly<{ - sectionHeader: string; - style?: StyleProp; - logoUri?: React.ComponentProps["source"]; - rightItem?: React.ReactNode; - accessibilityRole?: AccessibilityRole; -}>; - -const styles = StyleSheet.create({ - withoutLogo: { - paddingTop: 19, - paddingBottom: 11, - alignItems: "center" - }, - withLogo: { - paddingTop: customVariables.spacerWidth, - paddingBottom: 0, - alignItems: "center" - }, - sectionView: { - backgroundColor: IOColors.white, - flexDirection: "row", - borderBottomColor: customVariables.itemSeparator, - borderBottomWidth: StyleSheet.hairlineWidth - } -}); - -export default class SectionHeaderComponent extends React.Component { - public render() { - const rightItem = pipe( - this.props.rightItem, - O.fromNullable, - O.getOrElseW(() => - pipe( - this.props.logoUri, - O.fromNullable, - O.map(uri => ), - O.toUndefined - ) - ) - ); - return ( - -

- {this.props.sectionHeader} -

- <> - {rightItem} - - -
- ); - } -} diff --git a/ts/components/search/SearchButton.tsx b/ts/components/search/SearchButton.tsx index dc5bb849189..90204e25411 100644 --- a/ts/components/search/SearchButton.tsx +++ b/ts/components/search/SearchButton.tsx @@ -9,7 +9,6 @@ import I18n from "../../i18n"; import { disableSearch, searchMessagesEnabled, - searchServicesEnabled, updateSearchText } from "../../store/actions/search"; import { Dispatch } from "../../store/actions/types"; @@ -18,7 +17,7 @@ import { ICON_BUTTON_MARGIN } from "../screens/BaseHeader"; export const MIN_CHARACTER_SEARCH_TEXT = 3; -export type SearchType = "Messages" | "Services"; +export type SearchType = "Messages"; interface OwnProps { color?: IOColors; @@ -129,9 +128,6 @@ const mapDispatchToProps = (dispatch: Dispatch, props: OwnProps) => ({ case "Messages": dispatch(searchMessagesEnabled(isSearchEnabled)); break; - case "Services": - dispatch(searchServicesEnabled(isSearchEnabled)); - break; } } }); diff --git a/ts/components/services/ContactPreferencesToggles/PreferenceToggleRow.tsx b/ts/components/services/ContactPreferencesToggles/PreferenceToggleRow.tsx deleted file mode 100644 index 87f3f8a8a19..00000000000 --- a/ts/components/services/ContactPreferencesToggles/PreferenceToggleRow.tsx +++ /dev/null @@ -1,89 +0,0 @@ -import * as React from "react"; -import { View, StyleSheet } from "react-native"; -import { Icon, NativeSwitch } from "@pagopa/io-app-design-system"; -import { H4 } from "../../core/typography/H4"; -import { IOStyles } from "../../core/variables/IOStyles"; -import TouchableDefaultOpacity from "../../TouchableDefaultOpacity"; -import I18n from "../../../i18n"; -import { WithTestID } from "../../../types/WithTestID"; -import ActivityIndicator from "../../ui/ActivityIndicator"; - -type Props = WithTestID<{ - label: string; - onPress: (value: boolean) => void; - value: boolean; - graphicalState: "loading" | "error" | "ready"; - onReload: () => void; - disabled?: boolean; - accessiblityLabel?: string; -}>; - -const styles = StyleSheet.create({ - row: { - flexDirection: "row", - flex: 1, - justifyContent: "space-between", - paddingVertical: 12 - } -}); - -const PreferenceToggleRow = ({ - label, - onPress, - value, - graphicalState, - onReload, - disabled, - testID = "preference-toggle-row" -}: Props): React.ReactElement => { - const getComponentByGraphicalState = () => { - switch (graphicalState) { - case "loading": - return ( - - ); - case "error": - return ( - - - - ); - case "ready": - return ( - - ); - } - }; - return ( - - -

- {label} -

-
- {getComponentByGraphicalState()} -
- ); -}; - -export default PreferenceToggleRow; diff --git a/ts/components/services/ContactPreferencesToggles/__test__/ContactPreferencesToggles.test.tsx b/ts/components/services/ContactPreferencesToggles/__test__/ContactPreferencesToggles.test.tsx deleted file mode 100644 index ced4797c63e..00000000000 --- a/ts/components/services/ContactPreferencesToggles/__test__/ContactPreferencesToggles.test.tsx +++ /dev/null @@ -1,228 +0,0 @@ -import React from "react"; -import { Store } from "redux"; -import configureMockStore from "redux-mock-store"; -import { NotificationChannelEnum } from "../../../../../definitions/backend/NotificationChannel"; -import { ServiceId } from "../../../../../definitions/backend/ServiceId"; -import I18n from "../../../../i18n"; -import { applicationChangeState } from "../../../../store/actions/application"; -import { loadServicePreference } from "../../../../features/services/details/store/actions/preference"; -import { appReducer } from "../../../../store/reducers"; -import { GlobalState } from "../../../../store/reducers/types"; -import { ServicePreferenceResponse } from "../../../../features/services/details/types/ServicePreferenceResponse"; -import { renderScreenWithNavigationStoreContext } from "../../../../utils/testWrapper"; -import ContactPreferencesToggles from "../index"; - -jest.useFakeTimers(); - -describe("ContactPreferencesToggles component", () => { - it("should render the section header", () => { - const store = mockState({ - id: "some_id" as ServiceId, - kind: "success", - value: { - inbox: true, - email: true, - push: false, - can_access_message_read_status: false, - settings_version: 0 - } - }); - const component = renderComponent(store, {}); - expect( - component.getByText(I18n.t("serviceDetail.contacts.title")) - ).toBeDefined(); - }); - describe("when channels are not defined", () => { - it("should render all the switches", () => { - const store = mockState({ - id: "some_id" as ServiceId, - kind: "success", - value: { - inbox: true, - email: true, - push: false, - can_access_message_read_status: false, - settings_version: 0 - } - }); - const component = renderComponent(store, {}); - expect( - component.getByTestId("contact-preferences-inbox-switch") - ).toBeDefined(); - expect( - component.getByTestId("contact-preferences-webhook-switch") - ).toBeDefined(); - // TODO this option should be reintegrated once option will supported back from backend https://pagopa.atlassian.net/browse/IARS-17 - // expect( - // component.getByTestId("contact-preferences-email-switch") - // ).toBeDefined(); - }); - }); - - describe("when channels is an empty array", () => { - it("should render the INBOX switch", () => { - const store = mockState({ - id: "some_id" as ServiceId, - kind: "success", - value: { - inbox: true, - email: true, - push: false, - can_access_message_read_status: false, - settings_version: 0 - } - }); - const component = renderComponent(store, { channels: [] }); - expect( - component.getByTestId("contact-preferences-inbox-switch") - ).toBeDefined(); - }); - it("should not render WEBHOOK and EMAIL switches", () => { - const store = mockState({ - id: "some_id" as ServiceId, - kind: "success", - value: { - inbox: true, - email: true, - push: false, - can_access_message_read_status: false, - settings_version: 0 - } - }); - const component = renderComponent(store, { channels: [] }); - expect( - component.queryByTestId("contact-preferences-webhook-switch") - ).toBeNull(); - expect( - component.queryByTestId("contact-preferences-email-switch") - ).toBeNull(); - }); - }); - - describe("when channels contains all the items ", () => { - it("should render all the switches", () => { - const store = mockState({ - id: "some_id" as ServiceId, - kind: "success", - value: { - inbox: true, - email: true, - push: false, - can_access_message_read_status: false, - settings_version: 0 - } - }); - const component = renderComponent(store, { - channels: [ - NotificationChannelEnum.EMAIL, - NotificationChannelEnum.WEBHOOK - ] - }); - expect( - component.getByTestId("contact-preferences-inbox-switch") - ).toBeDefined(); - expect( - component.getByTestId("contact-preferences-webhook-switch") - ).toBeDefined(); - // TODO this option should be reintegrated once option will supported back from backend https://pagopa.atlassian.net/browse/IARS-17 - // expect( - // component.getByTestId("contact-preferences-email-switch") - // ).toBeDefined(); - }); - }); - - describe("when channels are loading", () => { - it("should render activity indicator on inbox", () => { - const initialState = appReducer( - undefined, - loadServicePreference.success({ - id: "some_id" as ServiceId, - kind: "success", - value: { - inbox: true, - email: true, - push: true, - can_access_message_read_status: false, - settings_version: 0 - } - }) - ); - // the store will be in someLoading - const state = appReducer( - initialState, - loadServicePreference.request("aServiceID" as ServiceId) - ); - const mockStore = configureMockStore(); - const store = mockStore({ - ...state - } as GlobalState); - const component = renderComponent(store, { - channels: [ - NotificationChannelEnum.EMAIL, - NotificationChannelEnum.WEBHOOK - ] - }); - expect( - component.getByTestId("contact-preferences-inbox-switch-loading") - ).toBeDefined(); - expect( - component.getByTestId("contact-preferences-webhook-switch-loading") - ).toBeDefined(); - }); - - it("should render activity indicator on inbox and webhook", () => { - const initialState = appReducer( - undefined, - applicationChangeState("active") - ); - const state = appReducer( - initialState, - loadServicePreference.request("aServiceID" as ServiceId) - ); - const mockStore = configureMockStore(); - const store = mockStore({ - ...state - } as GlobalState); - const component = renderComponent(store, { - channels: [ - NotificationChannelEnum.EMAIL, - NotificationChannelEnum.WEBHOOK - ] - }); - expect( - component.getByTestId("contact-preferences-inbox-switch-loading") - ).toBeDefined(); - }); - }); -}); - -const mockState = (servicePreference: ServicePreferenceResponse) => { - const initialState = appReducer(undefined, applicationChangeState("active")); - const state = appReducer( - initialState, - loadServicePreference.success(servicePreference) - ); - const mockStore = configureMockStore(); - return mockStore({ - ...state - } as GlobalState); -}; - -const renderComponent = ( - store: Store, - options: { - channels?: ReadonlyArray; - } -) => - renderScreenWithNavigationStoreContext( - () => ( - - ), - "route", - {}, - store - ); diff --git a/ts/components/services/ContactPreferencesToggles/__test__/PreferenceToggleRow.test.tsx b/ts/components/services/ContactPreferencesToggles/__test__/PreferenceToggleRow.test.tsx deleted file mode 100644 index a00c4f47abb..00000000000 --- a/ts/components/services/ContactPreferencesToggles/__test__/PreferenceToggleRow.test.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import React from "react"; -import { render, fireEvent } from "@testing-library/react-native"; - -import PreferenceToggleRow from "../PreferenceToggleRow"; - -describe("PreferenceToggleRow component", () => { - const options: Partial[0]> = { - label: "Push Notifications", - value: true, - onPress: jest.fn() - }; - it("should match the snapshot", () => { - const component = renderComponent(options); - expect(component.toJSON()).toMatchSnapshot(); - }); - - it("should show the label", () => { - const component = renderComponent(options); - expect(component.getByText("Push Notifications")).toBeDefined(); - }); - it("should expose a working switch", () => { - const component = renderComponent(options); - const switchComponent = component.getByRole("switch"); - expect(switchComponent).toBeDefined(); - fireEvent(switchComponent, "onValueChange", false); - expect(options.onPress).toHaveBeenCalledWith(false); - }); - it("should use a default testID", () => { - const component = renderComponent(options); - expect(component.getByTestId("preference-toggle-row")).toBeDefined(); - }); - describe("when a testID is passed", () => { - it("should honour the property", () => { - const component = renderComponent({ ...options, testID: "new-test-id" }); - expect(component.getByTestId("new-test-id")).toBeDefined(); - }); - }); - - describe("handle different status", () => { - it("should display activity indicator", () => { - const component = renderComponent({ - ...options, - graphicalState: "loading" - }); - - expect( - component.getByTestId("preference-toggle-row-loading") - ).toBeDefined(); - }); - - it("should display reload button", () => { - const spy = jest.fn(); - const component = renderComponent({ - ...options, - graphicalState: "error", - onReload: spy - }); - const reloadComponent = component.getByTestId( - "preference-toggle-row-reload" - ); - expect(reloadComponent).toBeDefined(); - fireEvent.press(reloadComponent); - expect(spy).toHaveBeenCalledTimes(1); - }); - - it("should display switch disabled", () => { - const component = renderComponent({ - ...options, - graphicalState: "ready", - disabled: true - }); - expect(component.getByTestId("preference-toggle-row")).toBeDefined(); - const switchComponent = component.getByRole("switch"); - expect(switchComponent).toBeDefined(); - expect(switchComponent).toHaveProp("disabled", true); - }); - }); -}); - -function renderComponent( - options: Partial[0]> -) { - const onPress = jest.fn(); - const onReload = jest.fn(); - return render( - - ); -} diff --git a/ts/components/services/ContactPreferencesToggles/__test__/__snapshots__/PreferenceToggleRow.test.tsx.snap b/ts/components/services/ContactPreferencesToggles/__test__/__snapshots__/PreferenceToggleRow.test.tsx.snap deleted file mode 100644 index 22b9ea6c100..00000000000 --- a/ts/components/services/ContactPreferencesToggles/__test__/__snapshots__/PreferenceToggleRow.test.tsx.snap +++ /dev/null @@ -1,83 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`PreferenceToggleRow component should match the snapshot 1`] = ` - - - - Push Notifications - - - - -`; diff --git a/ts/components/services/ContactPreferencesToggles/index.tsx b/ts/components/services/ContactPreferencesToggles/index.tsx deleted file mode 100644 index c6e54eedeaa..00000000000 --- a/ts/components/services/ContactPreferencesToggles/index.tsx +++ /dev/null @@ -1,232 +0,0 @@ -import { IOToast } from "@pagopa/io-app-design-system"; -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { useIsFocused } from "@react-navigation/native"; -import * as O from "fp-ts/lib/Option"; -import { pipe } from "fp-ts/lib/function"; -import React, { useCallback, useEffect, useMemo, useState } from "react"; -import { connect } from "react-redux"; -import I18n from "i18n-js"; -import { NotificationChannelEnum } from "../../../../definitions/backend/NotificationChannel"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { trackPNPushSettings } from "../../../features/pn/analytics"; -import { - loadServicePreference, - upsertServicePreference -} from "../../../features/services/details/store/actions/preference"; -import { Dispatch } from "../../../store/actions/types"; -import { useIOSelector } from "../../../store/hooks"; -import { isPremiumMessagesOptInOutEnabledSelector } from "../../../store/reducers/backendStatus"; -import { - servicePreferenceSelector, - ServicePreferenceState -} from "../../../features/services/details/store/reducers/servicePreference"; -import { GlobalState } from "../../../store/reducers/types"; -import { - isServicePreferenceResponseSuccess, - ServicePreference -} from "../../../features/services/details/types/ServicePreferenceResponse"; -import { isStrictSome } from "../../../utils/pot"; -import ItemSeparatorComponent from "../../ItemSeparatorComponent"; -import SectionHeader from "../SectionHeader"; -import PreferenceToggleRow from "./PreferenceToggleRow"; - -type Item = "email" | "push" | "inbox" | "can_access_message_read_status"; - -type Props = { - channels?: ReadonlyArray; - serviceId: ServiceId; - isSpecialService: boolean; - customSpecialFlowOpt?: string; -} & ReturnType & - ReturnType; - -const hasChannel = ( - channel: NotificationChannelEnum, - channels?: ReadonlyArray -) => - pipe( - channels, - O.fromNullable, - O.map(anc => anc.indexOf(channel) !== -1), - O.getOrElse(() => true) - ); - -/** - * Utility function to get the user preference value for a specific channel - * return false if preference state is pot.none or if an error occurred on API Response - * */ -const getChannelPreference = ( - potServicePreference: ServicePreferenceState, - key: Item -): boolean => { - if ( - pot.isSome(potServicePreference) && - isServicePreferenceResponseSuccess(potServicePreference.value) - ) { - return potServicePreference.value.value[key]; - } - return false; -}; - -const ContactPreferencesToggle: React.FC = (props: Props) => { - const { isLoading, isError } = props; - const [isFirstRender, setIsFirstRender] = useState(true); - const { serviceId, loadServicePreference } = props; - - const loadPreferences = useCallback( - () => loadServicePreference(serviceId), - [serviceId, loadServicePreference] - ); - - const isFocused = useIsFocused(); - - const isPremiumMessagesOptInOutEnabled = useIOSelector( - isPremiumMessagesOptInOutEnabledSelector - ); - - useEffect(() => { - loadPreferences(); - }, [serviceId, loadPreferences, isFocused]); - - useEffect(() => { - if (!isFirstRender) { - if (isError) { - IOToast.error(I18n.t("global.genericError")); - } - } else { - setIsFirstRender(false); - } - }, [isError, isFirstRender]); - - const onValueChange = (value: boolean, type: Item) => { - if ( - isStrictSome(props.servicePreferenceStatus) && - isServicePreferenceResponseSuccess(props.servicePreferenceStatus.value) - ) { - props.upsertServicePreference(props.serviceId, { - ...props.servicePreferenceStatus.value.value, - [type]: value - }); - } - }; - - const graphicalState = useMemo( - () => (isLoading ? "loading" : isError ? "error" : "ready"), - [isLoading, isError] - ); - - return ( - <> - - {/* - This Toggle is disabled if the current service is a Special Service cause user can - enable or disable the service only using the proper Special Service flow and not only tapping the specific toggle - */} - onValueChange(value, "inbox")} - disabled={props.isSpecialService} - graphicalState={graphicalState} - onReload={loadPreferences} - value={getChannelPreference(props.servicePreferenceStatus, "inbox")} - testID={"contact-preferences-inbox-switch"} - /> - - {hasChannel(NotificationChannelEnum.WEBHOOK, props.channels) && - getChannelPreference(props.servicePreferenceStatus, "inbox") && ( - // toggle is disabled if the inbox value is false to prevent inconsistent data - <> - { - pipe( - props.customSpecialFlowOpt, - O.fromNullable, - O.filter(customSpecialFlow => customSpecialFlow === "pn"), - O.fold( - () => undefined, - _ => trackPNPushSettings(value) - ) - ); - onValueChange(value, "push"); - }} - value={getChannelPreference( - props.servicePreferenceStatus, - "push" - )} - graphicalState={graphicalState} - onReload={loadPreferences} - testID={"contact-preferences-webhook-switch"} - /> - - - )} - {isPremiumMessagesOptInOutEnabled && - getChannelPreference(props.servicePreferenceStatus, "inbox") && ( - // toggle is disabled if the inbox value is false to prevent inconsistent data - <> - - onValueChange(value, "can_access_message_read_status") - } - value={getChannelPreference( - props.servicePreferenceStatus, - "can_access_message_read_status" - )} - graphicalState={graphicalState} - onReload={loadPreferences} - testID={"contact-preferences-trackSeen-switch"} - /> - - - )} - - {/* Email toggle is temporary removed until the feature will be enabled back from the backend */} - {/* TODO this option should be reintegrated once option will supported back from backend https://pagopa.atlassian.net/browse/IARS-17 */} - {/* {hasChannel(NotificationChannelEnum.EMAIL, props.channels) && getChannelPreference(props.servicePreferenceStatus, "inbox") && ( */} - {/* <> */} - {/* onValueChange(value, "email")} */} - {/* value={getChannelPreference(props.servicePreferenceStatus, "email")} */} - {/* graphicalState={graphicalState} */} - {/* isError={isError} */} - {/* testID={"contact-preferences-email-switch"} */} - {/* /> */} - {/* */} - {/* */} - {/* )} */} - - ); -}; - -const mapStateToProps = (state: GlobalState) => { - const servicePreferenceStatus = servicePreferenceSelector(state); - const isLoading = - pot.isLoading(servicePreferenceStatus) || - pot.isUpdating(servicePreferenceStatus); - - const isError = - pot.isError(servicePreferenceStatus) || - (isStrictSome(servicePreferenceStatus) && - servicePreferenceStatus.value.kind !== "success"); - - return { - isLoading, - isError, - servicePreferenceStatus - }; -}; - -const mapDispatchToProps = (dispatch: Dispatch) => ({ - upsertServicePreference: (id: ServiceId, sp: ServicePreference) => - dispatch(upsertServicePreference.request({ id, ...sp })), - loadServicePreference: (id: ServiceId) => - dispatch(loadServicePreference.request(id)) -}); - -export default connect( - mapStateToProps, - mapDispatchToProps -)(ContactPreferencesToggle); diff --git a/ts/components/services/LinkRow.tsx b/ts/components/services/LinkRow.tsx deleted file mode 100644 index b25001d0e87..00000000000 --- a/ts/components/services/LinkRow.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import * as React from "react"; -import { StyleSheet } from "react-native"; - -import { IOToast } from "@pagopa/io-app-design-system"; -import { TranslationKeys } from "../../../locales/locales"; -import I18n from "../../i18n"; -import { openWebUrl } from "../../utils/url"; - -import { Link } from "../core/typography/Link"; -import ItemSeparatorComponent from "../ItemSeparatorComponent"; - -const styles = StyleSheet.create({ - link: { - paddingVertical: 16 - } -}); - -type Props = { - text: TranslationKeys; - href: string; -}; - -const LinkRow = ({ text, href }: Props) => ( - <> - - openWebUrl(href, () => IOToast.error(I18n.t("global.jserror.title"))) - } - numberOfLines={1} - style={styles.link} - > - {I18n.t(text)} - - - -); - -export default LinkRow; diff --git a/ts/components/services/LocalServicesWebView.tsx b/ts/components/services/LocalServicesWebView.tsx deleted file mode 100644 index 82a889e0363..00000000000 --- a/ts/components/services/LocalServicesWebView.tsx +++ /dev/null @@ -1,175 +0,0 @@ -import { IOColors, IOToast, hexToRgba } from "@pagopa/io-app-design-system"; -import * as pot from "@pagopa/ts-commons/lib/pot"; -import * as E from "fp-ts/lib/Either"; -import * as O from "fp-ts/lib/Option"; -import { pipe } from "fp-ts/lib/function"; -import React from "react"; -import { StyleSheet, View } from "react-native"; -import WebView, { WebViewMessageEvent } from "react-native-webview"; -import { connect } from "react-redux"; -import { Dispatch } from "redux"; -import { ServiceId } from "../../../definitions/backend/ServiceId"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import { localServicesWebUrl } from "../../config"; -import { useTabItemPressWhenScreenActive } from "../../hooks/useTabItemPressWhenScreenActive"; -import I18n from "../../i18n"; -import { loadServiceDetail } from "../../features/services/details/store/actions/details"; -import { servicesByIdSelector } from "../../features/services/details/store/reducers/servicesById"; -import { GlobalState } from "../../store/reducers/types"; -import { isStrictSome } from "../../utils/pot"; -import { AVOID_ZOOM_JS, closeInjectedScript } from "../../utils/webview"; -import { withLightModalContext } from "../helpers/withLightModalContext"; -import GenericErrorComponent from "../screens/GenericErrorComponent"; -import { RefreshIndicator } from "../ui/RefreshIndicator"; - -type Props = { - onServiceSelect: (service: ServicePublic) => void; -} & ReturnType & - ReturnType; - -const opaqueBgColor = hexToRgba(IOColors.white, 0.5); - -const styles = StyleSheet.create({ - refreshIndicatorContainer: { - position: "absolute", - left: 0, - right: 0, - top: 0, - bottom: 0, - backgroundColor: opaqueBgColor, - justifyContent: "center", - alignItems: "center", - zIndex: 1000 - }, - genericError: { - flex: 1, - position: "absolute", - left: 0, - right: 0, - top: 0, - bottom: 0 - }, - webView: { - flex: 1 - } -}); -const renderLoading = () => ( - - - -); - -/** - * This component is basically a webview that loads an url showing local services - * It intercepts the request of loading a service and it does: - * - block that request from loading - * - extract from the request url the service id - * - load the selected service starting from the service id (load and error are handled) - */ -const LocalServicesWebView = (props: Props) => { - const [serviceIdToLoad, setServiceIdToLoad] = React.useState< - string | undefined - >(undefined); - const [webViewError, setWebViewError] = React.useState(false); - const webViewRef = React.createRef(); - - const scrollWebview = (x: number, y: number) => { - const script = `window.scrollTo(${x}, ${y})`; - webViewRef.current?.injectJavaScript(script); - }; - - useTabItemPressWhenScreenActive(() => scrollWebview(0, 0), true); - - const { servicesById, onServiceSelect } = props; - - React.useEffect(() => { - pipe( - serviceIdToLoad, - O.fromNullable, - O.chainNullableK(sid => servicesById[sid]), - O.map(servicePot => { - // if service has been loaded - if (isStrictSome(servicePot)) { - onServiceSelect(servicePot.value); - setServiceIdToLoad(undefined); - return; - } - if (pot.isError(servicePot)) { - IOToast.error(I18n.t("global.genericError")); - } - }) - ); - }, [servicesById, onServiceSelect, serviceIdToLoad]); - - const reloadWebView = () => { - if (webViewRef.current) { - webViewRef.current.reload(); - setWebViewError(false); - } - }; - - /** - * 'listen' on web message - * if a serviceId is sent: dispatch service loading request - * @param event - */ - const handleWebviewMessage = (event: WebViewMessageEvent) => { - pipe( - event.nativeEvent.data, - ServiceId.decode, - E.map(sId => { - setServiceIdToLoad(sId); - // request loading service - props.loadService(sId); - }) - ); - }; - - const isLoadingServiceLoading = pipe( - serviceIdToLoad, - O.fromNullable, - O.chainNullableK(sid => props.servicesById[sid]), - O.fold(() => false, pot.isLoading) - ); - return ( - <> - {isLoadingServiceLoading && renderLoading()} - - setWebViewError(true)} - onMessage={handleWebviewMessage} - startInLoadingState={true} - renderLoading={renderLoading} - javaScriptEnabled={true} - /> - {webViewError && ( - - - - )} - - ); -}; - -const mapDispatchToProps = (dispatch: Dispatch) => ({ - loadService: (serviceId: string) => - dispatch(loadServiceDetail.request(serviceId)) -}); - -const mapStateToProps = (state: GlobalState) => ({ - servicesById: servicesByIdSelector(state) -}); - -export default connect( - mapStateToProps, - mapDispatchToProps -)(withLightModalContext(LocalServicesWebView)); diff --git a/ts/components/services/NewServiceListItem.tsx b/ts/components/services/NewServiceListItem.tsx deleted file mode 100644 index 29c6469db17..00000000000 --- a/ts/components/services/NewServiceListItem.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import * as React from "react"; -import { GestureResponderEvent } from "react-native"; -import { ListItemNav } from "@pagopa/io-app-design-system"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import I18n from "../../i18n"; - -type Props = { - item: pot.Pot; - onSelect: (service: ServicePublic) => void; - hideSeparator: boolean; -}; - -const NewServiceListItem = (props: Props): React.ReactElement => { - const potService = props.item; - const onPress = pot.toUndefined( - pot.map(potService, service => () => props.onSelect(service)) - ); - - const serviceName = pot.fold( - potService, - () => I18n.t("global.remoteStates.loading"), - () => I18n.t("global.remoteStates.loading"), - () => I18n.t("global.remoteStates.notAvailable"), - () => I18n.t("global.remoteStates.notAvailable"), - service => service.service_name, - () => I18n.t("global.remoteStates.loading"), - service => service.service_name, - () => I18n.t("global.remoteStates.notAvailable") - ); - - return ( - void} - testID={serviceName} - /> - ); -}; - -export default NewServiceListItem; diff --git a/ts/components/services/OrganizationLogo.tsx b/ts/components/services/OrganizationLogo.tsx deleted file mode 100644 index 3a8850ef60c..00000000000 --- a/ts/components/services/OrganizationLogo.tsx +++ /dev/null @@ -1,35 +0,0 @@ -// A component to provide organization logo -import * as React from "react"; -import { ImageStyle, StyleProp, StyleSheet } from "react-native"; -import variables from "../../theme/variables"; -import { MultiImage } from "../ui/MultiImage"; - -type Props = { - logoUri: React.ComponentProps["source"]; - imageStyle?: StyleProp; -}; - -const styles = StyleSheet.create({ - organizationLogo: { - height: 32, - width: 32, - resizeMode: "contain", - marginBottom: 6, - alignSelf: "flex-start", - marginRight: variables.spacingBase - } -}); - -class OrganizationLogo extends React.Component { - public render(): React.ReactNode { - const { logoUri } = this.props; - return ( - - ); - } -} - -export default OrganizationLogo; diff --git a/ts/components/services/SectionHeader.tsx b/ts/components/services/SectionHeader.tsx deleted file mode 100644 index 1d701068645..00000000000 --- a/ts/components/services/SectionHeader.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import * as React from "react"; -import { StyleSheet, View } from "react-native"; - -import { IOIcons, Icon, HSpacer } from "@pagopa/io-app-design-system"; -import { TranslationKeys } from "../../../locales/locales"; -import I18n from "../../i18n"; - -import { H3 } from "../core/typography/H3"; - -const styles = StyleSheet.create({ - header: { - flexDirection: "row", - paddingVertical: 8, - alignItems: "center" - } -}); - -type Props = { - iconName: IOIcons; - title: TranslationKeys; -}; - -/** - * Renders a header for any section in the service's details page - */ -const sectionHeader: React.FC = ({ iconName, title }) => ( - - - -

- {I18n.t(title)} -

-
-); - -export default sectionHeader; diff --git a/ts/components/services/ServiceList.tsx b/ts/components/services/ServiceList.tsx deleted file mode 100644 index a03dbb14199..00000000000 --- a/ts/components/services/ServiceList.tsx +++ /dev/null @@ -1,134 +0,0 @@ -/** - * A component to render a list of services grouped by organization. - */ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import React from "react"; -import { - Animated, - ListRenderItemInfo, - NativeScrollEvent, - NativeSyntheticEvent, - RefreshControl, - SectionList, - SectionListData -} from "react-native"; -import { IOVisualCostants } from "@pagopa/io-app-design-system"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import { getLogoForOrganization } from "../../utils/organizations"; -import { - TabBarItemPressType, - withUseTabItemPressWhenScreenActive -} from "../helpers/withUseTabItemPressWhenScreenActive"; - -import ItemSeparatorComponent from "../ItemSeparatorComponent"; -import SectionHeaderComponent from "../screens/SectionHeaderComponent"; -import NewServiceListItem from "./NewServiceListItem"; - -type AnimatedProps = { - animated?: { - onScroll: (_: NativeSyntheticEvent) => void; - scrollEventThrottle?: number; - }; -}; - -type OwnProps = { - sections: ReadonlyArray>>; - isRefreshing: boolean; - onRefresh: () => void; - onSelect: (service: ServicePublic) => void; - ListEmptyComponent?: React.ComponentProps< - typeof SectionList - >["ListEmptyComponent"]; -}; - -type Props = OwnProps & AnimatedProps & TabBarItemPressType; - -class ServiceList extends React.Component { - componentDidMount() { - const { setHasInternalTab: setHasInternalTab, setTabPressCallback } = - this.props; - - setHasInternalTab(true); - setTabPressCallback(() => () => { - sectionListRef.current?.scrollToLocation({ - animated: true, - itemIndex: 0, - sectionIndex: 0, - viewOffset: 0 - }); - }); - } - - private renderServiceItem = ( - itemInfo: ListRenderItemInfo> - ) => ( - - ); - - private getServiceKey = ( - potService: pot.Pot, - index: number - ): string => - pot.getOrElse( - pot.map( - potService, - service => `${service.service_id}-${service.version}` - ), - `service-pot-${index}` - ); - - private renderServiceSectionHeader = (info: { - section: SectionListData>; - }): React.ReactNode => ( - - ); - - public render() { - const { sections, isRefreshing, onRefresh, ListEmptyComponent } = - this.props; - - const refreshControl = ( - - ); - - return ( - - ); - } -} - -const sectionListRef = React.createRef(); - -export default withUseTabItemPressWhenScreenActive(ServiceList); diff --git a/ts/components/services/ServiceMetadata/InformationRow.tsx b/ts/components/services/ServiceMetadata/InformationRow.tsx deleted file mode 100644 index bc89c79b197..00000000000 --- a/ts/components/services/ServiceMetadata/InformationRow.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import React from "react"; -import { View, StyleSheet } from "react-native"; -import { HSpacer } from "@pagopa/io-app-design-system"; -import { TranslationKeys } from "../../../../locales/locales"; -import { capitalize } from "../../../utils/strings"; -import I18n from "../../../i18n"; -import { H4 } from "../../core/typography/H4"; -import TouchableDefaultOpacity from "../../TouchableDefaultOpacity"; -import ItemSeparatorComponent from "../../ItemSeparatorComponent"; - -const styles = StyleSheet.create({ - touchable: { - flexDirection: "row", - marginVertical: 16 - }, - value: { - flexGrow: 1, - flexShrink: 1, - textAlign: "right" - } -}); - -type Props = { - value: string; - label: TranslationKeys; - onPress: () => void; - isLast?: boolean; - accessibilityLabel?: string; -}; - -const InformationRow = ({ - value, - label, - onPress, - isLast, - accessibilityLabel -}: Props) => ( - - -

- {capitalize(I18n.t(label))} -

- -

- {value} -

-
- {!isLast && } -
-); - -export default InformationRow; diff --git a/ts/components/services/ServiceMetadata/__tests__/InformationRow.test.tsx b/ts/components/services/ServiceMetadata/__tests__/InformationRow.test.tsx deleted file mode 100644 index a06f9af6a94..00000000000 --- a/ts/components/services/ServiceMetadata/__tests__/InformationRow.test.tsx +++ /dev/null @@ -1,20 +0,0 @@ -import React from "react"; -import { render } from "@testing-library/react-native"; -import { constNull } from "fp-ts/lib/function"; - -import InformationRow from "../InformationRow"; - -describe("the InformationRow component", () => { - it("should match the snapshot", () => { - expect( - render( - - ).toJSON() - ).toMatchSnapshot(); - }); -}); diff --git a/ts/components/services/ServiceMetadata/__tests__/ServiceMetadata.test.tsx b/ts/components/services/ServiceMetadata/__tests__/ServiceMetadata.test.tsx deleted file mode 100644 index 40e4ab86560..00000000000 --- a/ts/components/services/ServiceMetadata/__tests__/ServiceMetadata.test.tsx +++ /dev/null @@ -1,329 +0,0 @@ -import { OrganizationFiscalCode } from "@pagopa/ts-commons/lib/strings"; -import { fireEvent, render } from "@testing-library/react-native"; -import React from "react"; -import { testableGenServiceMetadataAccessibilityLabel } from "../"; -import { ServiceId } from "../../../../../definitions/backend/ServiceId"; -import { ServiceMetadata } from "../../../../../definitions/backend/ServiceMetadata"; -import { ServiceScopeEnum } from "../../../../../definitions/backend/ServiceScope"; -import { StandardServiceCategoryEnum } from "../../../../../definitions/backend/StandardServiceCategory"; -import { TranslationKeys } from "../../../../../locales/locales"; -import I18n from "../../../../i18n"; -import { capitalize } from "../../../../utils/strings"; -import * as utilsUrl from "../../../../utils/url"; -import ServiceMetadataComponent from "../../ServiceMetadata"; - -jest.mock("../../../../utils/platform"); - -const spyOpenWebUrl = jest.spyOn(utilsUrl, "openWebUrl"); - -const defaultServiceMetadata: ServiceMetadata = { - scope: ServiceScopeEnum.NATIONAL, - category: StandardServiceCategoryEnum.STANDARD -}; - -const defaultProps = { - getItemOnPress: jest.fn(), - isDebugModeEnabled: false, - organizationFiscalCode: "01234567891" as OrganizationFiscalCode, - serviceId: "ABC123" as ServiceId, - servicesMetadata: defaultServiceMetadata -}; - -const genServiceMetadataAccessibilityLabel = - testableGenServiceMetadataAccessibilityLabel!; - -describe("ServiceMetadata component", () => { - beforeEach(() => { - defaultProps.getItemOnPress.mockReset(); - spyOpenWebUrl.mockReset(); - }); - afterEach(() => { - jest.dontMock("../../../../utils/url"); - }); - - it("should render the section header", () => { - expect( - renderComponent({ ...defaultProps }).getByText( - I18n.t("services.contactsAndInfo") - ) - ).toBeDefined(); - }); - - describe("when debug mode is enabled", () => { - const currentOptions = { - ...defaultProps, - isDebugModeEnabled: true - }; - it("should render the serviceId label", () => { - expect( - renderComponent(currentOptions).getByText( - capitalize(I18n.t("global.id")) - ) - ).toBeDefined(); - }); - - it("should render the serviceId value", () => { - expect( - renderComponent(currentOptions).getByText(currentOptions.serviceId) - ).toBeDefined(); - }); - - it(`should call "getItemOnPress" with (${currentOptions.serviceId}, "COPY")`, () => { - renderComponent(currentOptions); - expect(currentOptions.getItemOnPress).toHaveBeenCalledWith( - currentOptions.serviceId, - "COPY" - ); - }); - }); - - describe("given an organizationFiscalCode", () => { - it("should render the organizationFiscalCode label", () => { - expect( - renderComponent(defaultProps).getByText( - capitalize(I18n.t("serviceDetail.fiscalCode")) - ) - ).toBeDefined(); - }); - - it("should render the organizationFiscalCode value", () => { - expect( - renderComponent(defaultProps).getByText( - defaultProps.organizationFiscalCode - ) - ).toBeDefined(); - }); - - it("should render the correct accessibility label", () => { - const a11yLabel = genServiceMetadataAccessibilityLabel( - I18n.t("serviceDetail.fiscalCode"), - defaultProps.organizationFiscalCode, - I18n.t("serviceDetail.fiscalCodeAccessibilityCopy") - ); - - expect( - renderComponent(defaultProps).getByA11yLabel(a11yLabel) - ).toBeDefined(); - }); - - it(`should call "getItemOnPress" with (${defaultProps.organizationFiscalCode}, "COPY")`, () => { - renderComponent(defaultProps); - expect(defaultProps.getItemOnPress).toHaveBeenCalledWith( - defaultProps.organizationFiscalCode, - "COPY" - ); - }); - }); - - [ - [ - "address", - "via genova", - "services.contactAddress", - "MAP", - "openMaps.openAddressOnMap" - ] - ].forEach(([name, value, label, action, hint]) => { - describe(`when ${name} is defined`, () => { - const currentOptions = { - ...defaultProps, - servicesMetadata: { - ...defaultServiceMetadata, - [name]: value - } - }; - it(`should render its label "${label}"`, () => { - expect( - renderComponent(currentOptions).getByText( - capitalize(I18n.t(label as TranslationKeys)) - ) - ).toBeDefined(); - }); - it(`should render its value "${value}"`, () => { - expect(renderComponent(currentOptions).getByText(value)).toBeDefined(); - }); - it(`should call "getItemOnPress" with ("${value}", ${action})`, () => { - renderComponent(currentOptions); - expect(currentOptions.getItemOnPress).toHaveBeenCalledWith( - value, - action - ); - }); - it("should render the correct accessibility label", () => { - const a11yLabel = genServiceMetadataAccessibilityLabel( - I18n.t(label as TranslationKeys), - value, - I18n.t(hint as TranslationKeys) - ); - - expect( - renderComponent(currentOptions).getByA11yLabel(a11yLabel) - ).toBeDefined(); - }); - }); - }); - - [ - ["email", "jest@test.com", "global.media.email", "mailto:"], - ["pec", "jest.pec@test.com", "global.media.pec", "mailto:"], - ["phone", "12341234", "global.media.phone", "tel:"] - ].forEach(([name, value, label, prefix]) => { - describe(`when ${name} is defined`, () => { - const currentOptions = { - ...defaultProps, - servicesMetadata: { ...defaultServiceMetadata, [name]: value } - }; - // eslint-disable-next-line sonarjs/no-identical-functions - it(`should render its label "${label}"`, () => { - expect( - renderComponent(currentOptions).getByText( - capitalize(I18n.t(label as TranslationKeys)) - ) - ).toBeDefined(); - }); - it(`should render its value "${value}"`, () => { - expect(renderComponent(currentOptions).getByText(value)).toBeDefined(); - }); - it(`should call "getItemOnPress" with ("${prefix}:${value}")`, () => { - renderComponent(currentOptions); - expect(currentOptions.getItemOnPress).toHaveBeenCalledWith( - `${prefix}${value}` - ); - }); - }); - }); - - [ - ["support_url", "www.support.it", "services.askForAssistance"], - ["web_url", "www.product.it", "services.visitWebsite"] - ].forEach(([name, value, label]) => { - const currentOptions = { - ...defaultProps, - servicesMetadata: { - ...defaultServiceMetadata, - [name]: value - } - }; - describe(`when ${name} is defined`, () => { - it(`should render a link with "${label}"`, () => { - const component = renderComponent(currentOptions); - const link = component.getByRole("link"); - expect(link).toBeDefined(); - expect(link.children.toString()).toMatch( - I18n.t(label as TranslationKeys) - ); - }); - describe("when the link is pressed", () => { - it(`should open the url "${value}"`, () => { - const component = renderComponent(currentOptions); - const link = component.getByRole("link"); - fireEvent(link, "onPress"); - expect(spyOpenWebUrl).toHaveBeenCalledWith( - value, - expect.any(Function) - ); - }); - }); - }); - }); - - describe("when the platform is Android", () => { - beforeAll(() => { - // eslint-disable-next-line @typescript-eslint/no-var-requires - require("../../../../utils/platform").test_setPlatform("android"); - }); - - describe(`and servicesMetadata.app_android is defined`, () => { - const androidUrl = "http://www.android.google"; - const currentOptions = { - ...defaultProps, - servicesMetadata: { - ...defaultServiceMetadata, - app_android: androidUrl - } as ServiceMetadata - }; - it(`should render the Android link`, () => { - const component = renderComponent(currentOptions); - const link = component.getByRole("link"); - expect(link.children.toString()).toMatch( - I18n.t("services.otherAppAndroid") - ); - }); - it(`the link should open ${androidUrl}`, () => { - const component = renderComponent(currentOptions); - const link = component.getByRole("link"); - fireEvent(link, "onPress"); - expect(spyOpenWebUrl).toHaveBeenCalledWith( - androidUrl, - expect.any(Function) - ); - }); - }); - - describe(`and servicesMetadata.app_ios is defined`, () => { - const currentOptions = { - ...defaultProps, - servicesMetadata: { - ...defaultServiceMetadata, - app_ios: "dummy" - } as ServiceMetadata - }; - it(`should not render it`, () => { - expect(renderComponent(currentOptions).queryByRole("link")).toBeNull(); - }); - }); - }); - - describe("when the platform is iOS", () => { - beforeAll(() => { - // eslint-disable-next-line @typescript-eslint/no-var-requires - require("../../../../utils/platform").test_setPlatform("ios"); - }); - - describe(`and servicesMetadata.app_ios is defined`, () => { - const iosUrl = "http://www.ios.apple"; - const currentOptions = { - ...defaultProps, - servicesMetadata: { - ...defaultServiceMetadata, - app_ios: iosUrl - } as ServiceMetadata - }; - it(`should render the iOS link`, () => { - const component = renderComponent(currentOptions); - const link = component.getByRole("link"); - expect(link.children.toString()).toMatch( - I18n.t("services.otherAppIos") - ); - }); - it(`the link should open ${iosUrl}`, () => { - const component = renderComponent(currentOptions); - const link = component.getByRole("link"); - fireEvent(link, "onPress"); - expect(spyOpenWebUrl).toHaveBeenCalledWith( - iosUrl, - expect.any(Function) - ); - }); - }); - - describe(`and servicesMetadata.app_android is defined`, () => { - const currentOptions = { - ...defaultProps, - servicesMetadata: { - ...defaultServiceMetadata, - app_android: "dummy" - } as ServiceMetadata - }; - it(`should not render it`, () => { - expect(renderComponent(currentOptions).queryByRole("link")).toBeNull(); - }); - }); - }); -}); - -function renderComponent( - props: Parameters[0] -) { - return render(); -} diff --git a/ts/components/services/ServiceMetadata/__tests__/__snapshots__/InformationRow.test.tsx.snap b/ts/components/services/ServiceMetadata/__tests__/__snapshots__/InformationRow.test.tsx.snap deleted file mode 100644 index 907c0eb4256..00000000000 --- a/ts/components/services/ServiceMetadata/__tests__/__snapshots__/InformationRow.test.tsx.snap +++ /dev/null @@ -1,112 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`the InformationRow component should match the snapshot 1`] = ` - - - - Institution's Fiscal Code - - - - via Roma - - - - -`; diff --git a/ts/components/services/ServiceMetadata/index.tsx b/ts/components/services/ServiceMetadata/index.tsx deleted file mode 100644 index 89c9c00b2ca..00000000000 --- a/ts/components/services/ServiceMetadata/index.tsx +++ /dev/null @@ -1,151 +0,0 @@ -import { OrganizationFiscalCode } from "@pagopa/ts-commons/lib/strings"; -import React from "react"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { ServiceMetadata } from "../../../../definitions/backend/ServiceMetadata"; -import I18n from "../../../i18n"; -import { isTestEnv } from "../../../utils/environment"; -import { isAndroid, isIos } from "../../../utils/platform"; -import { ItemAction } from "../../../utils/url"; -import LinkRow from ".././LinkRow"; -import SectionHeader from ".././SectionHeader"; -import InformationRow from "./InformationRow"; - -type Props = { - getItemOnPress: (value: string, valueType?: ItemAction) => () => void; - isDebugModeEnabled: boolean; - organizationFiscalCode: OrganizationFiscalCode; - serviceId: ServiceId; - servicesMetadata?: ServiceMetadata; -}; - -/** - * Function used to generate the `accessibilityLabel` for a single - * row in the `ServiceMetadataComponent`. Given the `field`, `value, - * and `hint` it creates a custom label that contains all these - * informations. - */ -const genServiceMetadataAccessibilityLabel = ( - field: string, - value: string, - hint: string -) => `${field}: ${value}, ${hint}`; - -export const testableGenServiceMetadataAccessibilityLabel = isTestEnv - ? genServiceMetadataAccessibilityLabel - : undefined; - -/** - * Renders a dedicated section with a service's metadata and the header. - */ -const ServiceMetadataComponent: React.FC = ({ - organizationFiscalCode, - getItemOnPress, - serviceId, - servicesMetadata, - isDebugModeEnabled -}: Props) => { - const { - address, - app_android, - email, - app_ios, - pec, - phone, - support_url, - web_url - } = servicesMetadata || {}; - return ( - <> - - - {/* links */} - {web_url && } - {support_url && ( - - )} - {isIos && app_ios && ( - - )} - {isAndroid && app_android && ( - - )} - - {/* touchable rows */} - { - - } - {address && ( - - )} - {phone && ( - - )} - {email && ( - - )} - {pec && ( - - )} - {isDebugModeEnabled && serviceId && ( - - )} - - ); -}; - -export default ServiceMetadataComponent; diff --git a/ts/components/services/ServicesSearch.tsx b/ts/components/services/ServicesSearch.tsx deleted file mode 100644 index acb7d6cb7b0..00000000000 --- a/ts/components/services/ServicesSearch.tsx +++ /dev/null @@ -1,162 +0,0 @@ -/** - * A component that renders a list of services that match a search text. - * TODO: fix scroll: some items are displayed only if the keyboard is hidden - * https://www.pivotaltracker.com/story/show/168803731 - */ - -import * as pot from "@pagopa/ts-commons/lib/pot"; -import React from "react"; -import { SectionListData } from "react-native"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import { ServicesSectionState } from "../../store/reducers/entities/services"; -import { isDefined } from "../../utils/guards"; -import { serviceContainsText } from "../../utils/services"; -import { SearchNoResultMessage } from "../search/SearchNoResultMessage"; -import ServicesSectionsList from "./ServicesSectionsList"; - -type OwnProps = { - sectionsState: ReadonlyArray; - searchText: string; - onRefresh: () => void; - navigateToServiceDetail: (service: ServicePublic) => void; -}; - -type Props = OwnProps; - -type State = { - potFilteredServiceSectionsStates: pot.Pot< - ReadonlyArray, - Error - >; -}; - -/** - * Filter only the services that match the searchText. - */ -const generateSectionsServicesStateMatchingSearchTextArrayAsync = ( - servicesState: ReadonlyArray, - searchText: string -): Promise> => - new Promise(resolve => { - const result = servicesState - .map(section => - filterSectionListDataMatchingSearchText(section, searchText) - ) - .filter(isDefined); - - resolve(result); - }); - -function filterSectionListDataMatchingSearchText( - sectionListData: SectionListData>, - searchText: string -) { - const filteredData = sectionListData.data - .map(potService => - pot.filter(potService, servicePublic => - // Search in service properties - serviceContainsText(servicePublic, searchText) - ) - ) - .filter(pot.isSome); - - const sectionListDataFiltered = { - organizationName: sectionListData.organizationName, - organizationFiscalCode: sectionListData.organizationFiscalCode, - data: filteredData - }; - return filteredData.length > 0 ? sectionListDataFiltered : null; -} - -class ServicesSearch extends React.PureComponent { - constructor(props: Props) { - super(props); - this.state = { - potFilteredServiceSectionsStates: pot.noneLoading - }; - } - - public async componentDidMount() { - const { sectionsState, searchText } = this.props; - const { potFilteredServiceSectionsStates } = this.state; - - // Set filtering status - this.setState({ - potFilteredServiceSectionsStates: pot.toLoading( - potFilteredServiceSectionsStates - ) - }); - - // Start filtering services - const filteredServiceSectionsStates = - await generateSectionsServicesStateMatchingSearchTextArrayAsync( - sectionsState, - searchText - ); - - // Unset filtering status - this.setState({ - potFilteredServiceSectionsStates: pot.some(filteredServiceSectionsStates) - }); - } - - public async componentDidUpdate(prevProps: Props) { - const { sectionsState: prevServicesState, searchText: prevSearchText } = - prevProps; - const { sectionsState, searchText } = this.props; - const { potFilteredServiceSectionsStates } = this.state; - - if (sectionsState !== prevServicesState || searchText !== prevSearchText) { - // Set filtering status - this.setState({ - potFilteredServiceSectionsStates: pot.toLoading( - potFilteredServiceSectionsStates - ) - }); - - // Start filtering services - const filteredServiceSectionsStates = - await generateSectionsServicesStateMatchingSearchTextArrayAsync( - sectionsState, - searchText - ); - - // Unset filtering status - this.setState({ - potFilteredServiceSectionsStates: pot.some( - filteredServiceSectionsStates - ) - }); - } - } - - public render() { - const { potFilteredServiceSectionsStates } = this.state; - const { onRefresh } = this.props; - - const isFiltering = pot.isLoading(potFilteredServiceSectionsStates); - - const filteredServiceSectionsStates = pot.getOrElse( - potFilteredServiceSectionsStates, - [] - ); - - return filteredServiceSectionsStates.length > 0 ? ( - - ) : ( - - ); - } - - private handleOnServiceSelect = (service: ServicePublic) => { - this.props.navigateToServiceDetail(service); - }; -} - -export default ServicesSearch; diff --git a/ts/components/services/ServicesSectionsList.tsx b/ts/components/services/ServicesSectionsList.tsx deleted file mode 100644 index 9e30ae9ea87..00000000000 --- a/ts/components/services/ServicesSectionsList.tsx +++ /dev/null @@ -1,81 +0,0 @@ -/** - * A component to render a list of services organized in sections, one for each organization. - */ -import { VSpacer } from "@pagopa/io-app-design-system"; -import React from "react"; -import { - Image, - NativeScrollEvent, - NativeSyntheticEvent, - StyleSheet, - View -} from "react-native"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import I18n from "../../i18n"; -import { ServicesSectionState } from "../../store/reducers/entities/services"; -import customVariables from "../../theme/variables"; -import { Body } from "../core/typography/Body"; -import { IOStyles } from "../core/variables/IOStyles"; -import ServiceList from "./ServiceList"; - -type AnimatedProps = { - animated?: { - onScroll: (_: NativeSyntheticEvent) => void; - scrollEventThrottle?: number; - }; -}; - -type OwnProps = { - sections: ReadonlyArray; - isRefreshing: boolean; - onRefresh: () => void; - onSelect: (service: ServicePublic) => void; -}; - -type Props = AnimatedProps & OwnProps; - -const styles = StyleSheet.create({ - contentWrapper: { - flex: 1 - }, - headerContentWrapper: { - paddingTop: customVariables.contentPadding / 2, - paddingBottom: customVariables.contentPadding / 2, - alignItems: "center" - } -}); - -// component used when the list is empty -const emptyListComponent = () => ( - - - - - - {I18n.t("services.emptyListMessage")} - - -); - -const ServicesSectionsList = (props: Props) => ( - - {/* TODO: This is a workaround to make sure that the list is not placed under the tab bar - https://pagopa.atlassian.net/jira/software/projects/IOAPPFD0/boards/313?selectedIssue=IOAPPFD0-40 */} - - - -); - -export default ServicesSectionsList; diff --git a/ts/components/services/ServicesTab.tsx b/ts/components/services/ServicesTab.tsx deleted file mode 100644 index b38b8556e7b..00000000000 --- a/ts/components/services/ServicesTab.tsx +++ /dev/null @@ -1,45 +0,0 @@ -/** - * A component to render a tab containing a list of services organized in sections - */ -import * as React from "react"; -import { Animated } from "react-native"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import { ServicesSectionState } from "../../store/reducers/entities/services"; -import { withLightModalContext } from "../helpers/withLightModalContext"; -import { LightModalContextInterface } from "../ui/LightModal"; -import ServicesSectionsList from "./ServicesSectionsList"; - -type OwnProps = Readonly<{ - sections: ReadonlyArray; - isRefreshing: boolean; - onRefresh: (hideToast?: boolean) => void; // eslint-disable-line - onServiceSelect: (service: ServicePublic) => void; - tabScrollOffset: Animated.Value; -}>; - -type Props = OwnProps & LightModalContextInterface; - -const ServicesTab = (props: Props): React.ReactElement => { - const onTabScroll = () => ({ - onScroll: Animated.event([ - { - nativeEvent: { - contentOffset: { y: props.tabScrollOffset } - } - } - ]), - scrollEventThrottle: 8 - }); - - return ( - - ); -}; - -export default withLightModalContext(ServicesTab); diff --git a/ts/components/services/SpecialServices/LegacySpecialServicesCTA.tsx b/ts/components/services/SpecialServices/LegacySpecialServicesCTA.tsx deleted file mode 100644 index 107118a98e5..00000000000 --- a/ts/components/services/SpecialServices/LegacySpecialServicesCTA.tsx +++ /dev/null @@ -1,118 +0,0 @@ -import * as React from "react"; -import { constNull, pipe } from "fp-ts/lib/function"; -import * as B from "fp-ts/lib/boolean"; -import * as O from "fp-ts/lib/Option"; -import { ButtonSolid } from "@pagopa/io-app-design-system"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { cdcEnabled } from "../../../config"; -import CdcServiceCTA from "../../../features/bonus/cdc/components/CdcServiceCTA"; -import LegacyCgnServiceCTA from "../../../features/bonus/cgn/components/LegacyCgnServiceCTA"; -import LegacyPnServiceCTA from "../../../features/pn/components/LegacyServiceCTA"; -import I18n from "../../../i18n"; -import { useIOSelector } from "../../../store/hooks"; -import { - isCdcEnabledSelector, - isCGNEnabledSelector, - isPnEnabledSelector, - isPnAppVersionSupportedSelector -} from "../../../store/reducers/backendStatus"; -import { openAppStoreUrl } from "../../../utils/url"; - -type SpecialServiceConfig = { - isEnabled: boolean; - isSupported: boolean; -}; - -type Props = { - customSpecialFlowOpt?: string; - serviceId: ServiceId; - activate?: boolean; -}; - -const UpdateAppCTA = () => { - // utility to open the app store on the OS - const openAppStore = React.useCallback(() => openAppStoreUrl(), []); - - return ( - - ); -}; - -const renderCta = ( - isEnabled: boolean, - isSupported: boolean, - cta: JSX.Element -) => - pipe( - isEnabled, - B.fold(constNull, () => - pipe( - isSupported, - B.fold( - () => , - () => cta - ) - ) - ) - ); - -const LegacySpecialServicesCTA = (props: Props) => { - const { customSpecialFlowOpt } = props; - - const isCGNEnabled = useIOSelector(isCGNEnabledSelector); - const cdcEnabledSelector = useIOSelector(isCdcEnabledSelector); - - const isCdcEnabled = cdcEnabledSelector && cdcEnabled; - - const isPnEnabled = useIOSelector(isPnEnabledSelector); - const isPnSupported = useIOSelector(isPnAppVersionSupportedSelector); - - const mapSpecialServiceConfig = new Map([ - ["cgn", { isEnabled: isCGNEnabled, isSupported: true }], - ["cdc", { isEnabled: isCdcEnabled, isSupported: true }], - ["pn", { isEnabled: isPnEnabled, isSupported: isPnSupported }] - ]); - - return pipe( - customSpecialFlowOpt, - O.fromNullable, - O.fold(constNull, csf => - pipe( - mapSpecialServiceConfig.get(csf), - O.fromNullable, - O.fold( - () => , - ({ isEnabled, isSupported }) => { - switch (csf) { - case "cgn": - return renderCta( - isEnabled, - isSupported, - - ); - case "cdc": - return renderCta(isEnabled, isSupported, ); - case "pn": - return renderCta( - isEnabled, - isSupported, - - ); - default: - return ; - } - } - ) - ) - ) - ); -}; - -export default LegacySpecialServicesCTA; diff --git a/ts/components/services/TosAndPrivacyBox.tsx b/ts/components/services/TosAndPrivacyBox.tsx deleted file mode 100644 index 3beb2e53496..00000000000 --- a/ts/components/services/TosAndPrivacyBox.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import * as React from "react"; -import { View } from "react-native"; - -import LinkRow from "./LinkRow"; -import SectionHeader from "./SectionHeader"; - -type Props = { - privacyUrl?: string; - tosUrl?: string; -}; - -/** - * Renders a dedicated section with TOS, Privacy urls, and the header. - * It **doesn't render** if both links are not defined! - */ -const TosAndPrivacy: React.FC = ({ tosUrl, privacyUrl }) => { - if (tosUrl === undefined && privacyUrl === undefined) { - return null; - } - return ( - - - {tosUrl && } - {privacyUrl && } - - ); -}; - -export default TosAndPrivacy; diff --git a/ts/components/services/__tests__/LinkRow.test.tsx b/ts/components/services/__tests__/LinkRow.test.tsx deleted file mode 100644 index dae0e1b439f..00000000000 --- a/ts/components/services/__tests__/LinkRow.test.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import React from "react"; -import { render } from "@testing-library/react-native"; - -import LinkRow from "../LinkRow"; - -describe("LinkRow component", () => { - it("should match the snapshot", () => { - const component = render( - - ); - expect(component.toJSON()).toMatchSnapshot(); - }); -}); diff --git a/ts/components/services/__tests__/SectionHeader.test.tsx b/ts/components/services/__tests__/SectionHeader.test.tsx deleted file mode 100644 index 6d62e9fb5b7..00000000000 --- a/ts/components/services/__tests__/SectionHeader.test.tsx +++ /dev/null @@ -1,13 +0,0 @@ -import React from "react"; -import { render } from "@testing-library/react-native"; - -import SectionHeader from "../SectionHeader"; - -describe("SectionHeader component", () => { - it("should match the snapshot", () => { - const component = render( - - ); - expect(component.toJSON()).toMatchSnapshot(); - }); -}); diff --git a/ts/components/services/__tests__/TosAndPrivacyBox.test.tsx b/ts/components/services/__tests__/TosAndPrivacyBox.test.tsx deleted file mode 100644 index e37277a0504..00000000000 --- a/ts/components/services/__tests__/TosAndPrivacyBox.test.tsx +++ /dev/null @@ -1,104 +0,0 @@ -import { fireEvent, render } from "@testing-library/react-native"; -import React from "react"; - -import { IOToast } from "@pagopa/io-app-design-system"; -import I18n from "../../../i18n"; -import TosAndPrivacyBox from "../TosAndPrivacyBox"; - -// eslint-disable-next-line functional/no-let -let MOCK_URL_WILL_FAIL = false; - -const mockOpenWebUrl = jest.fn(); - -jest.mock("../../../utils/url", () => ({ - openWebUrl: (_: string, onError: () => void) => { - mockOpenWebUrl(); - // we rely on an internal of `openWebUrl`, this might be improved? - if (MOCK_URL_WILL_FAIL) { - onError(); - } - } -})); - -const options = { - tosUrl: "https://www.fsf.org/", - privacyUrl: "https://gnupg.org/" -}; - -describe("TosAndPrivacyBox component", () => { - beforeEach(() => { - mockOpenWebUrl.mockReset(); - MOCK_URL_WILL_FAIL = false; - }); - - it("should have one header", () => { - const component = renderComponent({ ...options }); - expect(component.getByRole("header")).toBeDefined(); - expect(component.getByText(I18n.t("services.tosAndPrivacy"))).toBeDefined(); - }); - - describe("when both URLs are defined", () => { - it("should call `openWebUrl` for TOS link", () => { - const component = renderComponent(options); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const link = component - .getAllByRole("link") - .find(item => item.children[0] === I18n.t("services.tosLink"))!; - fireEvent(link, "onPress"); - expect(mockOpenWebUrl).toHaveBeenCalledTimes(1); - }); - - it("should call `openWebUrl` for Privacy link", () => { - const component = renderComponent(options); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const link = component - .getAllByRole("link") - .find(item => item.children[0] === I18n.t("services.privacyLink"))!; - fireEvent(link, "onPress"); - expect(mockOpenWebUrl).toHaveBeenCalledTimes(1); - }); - - it("should call `showToast` when then link fails", () => { - MOCK_URL_WILL_FAIL = true; - const component = renderComponent(options); - const showToastSpy = jest.spyOn(IOToast, "error"); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const link = component - .getAllByRole("link") - .find(item => item.children[0] === I18n.t("services.privacyLink"))!; - fireEvent(link, "onPress"); - expect(showToastSpy).toHaveBeenCalledTimes(1); - }); - }); - - describe("when either URL is not defined", () => { - it("should not render TOS link", () => { - expect( - renderComponent({ ...options, tosUrl: undefined }) - .getAllByRole("link") - .find(item => item.children[0] === I18n.t("services.tosLink")) - ).toBeUndefined(); - }); - - it("should not render Privacy link", () => { - expect( - renderComponent({ ...options, privacyUrl: undefined }) - .getAllByRole("link") - .find(item => item.children[0] === I18n.t("services.privacyLink")) - ).toBeUndefined(); - }); - }); - - describe("when neither URL is defined", () => { - it("should not render anything", () => { - expect(renderComponent({}).toJSON()).toEqual(null); - }); - }); -}); - -function renderComponent({ - tosUrl, - privacyUrl -}: Parameters[0]) { - return render(); -} diff --git a/ts/components/services/__tests__/__snapshots__/LinkRow.test.tsx.snap b/ts/components/services/__tests__/__snapshots__/LinkRow.test.tsx.snap deleted file mode 100644 index aae05bcac23..00000000000 --- a/ts/components/services/__tests__/__snapshots__/LinkRow.test.tsx.snap +++ /dev/null @@ -1,55 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`LinkRow component should match the snapshot 1`] = ` -Array [ - - Email - , - , -] -`; diff --git a/ts/components/services/__tests__/__snapshots__/SectionHeader.test.tsx.snap b/ts/components/services/__tests__/__snapshots__/SectionHeader.test.tsx.snap deleted file mode 100644 index 792bd226546..00000000000 --- a/ts/components/services/__tests__/__snapshots__/SectionHeader.test.tsx.snap +++ /dev/null @@ -1,110 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`SectionHeader component should match the snapshot 1`] = ` - - - - - - - - - ID - - -`; diff --git a/ts/components/ui/TabNavigation.tsx b/ts/components/ui/TabNavigation.tsx deleted file mode 100644 index 0b5b546ab1f..00000000000 --- a/ts/components/ui/TabNavigation.tsx +++ /dev/null @@ -1,114 +0,0 @@ -import React from "react"; -import { FlexStyle, LayoutChangeEvent, StyleSheet, View } from "react-native"; -import { ScrollView } from "react-native-gesture-handler"; -import { TabItem } from "./TabItem"; - -export type TabNavigationItem = Omit< - TabItem, - "onPress" | "color" | "selected" | "accessibilityLabel" | "accessibilityHint" ->; - -type TabNavigationChildren = - | React.ReactElement - | Array>; - -type TabAlignment = "start" | "center" | "end" | "stretch"; - -type TabNavigation = { - // Configuration - color?: TabItem["color"]; - selectedIndex?: number; - tabAlignment?: TabAlignment; - // Events - onItemPress?: (index: number) => void; - // Tabs - children: TabNavigationChildren; -}; - -const itemsJustify: Record = { - start: "flex-start", - center: "center", - end: "flex-end", - stretch: "space-between" -}; - -const TabNavigation = ({ - color = "light", - selectedIndex: forceSelectedIndex, - tabAlignment = "center", - onItemPress, - children -}: TabNavigation) => { - const [itemMinWidth, setItemMinWidth] = React.useState(0); - const [selectedIndex, setSelectedIndex] = React.useState( - forceSelectedIndex ?? 0 - ); - - const handleItemPress = (index: number) => { - setSelectedIndex(forceSelectedIndex ?? index); - onItemPress?.(index); - }; - - const handleItemOnLayout = (event: LayoutChangeEvent) => { - const { width } = event.nativeEvent.layout; - setItemMinWidth(current => Math.max(current, width)); - }; - - const stretchItems = tabAlignment === "stretch"; - - const wrapChild = (child: React.ReactElement, index: number = 0) => ( - - {React.cloneElement(child, { - onPress: event => { - child.props.onPress?.(event); - handleItemPress(index); - }, - selected: selectedIndex === index, - color - })} - - ); - - return ( - - {Array.isArray(children) ? children.map(wrapChild) : wrapChild(children)} - - ); -}; - -const styles = StyleSheet.create({ - container: { - flexGrow: 1, - paddingHorizontal: 24 - }, - item: { - flexGrow: 0, - flexShrink: 1, - flexBasis: 100, - alignItems: "center" - } -}); - -export { TabNavigation }; diff --git a/ts/config.ts b/ts/config.ts index ebdd49c6fe9..174c24247fa 100644 --- a/ts/config.ts +++ b/ts/config.ts @@ -36,9 +36,6 @@ const DEFAULT_FAST_LOGIN_MAX_RETRIES = 3; // Default number of workers to fetch message. const DEFAULT_TOT_MESSAGE_FETCH_WORKERS = 5; -// Default number of workers to fetch service. -const DEFAULT_TOT_SERVICE_FETCH_WORKERS = 5; - // TODO: calculate the page size based on available screen space and item's height // https://pagopa.atlassian.net/browse/IA-474 const DEFAULT_PAGE_SIZE = 12; @@ -151,12 +148,6 @@ export const totMessageFetchWorkers = pipe( E.getOrElse(() => DEFAULT_TOT_MESSAGE_FETCH_WORKERS) ); -export const totServiceFetchWorkers = pipe( - parseInt(Config.TOT_SERVICE_FETCH_WORKERS, 10), - t.Integer.decode, - E.getOrElse(() => DEFAULT_TOT_SERVICE_FETCH_WORKERS) -); - export const shufflePinPadOnPayment = Config.SHUFFLE_PINPAD_ON_PAYMENT === "YES"; @@ -172,12 +163,6 @@ export const zendeskPrivacyUrl: string = pipe( E.getOrElse(() => "https://www.pagopa.it/it/privacy-policy-assistenza/") ); -export const localServicesWebUrl: string = pipe( - Config.LOCAL_SERVICE_WEB_URL, - t.string.decode, - E.getOrElse(() => "https://io.italia.it") -); - export const unsupportedDeviceMoreInfoUrl: string = pipe( Config.UNSUPPORTED_DEVICE_MORE_INFO_URL, NonEmptyString.decode, diff --git a/ts/features/bonus/cgn/components/CgnServiceCTA.tsx b/ts/features/bonus/cgn/components/CgnServiceCTA.tsx index ba10902f8cf..131839402a4 100644 --- a/ts/features/bonus/cgn/components/CgnServiceCTA.tsx +++ b/ts/features/bonus/cgn/components/CgnServiceCTA.tsx @@ -6,9 +6,9 @@ import * as pot from "@pagopa/ts-commons/lib/pot"; import I18n from "../../../../i18n"; import { useIODispatch, useIOSelector } from "../../../../store/hooks"; import { - servicePreferenceResponseSuccessSelector, - servicePreferenceSelector -} from "../../../services/details/store/reducers/servicePreference"; + servicePreferencePotSelector, + servicePreferenceResponseSuccessSelector +} from "../../../services/details/store/reducers"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { cgnActivationStart } from "../store/actions/activation"; import { cgnUnsubscribe } from "../store/actions/unsubscribe"; @@ -31,7 +31,7 @@ export const CgnServiceCta = ({ serviceId }: CgnServiceCtaProps) => { servicePreferenceResponseSuccessSelector ); - const servicePreferencePot = useIOSelector(servicePreferenceSelector); + const servicePreferencePot = useIOSelector(servicePreferencePotSelector); const unsubscriptionStatus = useIOSelector(cgnUnsubscribeSelector); diff --git a/ts/features/bonus/cgn/components/LegacyCgnServiceCTA.tsx b/ts/features/bonus/cgn/components/LegacyCgnServiceCTA.tsx index 810dd4b461d..9beb95491ad 100644 --- a/ts/features/bonus/cgn/components/LegacyCgnServiceCTA.tsx +++ b/ts/features/bonus/cgn/components/LegacyCgnServiceCTA.tsx @@ -10,7 +10,7 @@ import { } from "@pagopa/io-app-design-system"; import I18n from "../../../../i18n"; import { useIODispatch, useIOSelector } from "../../../../store/hooks"; -import { servicePreferenceSelector } from "../../../services/details/store/reducers/servicePreference"; +import { servicePreferencePotSelector } from "../../../services/details/store/reducers"; import { isServicePreferenceResponseSuccess } from "../../../services/details/types/ServicePreferenceResponse"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { cgnActivationStart } from "../store/actions/activation"; @@ -27,10 +27,10 @@ type Props = { const LegacyCgnServiceCTA = (props: Props) => { const isFirstRender = useRef(true); const dispatch = useIODispatch(); - const servicePreference = useIOSelector(servicePreferenceSelector); + const servicePreferencePot = useIOSelector(servicePreferencePotSelector); const unsubscriptionStatus = useIOSelector(cgnUnsubscribeSelector); - const servicePreferenceValue = pot.getOrElse(servicePreference, undefined); + const servicePreferenceValue = pot.getOrElse(servicePreferencePot, undefined); useEffect(() => { if (!isFirstRender.current) { diff --git a/ts/features/bonus/cgn/screens/merchants/CgnMerchantsTabsScreen.tsx b/ts/features/bonus/cgn/screens/merchants/CgnMerchantsTabsScreen.tsx index 3d02f4791f5..b89b01dfc97 100644 --- a/ts/features/bonus/cgn/screens/merchants/CgnMerchantsTabsScreen.tsx +++ b/ts/features/bonus/cgn/screens/merchants/CgnMerchantsTabsScreen.tsx @@ -82,7 +82,7 @@ const CgnMerchantsTabsScreen: React.FunctionComponent = (_: Props) => { isSearchAvailable={{ enabled: true, onSearchTap: openFiltersModal }} > - {/* TABS component should be replaced with MaterialTopTab Navigator as done in Services and Messages home */} + {/* TABS component should be replaced with MaterialTopTab Navigator as done in Messages home */} {/* { // TODO: add mixpanel tracking and alert: https://pagopa.atlassian.net/browse/AP-14 IOToast.show(I18n.t("bonus.cdc.serviceEntryPoint.notAvailable")); }, - s => () => { - this.props.showServiceDetails(s); + s => () => this.props.navigateToServiceDetailsScreen({ serviceId: s.service_id - }); - } + }) ) ); }); @@ -242,9 +238,7 @@ const mapDispatchToProps = (dispatch: Dispatch) => ({ navigateToServiceDetailsScreen(params), serviceDetailsLoad: (serviceId: ServiceId) => { dispatch(loadServiceDetail.request(serviceId)); - }, - showServiceDetails: (service: ServicePublic) => - dispatch(showServiceDetails(service)) + } }); const AvailableBonusScreenFC: React.FunctionComponent = ( diff --git a/ts/features/bonus/common/store/selectors/index.ts b/ts/features/bonus/common/store/selectors/index.ts index 9f02c7c371f..42f040cd766 100644 --- a/ts/features/bonus/common/store/selectors/index.ts +++ b/ts/features/bonus/common/store/selectors/index.ts @@ -8,7 +8,7 @@ import { GlobalState } from "../../../../../store/reducers/types"; import { ServicePublic } from "../../../../../../definitions/backend/ServicePublic"; import { BonusVisibilityEnum } from "../../../../../../definitions/content/BonusVisibility"; -import { servicesByIdSelector } from "../../../../services/details/store/reducers/servicesById"; +import { servicesByIdSelector } from "../../../../services/details/store/reducers"; import { mapBonusIdFeatureFlag } from "../../utils"; import { AvailableBonusTypesState } from "../reducers/availableBonusesTypes"; diff --git a/ts/features/design-system/core/DSGradientScroll.tsx b/ts/features/design-system/core/DSGradientScroll.tsx deleted file mode 100644 index 4c0e4bfaaff..00000000000 --- a/ts/features/design-system/core/DSGradientScroll.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import * as React from "react"; -import { Alert, View } from "react-native"; -import { - ButtonOutline, - GradientScrollView, - IOColors -} from "@pagopa/io-app-design-system"; -import { H2 } from "../../../components/core/typography/H2"; -import { Body } from "../../../components/core/typography/Body"; - -export const DSGradientScroll = () => ( - - Alert.alert("Primary action pressed! (⁠⁠ꈍ⁠ᴗ⁠ꈍ⁠)") - }} - > -

Start

- {[...Array(50)].map((_el, i) => ( - Repeated text - ))} - Alert.alert("Test button")} - /> - {[...Array(2)].map((_el, i) => ( - Repeated text - ))} -

End

-
-
-); diff --git a/ts/features/design-system/core/DSLegacyPictograms.tsx b/ts/features/design-system/core/DSLegacyPictograms.tsx index db4795a66fd..a24e04cd1d4 100644 --- a/ts/features/design-system/core/DSLegacyPictograms.tsx +++ b/ts/features/design-system/core/DSLegacyPictograms.tsx @@ -23,7 +23,6 @@ import Question from "../../../../img/pictograms/doubt.png"; import CompletedRaster from "../../../../img/pictograms/payment-completed.png"; import BeerMug from "../../../../img/search/beer-mug.png"; import Search from "../../../../img/search/search-icon.png"; -import Puzzle from "../../../../img/services/icon-loading-services.png"; import ABILogo from "../../../../img/wallet/cards-icons/abiLogoFallback.png"; import Umbrella from "../../../../img/wallet/errors/generic-error-icon.png"; import NotAvailable from "../../../../img/wallet/errors/payment-unavailable-icon.png"; @@ -119,11 +118,6 @@ export const DSLegacyPictograms = () => { name={"Search"} image={renderRasterImage(Search)} /> - { const dispatch = useIODispatch(); const fciServiceId = useIOSelector(fciMetadataServiceIdSelector); - const servicePreference = useIOSelector(servicePreferenceSelector); + const servicePreferencePot = useIOSelector(servicePreferencePotSelector); const fciEnvironment = useIOSelector(fciEnvironmentSelector); - const servicePreferenceValue = pot.getOrElse(servicePreference, undefined); + const servicePreferenceValue = pot.getOrElse(servicePreferencePot, undefined); const cancelButtonProps: ButtonSolidProps = { onPress: () => { dispatch(fciStartSigningRequest()); diff --git a/ts/features/fci/screens/valid/FciQtspClausesScreen.tsx b/ts/features/fci/screens/valid/FciQtspClausesScreen.tsx index cc1026b6ec7..8154a29627b 100644 --- a/ts/features/fci/screens/valid/FciQtspClausesScreen.tsx +++ b/ts/features/fci/screens/valid/FciQtspClausesScreen.tsx @@ -29,7 +29,7 @@ import { } from "../../store/reducers/fciPollFilledDocument"; import GenericErrorComponent from "../../components/GenericErrorComponent"; import LinkedText from "../../components/LinkedText"; -import { servicePreferenceSelector } from "../../../services/details/store/reducers/servicePreference"; +import { servicePreferencePotSelector } from "../../../services/details/store/reducers"; import { loadServicePreference } from "../../../services/details/store/actions/preference"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { useFciCheckService } from "../../hooks/useFciCheckService"; @@ -45,7 +45,7 @@ const FciQtspClausesScreen = () => { const dispatch = useIODispatch(); const navigation = useIONavigation(); const [clausesChecked, setClausesChecked] = React.useState(0); - const servicePreference = useIOSelector(servicePreferenceSelector); + const servicePreferencePot = useIOSelector(servicePreferencePotSelector); const qtspClausesSelector = useIOSelector(fciQtspClausesSelector); const qtspPrivacyTextSelector = useIOSelector(fciQtspPrivacyTextSelector); const qtspPrivacyUrlSelector = useIOSelector(fciQtspPrivacyUrlSelector); @@ -58,7 +58,7 @@ const FciQtspClausesScreen = () => { const fciServiceId = useIOSelector(fciMetadataServiceIdSelector); const fciEnvironment = useIOSelector(fciEnvironmentSelector); - const servicePreferenceValue = pot.getOrElse(servicePreference, undefined); + const servicePreferenceValue = pot.getOrElse(servicePreferencePot, undefined); const isServiceActive = servicePreferenceValue && diff --git a/ts/features/fims/singleSignOn/components/FimsSuccessBody.tsx b/ts/features/fims/singleSignOn/components/FimsSuccessBody.tsx index 52d138df9fb..ce8e2fe25bf 100644 --- a/ts/features/fims/singleSignOn/components/FimsSuccessBody.tsx +++ b/ts/features/fims/singleSignOn/components/FimsSuccessBody.tsx @@ -27,7 +27,7 @@ import { useIODispatch, useIOSelector } from "../../../../store/hooks"; import { useIOBottomSheetModal } from "../../../../utils/hooks/bottomSheet"; import { openWebUrl } from "../../../../utils/url"; import { loadServiceDetail } from "../../../services/details/store/actions/details"; -import { serviceByIdSelector } from "../../../services/details/store/reducers/servicesById"; +import { serviceByIdSelector } from "../../../services/details/store/reducers"; import { logoForService } from "../../../services/home/utils"; import { fimsGetRedirectUrlAndOpenIABAction } from "../store/actions"; import { ConsentData, FimsClaimType } from "../types"; diff --git a/ts/features/idpay/onboarding/screens/PDNDPrerequisitesScreen.tsx b/ts/features/idpay/onboarding/screens/PDNDPrerequisitesScreen.tsx index 60122d88c98..efabe0af636 100644 --- a/ts/features/idpay/onboarding/screens/PDNDPrerequisitesScreen.tsx +++ b/ts/features/idpay/onboarding/screens/PDNDPrerequisitesScreen.tsx @@ -22,7 +22,7 @@ import I18n from "../../../../i18n"; import { useIOSelector } from "../../../../store/hooks"; import { emptyContextualHelp } from "../../../../utils/emptyContextualHelp"; import { useIOBottomSheetAutoresizableModal } from "../../../../utils/hooks/bottomSheet"; -import { serviceByIdPotSelector } from "../../../services/details/store/reducers/servicesById"; +import { serviceByIdPotSelector } from "../../../services/details/store/reducers"; import { getPDNDCriteriaDescription } from "../utils/strings"; import { useOnboardingMachineService } from "../xstate/provider"; import { pdndCriteriaSelector, selectServiceId } from "../xstate/selectors"; diff --git a/ts/features/messages/components/Home/__tests__/homeUtils.test.ts b/ts/features/messages/components/Home/__tests__/homeUtils.test.ts index 91cdfd6ed79..ada73a79f83 100644 --- a/ts/features/messages/components/Home/__tests__/homeUtils.test.ts +++ b/ts/features/messages/components/Home/__tests__/homeUtils.test.ts @@ -377,10 +377,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return undefined, defined organization fiscal code", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.none + details: { + byId: { + [serviceId]: pot.none + } } } } @@ -396,10 +398,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return undefined, undefined organization fiscal code, service pot.noneLoading", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.noneLoading + details: { + byId: { + [serviceId]: pot.noneLoading + } } } } @@ -414,10 +418,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return undefined, undefined organization fiscal code, service pot.someLoading", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.someLoading({}) + details: { + byId: { + [serviceId]: pot.someLoading({}) + } } } } @@ -432,9 +438,11 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service unmatching", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: {} + details: { + byId: {} + } } } } as GlobalState; @@ -449,10 +457,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service pot.none", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.none + details: { + byId: { + [serviceId]: pot.none + } } } } @@ -468,10 +478,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service pot.noneUpdating", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.noneUpdating({}) + details: { + byId: { + [serviceId]: pot.noneUpdating({}) + } } } } @@ -487,10 +499,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service pot.noneError", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.noneError(new Error()) + details: { + byId: { + [serviceId]: pot.noneError(new Error()) + } } } } @@ -506,10 +520,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service pot.some", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.some({}) + details: { + byId: { + [serviceId]: pot.some({}) + } } } } @@ -525,10 +541,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service pot.someUpdating", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.someUpdating({}, {}) + details: { + byId: { + [serviceId]: pot.someUpdating({}, {}) + } } } } @@ -544,10 +562,12 @@ describe("getLoadServiceDetailsActionIfNeeded", () => { it("should return loadServiceDetail.request, undefined organization fiscal code, service pot.someError", () => { const serviceId = "01HYE2HRFESQ9TN5E1WZ99AW8Z" as ServiceId; const globalState = { - entities: { + features: { services: { - byId: { - [serviceId]: pot.someError({}, new Error()) + details: { + byId: { + [serviceId]: pot.someError({}, new Error()) + } } } } diff --git a/ts/features/messages/components/Home/homeUtils.ts b/ts/features/messages/components/Home/homeUtils.ts index 62cbe242373..d5c6a2dc268 100644 --- a/ts/features/messages/components/Home/homeUtils.ts +++ b/ts/features/messages/components/Home/homeUtils.ts @@ -11,7 +11,7 @@ import I18n from "../../../../i18n"; import { convertReceivedDateToAccessible } from "../../utils/convertDateToWordDistance"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { loadServiceDetail } from "../../../services/details/store/actions/details"; -import { isLoadingServiceByIdSelector } from "../../../services/details/store/reducers/servicesById"; +import { isLoadingServiceByIdSelector } from "../../../services/details/store/reducers"; import { messagePagePotFromCategorySelector, shownMessageCategorySelector diff --git a/ts/features/messages/components/MessageDetail/MessageDetailsFooter.tsx b/ts/features/messages/components/MessageDetail/MessageDetailsFooter.tsx index 447d84e4c8d..ff2c284bfcf 100644 --- a/ts/features/messages/components/MessageDetail/MessageDetailsFooter.tsx +++ b/ts/features/messages/components/MessageDetail/MessageDetailsFooter.tsx @@ -2,7 +2,7 @@ import React, { useMemo } from "react"; import { StyleSheet, View } from "react-native"; import { IOColors, IOStyles, VSpacer } from "@pagopa/io-app-design-system"; import { useIOSelector } from "../../../../store/hooks"; -import { serviceMetadataByIdSelector } from "../../../services/details/store/reducers/servicesById"; +import { serviceMetadataByIdSelector } from "../../../services/details/store/reducers"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { UIMessageId } from "../../types"; import I18n from "../../../../i18n"; diff --git a/ts/features/messages/components/MessageDetail/MessageDetailsHeader.tsx b/ts/features/messages/components/MessageDetail/MessageDetailsHeader.tsx index fc23444f859..60bef8c2548 100644 --- a/ts/features/messages/components/MessageDetail/MessageDetailsHeader.tsx +++ b/ts/features/messages/components/MessageDetail/MessageDetailsHeader.tsx @@ -7,9 +7,9 @@ import * as pot from "@pagopa/ts-commons/lib/pot"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { localeDateFormat } from "../../../../utils/locale"; import I18n from "../../../../i18n"; -import { logosForService } from "../../../../utils/services"; +import { logosForService } from "../../../services/common/utils"; import { useIOSelector } from "../../../../store/hooks"; -import { serviceByIdPotSelector } from "../../../services/details/store/reducers/servicesById"; +import { serviceByIdPotSelector } from "../../../services/details/store/reducers"; import { gapBetweenItemsInAGrid } from "../../utils"; import { OrganizationHeader } from "./OrganizationHeader"; diff --git a/ts/features/messages/saga/__test__/handleLoadMessageData.test.ts b/ts/features/messages/saga/__test__/handleLoadMessageData.test.ts index b4b0726ef98..5db69f1c4b5 100644 --- a/ts/features/messages/saga/__test__/handleLoadMessageData.test.ts +++ b/ts/features/messages/saga/__test__/handleLoadMessageData.test.ts @@ -12,7 +12,7 @@ import { upsertMessageStatusAttributes } from "../../store/actions"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; -import { serviceByIdPotSelector } from "../../../services/details/store/reducers/servicesById"; +import { serviceByIdPotSelector } from "../../../services/details/store/reducers"; import { loadServiceDetail } from "../../../services/details/store/actions/details"; import { messageDetailsByIdSelector } from "../../store/reducers/detailsById"; import { ThirdPartyMessageWithContent } from "../../../../../definitions/backend/ThirdPartyMessageWithContent"; diff --git a/ts/features/messages/saga/handleLoadMessageData.ts b/ts/features/messages/saga/handleLoadMessageData.ts index 52240ef0fa4..609d6a1b64f 100644 --- a/ts/features/messages/saga/handleLoadMessageData.ts +++ b/ts/features/messages/saga/handleLoadMessageData.ts @@ -18,7 +18,7 @@ import { } from "../store/actions"; import { getPaginatedMessageById } from "../store/reducers/paginatedById"; import { UIMessage, UIMessageDetails, UIMessageId } from "../types"; -import { serviceByIdPotSelector } from "../../services/details/store/reducers/servicesById"; +import { serviceByIdPotSelector } from "../../services/details/store/reducers"; import { loadServiceDetail } from "../../services/details/store/actions/details"; import { messageDetailsByIdSelector } from "../store/reducers/detailsById"; import { thirdPartyFromIdSelector } from "../store/reducers/thirdPartyById"; diff --git a/ts/features/messages/screens/MessageDetailsScreen.tsx b/ts/features/messages/screens/MessageDetailsScreen.tsx index f31db11524e..4c0bad7d722 100644 --- a/ts/features/messages/screens/MessageDetailsScreen.tsx +++ b/ts/features/messages/screens/MessageDetailsScreen.tsx @@ -40,7 +40,7 @@ import { cancelPaymentStatusTracking } from "../../pn/store/actions"; import { userSelectedPaymentRptIdSelector } from "../store/reducers/payments"; import { MessageDetailsStickyFooter } from "../components/MessageDetail/MessageDetailsStickyFooter"; import { MessageDetailsScrollViewAdditionalSpace } from "../components/MessageDetail/MessageDetailsScrollViewAdditionalSpace"; -import { serviceMetadataByIdSelector } from "../../services/details/store/reducers/servicesById"; +import { serviceMetadataByIdSelector } from "../../services/details/store/reducers"; import { isPNOptInMessage } from "../../pn/utils"; import { useOnFirstRender } from "../../../utils/hooks/useOnFirstRender"; import { diff --git a/ts/features/messages/screens/legacy/LegacyMessageDetailScreen.tsx b/ts/features/messages/screens/legacy/LegacyMessageDetailScreen.tsx index 9d37515e327..de4abc5e4b8 100644 --- a/ts/features/messages/screens/legacy/LegacyMessageDetailScreen.tsx +++ b/ts/features/messages/screens/legacy/LegacyMessageDetailScreen.tsx @@ -35,7 +35,7 @@ import { UIMessageId } from "../../types"; import { serviceByIdPotSelector, serviceMetadataByIdSelector -} from "../../../services/details/store/reducers/servicesById"; +} from "../../../services/details/store/reducers"; import { toUIService } from "../../../../store/reducers/entities/services/transformers"; import { useOnFirstRender } from "../../../../utils/hooks/useOnFirstRender"; import { useIODispatch, useIOSelector } from "../../../../store/hooks"; diff --git a/ts/features/pn/components/LegacyServiceCTA.tsx b/ts/features/pn/components/LegacyServiceCTA.tsx index f6bd24a2a6b..bcb2d9a7fa9 100644 --- a/ts/features/pn/components/LegacyServiceCTA.tsx +++ b/ts/features/pn/components/LegacyServiceCTA.tsx @@ -11,7 +11,7 @@ import { LoadingIndicator } from "../../../components/ui/LoadingIndicator"; import { ServiceId } from "../../../../definitions/backend/ServiceId"; import I18n from "../../../i18n"; import { useIODispatch, useIOSelector } from "../../../store/hooks"; -import { servicePreferenceSelector } from "../../services/details/store/reducers/servicePreference"; +import { servicePreferencePotSelector } from "../../services/details/store/reducers"; import { isServicePreferenceResponseSuccess } from "../../services/details/types/ServicePreferenceResponse"; import { AppDispatch } from "../../../App"; import { pnActivationUpsert } from "../store/actions"; @@ -61,11 +61,11 @@ const LegacyPnServiceCTA = ({ serviceId, activate }: Props) => { const dispatch = useIODispatch(); const serviceActivation = useIOSelector(pnActivationSelector); - const servicePreference = useIOSelector(servicePreferenceSelector); - const servicePreferenceValue = pot.getOrElse(servicePreference, undefined); + const servicePreferencePot = useIOSelector(servicePreferencePotSelector); + const servicePreferenceValue = pot.getOrElse(servicePreferencePot, undefined); const isLoading = - pot.isLoading(servicePreference) || + pot.isLoading(servicePreferencePot) || pot.isLoading(serviceActivation) || pot.isUpdating(serviceActivation); diff --git a/ts/features/pn/components/MessageBottomMenu.tsx b/ts/features/pn/components/MessageBottomMenu.tsx index cf0db7b4df2..9f2d62ce7d4 100644 --- a/ts/features/pn/components/MessageBottomMenu.tsx +++ b/ts/features/pn/components/MessageBottomMenu.tsx @@ -3,7 +3,7 @@ import React, { useMemo } from "react"; import { StyleSheet, View } from "react-native"; import { ContactsListItem } from "../../messages/components/MessageDetail/ContactsListItem"; import { useIOSelector } from "../../../store/hooks"; -import { serviceMetadataByIdSelector } from "../../services/details/store/reducers/servicesById"; +import { serviceMetadataByIdSelector } from "../../services/details/store/reducers"; import { ServiceId } from "../../../../definitions/backend/ServiceId"; import { ShowMoreListItem, diff --git a/ts/features/pn/components/MessageDetailsHeader.tsx b/ts/features/pn/components/MessageDetailsHeader.tsx index d46ca6acd70..fbd272008dc 100644 --- a/ts/features/pn/components/MessageDetailsHeader.tsx +++ b/ts/features/pn/components/MessageDetailsHeader.tsx @@ -1,7 +1,7 @@ import React from "react"; import { ServicePublic } from "../../../../definitions/backend/ServicePublic"; import OrganizationHeader from "../../../components/OrganizationHeader"; -import { logosForService } from "../../../utils/services"; +import { logosForService } from "../../services/common/utils"; type Props = Readonly<{ service: ServicePublic }>; diff --git a/ts/features/pn/components/ServiceCTA.tsx b/ts/features/pn/components/ServiceCTA.tsx index 7d7e43464fb..93b06943bd1 100644 --- a/ts/features/pn/components/ServiceCTA.tsx +++ b/ts/features/pn/components/ServiceCTA.tsx @@ -7,9 +7,9 @@ import { ServiceId } from "../../../../definitions/backend/ServiceId"; import I18n from "../../../i18n"; import { useIODispatch, useIOSelector } from "../../../store/hooks"; import { - servicePreferenceResponseSuccessSelector, - servicePreferenceSelector -} from "../../services/details/store/reducers/servicePreference"; + servicePreferencePotSelector, + servicePreferenceResponseSuccessSelector +} from "../../services/details/store/reducers"; import { pnActivationUpsert } from "../store/actions"; import { isLoadingPnActivationSelector } from "../store/reducers/activation"; import { useOnFirstRender } from "../../../utils/hooks/useOnFirstRender"; @@ -32,7 +32,7 @@ export const PnServiceCta = ({ serviceId, activate }: PnServiceCtaProps) => { servicePreferenceResponseSuccessSelector ); - const servicePreferencePot = useIOSelector(servicePreferenceSelector); + const servicePreferencePot = useIOSelector(servicePreferencePotSelector); const isLoadingPnActivation = useIOSelector(isLoadingPnActivationSelector); diff --git a/ts/features/pn/screens/LegacyMessageDetailsScreen.tsx b/ts/features/pn/screens/LegacyMessageDetailsScreen.tsx index c0684526fc2..541c66d875f 100644 --- a/ts/features/pn/screens/LegacyMessageDetailsScreen.tsx +++ b/ts/features/pn/screens/LegacyMessageDetailsScreen.tsx @@ -9,7 +9,7 @@ import BaseScreenComponent from "../../../components/screens/BaseScreenComponent import I18n from "../../../i18n"; import { IOStackNavigationRouteProps } from "../../../navigation/params/AppParamsList"; import { useIODispatch, useIOSelector, useIOStore } from "../../../store/hooks"; -import { serviceByIdPotSelector } from "../../services/details/store/reducers/servicesById"; +import { serviceByIdSelector } from "../../services/details/store/reducers"; import { emptyContextualHelp } from "../../../utils/emptyContextualHelp"; import { useOnFirstRender } from "../../../utils/hooks/useOnFirstRender"; import { LegacyMessageDetails } from "../components/LegacyMessageDetails"; @@ -47,9 +47,7 @@ export const LegacyMessageDetailsScreen = ( const dispatch = useIODispatch(); const navigation = useNavigation(); - const service = pot.toUndefined( - useIOSelector(state => serviceByIdPotSelector(state, serviceId)) - ); + const service = useIOSelector(state => serviceByIdSelector(state, serviceId)); const currentFiscalCode = useIOSelector(profileFiscalCodeSelector); const messagePot = useIOSelector(state => diff --git a/ts/features/pn/store/sagas/watchPnSaga.ts b/ts/features/pn/store/sagas/watchPnSaga.ts index 7752be83d76..551578cd486 100644 --- a/ts/features/pn/store/sagas/watchPnSaga.ts +++ b/ts/features/pn/store/sagas/watchPnSaga.ts @@ -16,7 +16,7 @@ import { trackPNServiceStatusChangeError, trackPNServiceStatusChangeSuccess } from "../../analytics"; -import { servicePreferenceSelector } from "../../../services/details/store/reducers/servicePreference"; +import { servicePreferencePotSelector } from "../../../services/details/store/reducers"; import { isServicePreferenceResponseSuccess } from "../../../services/details/types/ServicePreferenceResponse"; import { watchPaymentStatusForMixpanelTracking } from "./watchPaymentStatusSaga"; @@ -62,7 +62,9 @@ function* handlePnActivation( } function* reportPNServiceStatusOnFailure(predictedValue: boolean) { - const selectedServicePreferencePot = yield* select(servicePreferenceSelector); + const selectedServicePreferencePot = yield* select( + servicePreferencePotSelector + ); const isServiceActive = pipe( selectedServicePreferencePot, pot.toOption, diff --git a/ts/features/services/common/store/reducers/index.ts b/ts/features/services/common/store/reducers/index.ts index 53ac7faa9aa..7a007fc7a8c 100644 --- a/ts/features/services/common/store/reducers/index.ts +++ b/ts/features/services/common/store/reducers/index.ts @@ -4,14 +4,19 @@ import institutionReducer, { InstitutionState } from "../../../institution/store/reducers"; import searchReducer, { SearchState } from "../../../search/store/reducers"; +import servicesDetailsReducer, { + ServicesDetailsState +} from "../../../details/store/reducers"; export type ServicesState = { + details: ServicesDetailsState; home: ServicesHomeState; institution: InstitutionState; search: SearchState; }; const servicesReducer = combineReducers({ + details: servicesDetailsReducer, home: homeReducer, institution: institutionReducer, search: searchReducer diff --git a/ts/features/services/common/utils/index.ts b/ts/features/services/common/utils/index.ts index 58baab0efc2..754e1807d6f 100644 --- a/ts/features/services/common/utils/index.ts +++ b/ts/features/services/common/utils/index.ts @@ -1,3 +1,5 @@ +import { ImageURISource } from "react-native"; +import { ServicePublic } from "../../../../../definitions/backend/ServicePublic"; import { contentRepoUrl } from "../../../../config"; export function getLogoForInstitution( @@ -8,3 +10,22 @@ export function getLogoForInstitution( uri: `${logosRepoUrl}/${u}.png` })); } + +/** + * Returns an array of ImageURISource pointing to possible logos for the + * provided service. + * + * The returned array is suitable for being used with the MultiImage component. + * The arrays will have first the service logo, then the organization logo. + */ +export function logosForService( + service: ServicePublic, + logosRepoUrl: string = `${contentRepoUrl}/logos` +): ReadonlyArray { + return [ + `services/${service.service_id.toLowerCase()}`, + `organizations/${service.organization_fiscal_code.replace(/^0+/, "")}` + ].map(u => ({ + uri: `${logosRepoUrl}/${u}.png` + })); +} diff --git a/ts/features/services/details/components/ServiceDetailsMetadata.tsx b/ts/features/services/details/components/ServiceDetailsMetadata.tsx index 5dfa0749ad7..9ca51cbb301 100644 --- a/ts/features/services/details/components/ServiceDetailsMetadata.tsx +++ b/ts/features/services/details/components/ServiceDetailsMetadata.tsx @@ -12,7 +12,7 @@ import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { ServiceMetadata } from "../../../../../definitions/backend/ServiceMetadata"; import I18n from "../../../../i18n"; import { useIOSelector } from "../../../../store/hooks"; -import { serviceMetadataByIdSelector } from "../store/reducers/servicesById"; +import { serviceMetadataByIdSelector } from "../store/reducers"; import { handleItemOnPress } from "../../../../utils/url"; import * as analytics from "../../common/analytics"; diff --git a/ts/features/services/details/components/ServiceDetailsPreferences.tsx b/ts/features/services/details/components/ServiceDetailsPreferences.tsx index 8307202ff2d..7b4cd34ce5f 100644 --- a/ts/features/services/details/components/ServiceDetailsPreferences.tsx +++ b/ts/features/services/details/components/ServiceDetailsPreferences.tsx @@ -23,9 +23,9 @@ import { upsertServicePreference } from "../store/actions/preference"; import { isErrorServicePreferenceSelector, isLoadingServicePreferenceSelector, + serviceMetadataInfoSelector, servicePreferenceResponseSuccessSelector -} from "../store/reducers/servicePreference"; -import { serviceMetadataInfoSelector } from "../store/reducers/servicesById"; +} from "../store/reducers"; const hasChannel = ( notificationChannel: NotificationChannelEnum, diff --git a/ts/features/services/details/components/ServiceDetailsTosAndPrivacy.tsx b/ts/features/services/details/components/ServiceDetailsTosAndPrivacy.tsx index 509ce921bdf..3c92dc62fef 100644 --- a/ts/features/services/details/components/ServiceDetailsTosAndPrivacy.tsx +++ b/ts/features/services/details/components/ServiceDetailsTosAndPrivacy.tsx @@ -10,7 +10,7 @@ import { import I18n from "../../../../i18n"; import { openWebUrl } from "../../../../utils/url"; import { useIOSelector } from "../../../../store/hooks"; -import { serviceMetadataByIdSelector } from "../store/reducers/servicesById"; +import { serviceMetadataByIdSelector } from "../store/reducers"; import { ServiceId } from "../../../../../definitions/backend/ServiceId"; type TosAndPrivacyListItem = { diff --git a/ts/features/services/details/saga/__tests__/handleServiceDetails.test.ts b/ts/features/services/details/saga/__tests__/handleServiceDetails.test.ts index f06cca203e5..a57259834cf 100644 --- a/ts/features/services/details/saga/__tests__/handleServiceDetails.test.ts +++ b/ts/features/services/details/saga/__tests__/handleServiceDetails.test.ts @@ -8,8 +8,6 @@ import { ServiceName } from "../../../../../../definitions/backend/ServiceName"; import { ServicePublic } from "../../../../../../definitions/backend/ServicePublic"; import { loadServiceDetail } from "../../store/actions/details"; import { handleServiceDetails } from "../handleServiceDetails"; -import { handleOrganizationNameUpdateSaga } from "../../../../../sagas/services/handleOrganizationNameUpdateSaga"; -import { handleServiceReadabilitySaga } from "../../../../../sagas/services/handleServiceReadabilitySaga"; import { withRefreshApiCall } from "../../../../fastLogin/saga/utils"; import { BackendClient } from "../../../../../api/__mocks__/backend"; @@ -64,10 +62,6 @@ describe("handleServiceDetails", () => { .next(E.right({ status: 200, value: mockedService })) .put(loadServiceDetail.success(mockedService)) .next() - .call(handleServiceReadabilitySaga, mockedServiceId) - .next() - .call(handleOrganizationNameUpdateSaga, mockedService) - .next() .isDone(); }); }); diff --git a/ts/features/services/details/saga/handleServiceDetails.ts b/ts/features/services/details/saga/handleServiceDetails.ts index 8f08e6e357b..e87b90e389f 100644 --- a/ts/features/services/details/saga/handleServiceDetails.ts +++ b/ts/features/services/details/saga/handleServiceDetails.ts @@ -3,15 +3,11 @@ import { call, put } from "typed-redux-saga/macro"; import { ActionType } from "typesafe-actions"; import { PathTraversalSafePathParam } from "../../../../../definitions/backend/PathTraversalSafePathParam"; import { BackendClient } from "../../../../api/backend"; -import { handleOrganizationNameUpdateSaga } from "../../../../sagas/services/handleOrganizationNameUpdateSaga"; -import { handleServiceReadabilitySaga } from "../../../../sagas/services/handleServiceReadabilitySaga"; -import { loadServiceDetailNotFound } from "../../../../store/actions/services"; import { SagaCallReturnType } from "../../../../types/utils"; import { convertUnknownToError } from "../../../../utils/errors"; import { withRefreshApiCall } from "../../../fastLogin/saga/utils"; import { loadServiceDetail } from "../store/actions/details"; import { readablePrivacyReport } from "../../../../utils/reporters"; -import { ServiceId } from "../../../../../definitions/backend/ServiceId"; /** * saga to handle the loading of a service detail @@ -50,20 +46,8 @@ export function* handleServiceDetails( if (response.right.status === 200) { yield* put(loadServiceDetail.success(response.right.value)); - // If it is occurring during the first load of serivces, - // mark the service as read (it will not display the badge on the list item) - yield* call(handleServiceReadabilitySaga, action.payload); - // Update, if needed, the name of the organization that provides the service - yield* call(handleOrganizationNameUpdateSaga, response.right.value); - return; } - - if (response.right.status === 404) { - yield* put( - loadServiceDetailNotFound(action.payload as unknown as ServiceId) - ); - } // not handled error codes yield* put( loadServiceDetail.failure({ diff --git a/ts/features/services/details/saga/handleUpsertServicePreference.ts b/ts/features/services/details/saga/handleUpsertServicePreference.ts index 1119bf45081..8dad65bc68b 100644 --- a/ts/features/services/details/saga/handleUpsertServicePreference.ts +++ b/ts/features/services/details/saga/handleUpsertServicePreference.ts @@ -14,10 +14,9 @@ import { withRefreshApiCall } from "../../../fastLogin/saga/utils"; import { trackPNPushSettings } from "../../../pn/analytics"; import { upsertServicePreference } from "../store/actions/preference"; import { - ServicePreferenceState, - servicePreferenceSelector -} from "../store/reducers/servicePreference"; -import { serviceMetadataInfoSelector } from "../store/reducers/servicesById"; + serviceMetadataInfoSelector, + servicePreferencePotSelector +} from "../store/reducers"; import { isServicePreferenceResponseSuccess } from "../types/ServicePreferenceResponse"; import { mapKinds } from "./handleGetServicePreference"; @@ -29,7 +28,9 @@ import { mapKinds } from "./handleGetServicePreference"; * @param action */ const calculateUpdatingPreference = ( - currentServicePreferenceState: ServicePreferenceState, + currentServicePreferenceState: ReturnType< + typeof servicePreferencePotSelector + >, action: ActionType ): ServicePreference => { if ( @@ -96,11 +97,10 @@ export function* handleUpsertServicePreference( ) { yield* call(trackPNPushNotificationSettings, action); - const currentPreferences: ReturnType = - yield* select(servicePreferenceSelector); + const servicePreferencePot = yield* select(servicePreferencePotSelector); const updatingPreference = calculateUpdatingPreference( - currentPreferences, + servicePreferencePot, action ); diff --git a/ts/features/services/details/screens/ServiceDetailsScreen.tsx b/ts/features/services/details/screens/ServiceDetailsScreen.tsx index b28d23c15e8..02d409ef961 100644 --- a/ts/features/services/details/screens/ServiceDetailsScreen.tsx +++ b/ts/features/services/details/screens/ServiceDetailsScreen.tsx @@ -8,7 +8,7 @@ import { ServiceId } from "../../../../../definitions/backend/ServiceId"; import { IOStackNavigationRouteProps } from "../../../../navigation/params/AppParamsList"; import { useIODispatch, useIOSelector } from "../../../../store/hooks"; import { useOnFirstRender } from "../../../../utils/hooks/useOnFirstRender"; -import { logosForService } from "../../../../utils/services"; +import { logosForService } from "../../common/utils"; import { CTA, CTAS } from "../../../messages/types/MessageCTA"; import { getServiceCTA, @@ -39,7 +39,7 @@ import { serviceByIdSelector, serviceMetadataByIdSelector, serviceMetadataInfoSelector -} from "../store/reducers/servicesById"; +} from "../store/reducers"; import { ServiceMetadataInfo } from "../types/ServiceMetadataInfo"; export type ServiceDetailsScreenRouteParams = { diff --git a/ts/features/services/details/store/reducers/__tests__/servicePreference.test.ts b/ts/features/services/details/store/reducers/__tests__/servicePreference.test.ts index b7bef3bc180..c8ca87f5fc3 100644 --- a/ts/features/services/details/store/reducers/__tests__/servicePreference.test.ts +++ b/ts/features/services/details/store/reducers/__tests__/servicePreference.test.ts @@ -17,7 +17,7 @@ import { isErrorServicePreferenceSelector, isLoadingServicePreferenceSelector, servicePreferenceResponseSuccessSelector -} from "../servicePreference"; +} from ".."; import { GlobalState } from "../../../../../../store/reducers/types"; const serviceId = "serviceId" as ServiceId; @@ -57,7 +57,9 @@ describe("servicePreference reducer", () => { it("should have initial state", () => { const state = appReducer(undefined, applicationChangeState("active")); - expect(state.entities.services.servicePreference).toStrictEqual(pot.none); + expect(state.features.services.details.servicePreference).toStrictEqual( + pot.none + ); }); it("should handle loadServicePreference action", () => { @@ -66,19 +68,21 @@ describe("servicePreference reducer", () => { store.dispatch(loadServicePreference.request(serviceId)); - expect(store.getState().entities.services.servicePreference).toStrictEqual( - pot.noneLoading - ); + expect( + store.getState().features.services.details.servicePreference + ).toStrictEqual(pot.noneLoading); store.dispatch( loadServicePreference.success(servicePreferenceResponseSuccess) ); - expect(store.getState().entities.services.servicePreference).toStrictEqual( - pot.some(servicePreferenceResponseSuccess) - ); + expect( + store.getState().features.services.details.servicePreference + ).toStrictEqual(pot.some(servicePreferenceResponseSuccess)); store.dispatch(loadServicePreference.failure(servicePreferenceError)); - expect(store.getState().entities.services.servicePreference).toStrictEqual( + expect( + store.getState().features.services.details.servicePreference + ).toStrictEqual( pot.someError(servicePreferenceResponseSuccess, servicePreferenceError) ); }); @@ -87,11 +91,14 @@ describe("servicePreference reducer", () => { const state = appReducer(undefined, applicationChangeState("active")); const finalState: GlobalState = { ...state, - entities: { - ...state.entities, + features: { + ...state.features, services: { - ...state.entities.services, - servicePreference: pot.some(servicePreferenceResponseSuccess) + ...state.features.services, + details: { + ...state.features.services.details, + servicePreference: pot.some(servicePreferenceResponseSuccess) + } } } }; @@ -99,7 +106,9 @@ describe("servicePreference reducer", () => { store.dispatch(upsertServicePreference.request(updatingResponse)); - expect(store.getState().entities.services.servicePreference).toStrictEqual( + expect( + store.getState().features.services.details.servicePreference + ).toStrictEqual( pot.someUpdating(servicePreferenceResponseSuccess, { id: serviceId, kind: "success", @@ -114,7 +123,9 @@ describe("servicePreference reducer", () => { ); store.dispatch(upsertServicePreference.failure(servicePreferenceError)); - expect(store.getState().entities.services.servicePreference).toStrictEqual( + expect( + store.getState().features.services.details.servicePreference + ).toStrictEqual( pot.someError(servicePreferenceResponseSuccess, servicePreferenceError) ); }); diff --git a/ts/features/services/details/store/reducers/__tests__/servicesById.test.ts b/ts/features/services/details/store/reducers/__tests__/servicesById.test.ts index 77ad98d322f..435898c2efd 100644 --- a/ts/features/services/details/store/reducers/__tests__/servicesById.test.ts +++ b/ts/features/services/details/store/reducers/__tests__/servicesById.test.ts @@ -3,7 +3,6 @@ import { NonEmptyString, OrganizationFiscalCode } from "@pagopa/ts-commons/lib/strings"; -import { Tuple2 } from "@pagopa/ts-commons/lib/tuples"; import { Action, createStore } from "redux"; import { ServiceId } from "../../../../../../../definitions/backend/ServiceId"; import { ServicePublic } from "../../../../../../../definitions/backend/ServicePublic"; @@ -16,7 +15,6 @@ import { sessionExpired } from "../../../../../../store/actions/authentication"; import { loadServiceDetail } from "../../actions/details"; -import { removeServiceTuples } from "../../../../../../store/actions/services"; import { appReducer } from "../../../../../../store/reducers"; import { GlobalState } from "../../../../../../store/reducers/types"; import { reproduceSequence } from "../../../../../../utils/tests"; @@ -26,7 +24,7 @@ import { serviceByIdSelector, serviceMetadataByIdSelector, serviceMetadataInfoSelector -} from "../servicesById"; +} from ".."; const serviceId = "serviceId" as ServiceId; @@ -42,7 +40,7 @@ describe("serviceById reducer", () => { it("should have initial state", () => { const state = appReducer(undefined, applicationChangeState("active")); - expect(state.entities.services.byId).toStrictEqual({}); + expect(state.features.services.details.byId).toStrictEqual({}); }); it("should handle loadServiceDetail action", () => { @@ -51,12 +49,12 @@ describe("serviceById reducer", () => { store.dispatch(loadServiceDetail.request(serviceId)); - expect(store.getState().entities.services.byId).toStrictEqual({ + expect(store.getState().features.services.details.byId).toStrictEqual({ serviceId: pot.noneLoading }); store.dispatch(loadServiceDetail.success(service)); - expect(store.getState().entities.services.byId).toStrictEqual({ + expect(store.getState().features.services.details.byId).toStrictEqual({ serviceId: pot.some(service) }); @@ -66,7 +64,7 @@ describe("serviceById reducer", () => { }; store.dispatch(loadServiceDetail.failure(tError)); - expect(store.getState().entities.services.byId).toStrictEqual({ + expect(store.getState().features.services.details.byId).toStrictEqual({ serviceId: pot.someError(service, new Error("load failed")) }); }); @@ -83,7 +81,7 @@ describe("serviceById reducer", () => { appReducer, sequenceOfActions ); - expect(state.entities.services.byId).toEqual({}); + expect(state.features.services.details.byId).toEqual({}); }); it("should handle sessionExpired action", () => { @@ -98,36 +96,7 @@ describe("serviceById reducer", () => { appReducer, sequenceOfActions ); - expect(state.entities.services.byId).toEqual({}); - }); - - it("should handle removeServiceTuples action", () => { - const sequenceOfActions: ReadonlyArray = [ - applicationChangeState("active"), - loadServiceDetail.success({ ...service, service_id: "s1" as ServiceId }), - loadServiceDetail.success({ ...service, service_id: "s2" as ServiceId }), - loadServiceDetail.success({ ...service, service_id: "s3" as ServiceId }), - loadServiceDetail.success({ ...service, service_id: "s4" as ServiceId }), - loadServiceDetail.success({ ...service, service_id: "s5" as ServiceId }), - removeServiceTuples([ - Tuple2("s2", "FSCLCD"), - Tuple2("s3", "FSCLCD"), - // Not existing serviceId - Tuple2("s6", "FSCLCD") - ]) - ]; - - const state: GlobalState = reproduceSequence( - {} as GlobalState, - appReducer, - sequenceOfActions - ); - - expect(state.entities.services.byId).toEqual({ - s1: pot.some({ ...service, service_id: "s1" as ServiceId }), - s4: pot.some({ ...service, service_id: "s4" as ServiceId }), - s5: pot.some({ ...service, service_id: "s5" as ServiceId }) - }); + expect(state.features.services.details.byId).toEqual({}); }); }); diff --git a/ts/features/services/details/store/reducers/index.ts b/ts/features/services/details/store/reducers/index.ts new file mode 100644 index 00000000000..74ab3df014c --- /dev/null +++ b/ts/features/services/details/store/reducers/index.ts @@ -0,0 +1,216 @@ +import * as pot from "@pagopa/ts-commons/lib/pot"; +import * as O from "fp-ts/lib/Option"; +import { pipe } from "fp-ts/lib/function"; +import { createSelector } from "reselect"; +import { getType } from "typesafe-actions"; +import { ServiceId } from "../../../../../../definitions/backend/ServiceId"; +import { ServiceMetadata } from "../../../../../../definitions/backend/ServiceMetadata"; +import { ServicePublic } from "../../../../../../definitions/backend/ServicePublic"; +import { SpecialServiceMetadata } from "../../../../../../definitions/backend/SpecialServiceMetadata"; +import { + logoutSuccess, + sessionExpired +} from "../../../../../store/actions/authentication"; +import { Action } from "../../../../../store/actions/types"; +import { GlobalState } from "../../../../../store/reducers/types"; +import { NetworkError } from "../../../../../utils/errors"; +import { isStrictSome } from "../../../../../utils/pot"; +import { ServiceMetadataInfo } from "../../types/ServiceMetadataInfo"; +import { + ServicePreferenceResponse, + WithServiceID, + isServicePreferenceResponseSuccess +} from "../../types/ServicePreferenceResponse"; +import { loadServiceDetail } from "../actions/details"; +import { + loadServicePreference, + upsertServicePreference +} from "../actions/preference"; + +export type ServicesDetailsState = { + byId: Record>; + servicePreference: pot.Pot< + ServicePreferenceResponse, + WithServiceID + >; +}; + +const INITIAL_STATE: ServicesDetailsState = { + byId: {}, + servicePreference: pot.none +}; + +const servicesDetailsReducer = ( + state: ServicesDetailsState = INITIAL_STATE, + action: Action +): ServicesDetailsState => { + switch (action.type) { + // Get service details actions + case getType(loadServiceDetail.request): + // When a previously loaded service detail is loaded again, its state + // is updated with a someLoading pot, otherwise its state is updated with a noneLoading pot + return { + ...state, + byId: { + ...state.byId, + [action.payload]: pipe( + state.byId[action.payload], + O.fromNullable, + O.fold(() => pot.noneLoading, pot.toLoading) + ) + } + }; + + case getType(loadServiceDetail.success): + // Use the ID as object key + return { + ...state, + byId: { + ...state.byId, + [action.payload.service_id]: pot.some(action.payload) + } + }; + + case getType(loadServiceDetail.failure): + // when a request to load a previously loaded service detail fails its state is updated + // with a someError pot, otherwise its state is updated with a noneError pot + return { + ...state, + byId: { + ...state.byId, + [action.payload.service_id]: pipe( + state.byId[action.payload.service_id], + O.fromNullable, + O.fold( + () => pot.noneError(action.payload.error), + servicePot => pot.toError(servicePot, action.payload.error) + ) + ) + } + }; + + // Get service preference actions + case getType(loadServicePreference.request): + return { + ...state, + servicePreference: pot.toLoading(state.servicePreference) + }; + case getType(upsertServicePreference.request): + const { id, ...payload } = action.payload; + + return { + ...state, + servicePreference: pot.toUpdating(state.servicePreference, { + id, + kind: "success", + value: payload + }) + }; + case getType(loadServicePreference.success): + case getType(upsertServicePreference.success): + return { + ...state, + servicePreference: pot.some(action.payload) + }; + case getType(loadServicePreference.failure): + case getType(upsertServicePreference.failure): + return { + ...state, + servicePreference: pot.toError(state.servicePreference, action.payload) + }; + + case getType(logoutSuccess): + case getType(sessionExpired): + return INITIAL_STATE; + } + return state; +}; + +export default servicesDetailsReducer; + +// Selectors +export const servicesByIdSelector = (state: GlobalState) => + state.features.services.details.byId; + +export const serviceByIdPotSelector = ( + state: GlobalState, + id: ServiceId +): pot.Pot => + state.features.services.details.byId[id] ?? pot.none; + +export const serviceByIdSelector = ( + state: GlobalState, + id: ServiceId +): ServicePublic | undefined => + pipe(serviceByIdPotSelector(state, id), pot.toUndefined); + +export const isLoadingServiceByIdSelector = ( + state: GlobalState, + id: ServiceId +) => pipe(serviceByIdPotSelector(state, id), pot.isLoading); + +export const isErrorServiceByIdSelector = (state: GlobalState, id: ServiceId) => + pipe(serviceByIdPotSelector(state, id), pot.isError); + +export const serviceMetadataByIdSelector = createSelector( + serviceByIdPotSelector, + serviceByIdPot => + pipe( + serviceByIdPot, + pot.toOption, + O.chainNullableK(service => service.service_metadata), + O.toUndefined + ) +); + +export const serviceMetadataInfoSelector = createSelector( + serviceMetadataByIdSelector, + serviceMetadata => + pipe( + serviceMetadata, + O.fromNullable, + O.chain(serviceMetadata => { + if (SpecialServiceMetadata.is(serviceMetadata)) { + return O.some({ + isSpecialService: true, + customSpecialFlow: serviceMetadata.custom_special_flow as string + }); + } + return O.none; + }), + O.getOrElse(() => ({ isSpecialService: false })) + ) +); + +export const servicePreferencePotSelector = (state: GlobalState) => + state.features.services.details.servicePreference; + +export const servicePreferenceResponseSuccessSelector = createSelector( + servicePreferencePotSelector, + servicePreferencePot => + pipe( + servicePreferencePot, + pot.toOption, + O.filter(isServicePreferenceResponseSuccess), + O.toUndefined + ) +); + +export const isLoadingServicePreferenceSelector = (state: GlobalState) => + pipe( + state, + servicePreferencePotSelector, + servicePreferencePot => + pot.isLoading(servicePreferencePot) || + pot.isUpdating(servicePreferencePot) + ); + +export const isErrorServicePreferenceSelector = (state: GlobalState) => + pipe( + state, + servicePreferencePotSelector, + servicePreferencePot => + pot.isError(servicePreferencePot) || + (isStrictSome(servicePreferencePot) && + !isServicePreferenceResponseSuccess(servicePreferencePot.value)) + ); diff --git a/ts/features/services/details/store/reducers/servicePreference.ts b/ts/features/services/details/store/reducers/servicePreference.ts deleted file mode 100644 index 7705976eeef..00000000000 --- a/ts/features/services/details/store/reducers/servicePreference.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { createSelector } from "reselect"; -import * as pot from "@pagopa/ts-commons/lib/pot"; -import * as O from "fp-ts/lib/Option"; -import { pipe } from "fp-ts/lib/function"; -import { getType } from "typesafe-actions"; -import { - ServicePreferenceResponse, - WithServiceID, - isServicePreferenceResponseSuccess -} from "../../types/ServicePreferenceResponse"; -import { NetworkError } from "../../../../../utils/errors"; -import { isStrictSome } from "../../../../../utils/pot"; -import { - loadServicePreference, - upsertServicePreference -} from "../actions/preference"; -import { Action } from "../../../../../store/actions/types"; -import { GlobalState } from "../../../../../store/reducers/types"; - -export type ServicePreferenceState = pot.Pot< - ServicePreferenceResponse, - WithServiceID ->; - -const INITIAL_STATE: ServicePreferenceState = pot.none; - -/** - * Reducer to handle specific service contact preferences (inbox, push, emails) - */ -const servicePreferenceReducer = ( - state: ServicePreferenceState = INITIAL_STATE, - action: Action -): ServicePreferenceState => { - switch (action.type) { - case getType(loadServicePreference.request): - return pot.toLoading(state); - case getType(upsertServicePreference.request): - const { id, ...payload } = action.payload; - - return pot.toUpdating(state, { - id, - kind: "success", - value: payload - }); - case getType(loadServicePreference.success): - case getType(upsertServicePreference.success): - return pot.some(action.payload); - case getType(loadServicePreference.failure): - case getType(upsertServicePreference.failure): - return pot.toError(state, action.payload); - } - return state; -}; - -export default servicePreferenceReducer; - -// Selectors -export const servicePreferenceSelector = ( - state: GlobalState -): ServicePreferenceState => state.entities.services.servicePreference; - -export const servicePreferenceResponseSuccessSelector = createSelector( - servicePreferenceSelector, - servicePreferencePot => - pipe( - servicePreferencePot, - pot.toOption, - O.filter(isServicePreferenceResponseSuccess), - O.toUndefined - ) -); - -export const isLoadingServicePreferenceSelector = (state: GlobalState) => - pipe( - state, - servicePreferenceSelector, - servicePreferencePot => - pot.isLoading(servicePreferencePot) || - pot.isUpdating(servicePreferencePot) - ); - -export const isErrorServicePreferenceSelector = (state: GlobalState) => - pipe( - state, - servicePreferenceSelector, - servicePreferencePot => - pot.isError(servicePreferencePot) || - (isStrictSome(servicePreferencePot) && - !isServicePreferenceResponseSuccess(servicePreferencePot.value)) - ); diff --git a/ts/features/services/details/store/reducers/servicesById.ts b/ts/features/services/details/store/reducers/servicesById.ts deleted file mode 100644 index d9a7652d42a..00000000000 --- a/ts/features/services/details/store/reducers/servicesById.ts +++ /dev/null @@ -1,139 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import * as O from "fp-ts/lib/Option"; -import { pipe } from "fp-ts/lib/function"; -import { createSelector } from "reselect"; -import { getType } from "typesafe-actions"; -import { ServiceId } from "../../../../../../definitions/backend/ServiceId"; -import { ServiceMetadata } from "../../../../../../definitions/backend/ServiceMetadata"; -import { ServicePublic } from "../../../../../../definitions/backend/ServicePublic"; -import { SpecialServiceMetadata } from "../../../../../../definitions/backend/SpecialServiceMetadata"; -import { - logoutSuccess, - sessionExpired -} from "../../../../../store/actions/authentication"; -import { removeServiceTuples } from "../../../../../store/actions/services"; -import { Action } from "../../../../../store/actions/types"; -import { GlobalState } from "../../../../../store/reducers/types"; -import { ServiceMetadataInfo } from "../../types/ServiceMetadataInfo"; -import { loadServiceDetail } from "../actions/details"; - -export type ServicesByIdState = Readonly<{ - [key: string]: pot.Pot | undefined; -}>; - -const INITIAL_STATE: ServicesByIdState = {}; - -/** - * A reducer to store the services detail normalized by id - */ -const serviceByIdReducer = ( - state: ServicesByIdState = INITIAL_STATE, - action: Action -): ServicesByIdState => { - switch (action.type) { - case getType(loadServiceDetail.request): - // When a previously loaded service detail is loaded again, its state - // is updated with a someLoading pot, otherwise its state is updated with a noneLoading pot - return { - ...state, - [action.payload]: pipe( - state[action.payload], - O.fromNullable, - O.fold(() => pot.noneLoading, pot.toLoading) - ) - }; - - case getType(loadServiceDetail.success): - // Use the ID as object key - return { - ...state, - [action.payload.service_id]: pot.some(action.payload) - }; - - case getType(loadServiceDetail.failure): - // when a request to load a previously loaded service detail fails its state is updated - // with a someError pot, otherwise its state is updated with a noneError pot - return { - ...state, - [action.payload.service_id]: pipe( - state[action.payload.service_id], - O.fromNullable, - O.fold( - () => pot.noneError(action.payload.error), - servicePot => pot.toError(servicePot, action.payload.error) - ) - ) - }; - - case getType(removeServiceTuples): { - const serviceTuples = action.payload; - const newState = { ...state }; - // eslint-disable-next-line - serviceTuples.forEach(_ => delete newState[_.e1]); - return newState; - } - - case getType(logoutSuccess): - case getType(sessionExpired): - return INITIAL_STATE; - - default: - return state; - } -}; - -export default serviceByIdReducer; - -// Selectors -export const servicesByIdSelector = (state: GlobalState): ServicesByIdState => - state.entities.services.byId; - -export const serviceByIdPotSelector = ( - state: GlobalState, - id: ServiceId -): pot.Pot => - state.entities.services.byId[id] ?? pot.none; - -export const serviceByIdSelector = ( - state: GlobalState, - id: ServiceId -): ServicePublic | undefined => - pipe(serviceByIdPotSelector(state, id), pot.toUndefined); - -export const isLoadingServiceByIdSelector = ( - state: GlobalState, - id: ServiceId -) => pipe(serviceByIdPotSelector(state, id), pot.isLoading); - -export const isErrorServiceByIdSelector = (state: GlobalState, id: ServiceId) => - pipe(serviceByIdPotSelector(state, id), pot.isError); - -export const serviceMetadataByIdSelector = createSelector( - serviceByIdPotSelector, - serviceByIdPot => - pipe( - serviceByIdPot, - pot.toOption, - O.chainNullableK(service => service.service_metadata), - O.toUndefined - ) -); - -export const serviceMetadataInfoSelector = createSelector( - serviceMetadataByIdSelector, - serviceMetadata => - pipe( - serviceMetadata, - O.fromNullable, - O.chain(serviceMetadata => { - if (SpecialServiceMetadata.is(serviceMetadata)) { - return O.some({ - isSpecialService: true, - customSpecialFlow: serviceMetadata.custom_special_flow as string - }); - } - return O.none; - }), - O.getOrElse(() => ({ isSpecialService: false })) - ) -); diff --git a/ts/features/wallet/component/card/FeaturedCardCarousel.tsx b/ts/features/wallet/component/card/FeaturedCardCarousel.tsx index 571af6fc4f1..cd6d77f5604 100644 --- a/ts/features/wallet/component/card/FeaturedCardCarousel.tsx +++ b/ts/features/wallet/component/card/FeaturedCardCarousel.tsx @@ -17,7 +17,6 @@ import { IOStackNavigationProp } from "../../../../navigation/params/AppParamsList"; import { loadServiceDetail } from "../../../services/details/store/actions/details"; -import { showServiceDetails } from "../../../../store/actions/services"; import { Dispatch } from "../../../../store/actions/types"; import { useIODispatch, useIOSelector } from "../../../../store/hooks"; import { @@ -100,13 +99,11 @@ const FeaturedCardCarousel: React.FunctionComponent = (props: Props) => { // TODO: add mixpanel tracking and alert: https://pagopa.atlassian.net/browse/AP-14 IOToast.info(I18n.t("bonus.cdc.serviceEntryPoint.notAvailable")); }, - s => () => { - dispatch(showServiceDetails(s)); + s => () => navigation.navigate(SERVICES_ROUTES.SERVICES_NAVIGATOR, { screen: SERVICES_ROUTES.SERVICE_DETAIL, params: { serviceId: s.service_id } - }); - } + }) ) ); } diff --git a/ts/navigation/ServicesHomeTabNavigator.tsx b/ts/navigation/ServicesHomeTabNavigator.tsx deleted file mode 100644 index c1f7d46fb8d..00000000000 --- a/ts/navigation/ServicesHomeTabNavigator.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs"; -import I18n from "i18n-js"; -import * as React from "react"; -import { Platform } from "react-native"; -import { IOColors } from "@pagopa/io-app-design-system"; -import { makeFontStyleObject } from "../components/core/fonts"; -import ServicesLocalScreen from "../screens/services/ServicesLocalScreen"; -import ServicesNationalScreen from "../screens/services/ServicesNationalScreen"; - -const Tab = createMaterialTopTabNavigator(); - -const ServicesHomeTabNavigator = () => ( - - - - -); - -export default ServicesHomeTabNavigator; diff --git a/ts/navigation/TabNavigator.tsx b/ts/navigation/TabNavigator.tsx index 34923c8aa0c..eaab740bcf6 100644 --- a/ts/navigation/TabNavigator.tsx +++ b/ts/navigation/TabNavigator.tsx @@ -194,8 +194,6 @@ export const MainTabNavigator = () => { iconNameFocused="navServicesFocused" color={color} focused={focused} - // Badge counter has been disabled - // https://www.pivotaltracker.com/story/show/176919053 /> ) }} diff --git a/ts/sagas/services/__tests__/handleFirstVisibleServiceLoadSaga.test.ts b/ts/sagas/services/__tests__/handleFirstVisibleServiceLoadSaga.test.ts deleted file mode 100644 index 52750d0da89..00000000000 --- a/ts/sagas/services/__tests__/handleFirstVisibleServiceLoadSaga.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { testSaga } from "redux-saga-test-plan"; -import { firstServiceLoadSuccess } from "../../../store/actions/services"; -import { visibleServicesDetailLoadStateSelector } from "../../../store/reducers/entities/services"; -import { isFirstVisibleServiceLoadCompletedSelector } from "../../../store/reducers/entities/services/firstServicesLoading"; -import { handleFirstVisibleServiceLoadSaga } from "../handleFirstVisibleServiceLoadSaga"; - -describe("handleFirstVisibleServiceLoadSaga", () => { - it("does nothing if the visible services loading is not completed", () => { - testSaga(handleFirstVisibleServiceLoadSaga) - .next() - .select(isFirstVisibleServiceLoadCompletedSelector) - .next(false) - .select(visibleServicesDetailLoadStateSelector) - .next(pot.noneLoading) - .isDone(); - }); - - it("saves on the redux store that the first service loading is completed if all the visible services have been loaded successfully", () => { - testSaga(handleFirstVisibleServiceLoadSaga) - .next() - .select(isFirstVisibleServiceLoadCompletedSelector) - .next(false) - .select(visibleServicesDetailLoadStateSelector) - .next(pot.some(undefined)) - .put(firstServiceLoadSuccess()) - .next() - .isDone(); - }); - - it("does nothing if the visible services are not loaded (error)", () => { - testSaga(handleFirstVisibleServiceLoadSaga) - .next() - .select(isFirstVisibleServiceLoadCompletedSelector) - .next(false) - .select(visibleServicesDetailLoadStateSelector) - .next(pot.noneError) - .isDone(); - }); -}); diff --git a/ts/sagas/services/__tests__/handleOrganizationNameUpdateSaga.test.ts b/ts/sagas/services/__tests__/handleOrganizationNameUpdateSaga.test.ts deleted file mode 100644 index 8cc887097e3..00000000000 --- a/ts/sagas/services/__tests__/handleOrganizationNameUpdateSaga.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { NonEmptyString } from "@pagopa/ts-commons/lib/strings"; -import { testSaga } from "redux-saga-test-plan"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { updateOrganizations } from "../../../store/actions/organizations"; -import { - organizationNamesByFiscalCodeSelector, - OrganizationNamesByFiscalCodeState -} from "../../../store/reducers/entities/organizations/organizationsByFiscalCodeReducer"; -import { visibleServicesSelector } from "../../../store/reducers/entities/services/visibleServices"; -import { mockedService } from "../../../features/services/details/saga/__tests__/handleServiceDetails.test"; -import { handleOrganizationNameUpdateSaga } from "../handleOrganizationNameUpdateSaga"; - -const mockedOrganizationsNameByFiscalCode: OrganizationNamesByFiscalCodeState = - { - ["01"]: "ente1" as NonEmptyString, - ["02"]: "ente2" as NonEmptyString, - ["03"]: "ente3" as NonEmptyString - }; - -const mockedOrganizationsNameByFiscalCodeUpdated: OrganizationNamesByFiscalCodeState = - { - ["01"]: "ente1 - nuovo nome" as NonEmptyString, - ["02"]: "ente2" as NonEmptyString, - ["03"]: "ente3" as NonEmptyString - }; - -const mockedVisibleServices = pot.some([ - { service_id: "A01" as ServiceId, version: 1 }, - { service_id: "A02" as ServiceId, version: 5 }, - { service_id: "A03" as ServiceId, version: 2 } -]); - -describe("handleOrganizationNameUpdateSaga", () => { - it("does nothing if the organizationNamesByFiscalCodeSelector return undefined", () => { - testSaga(handleOrganizationNameUpdateSaga, mockedService) - .next() - .select(organizationNamesByFiscalCodeSelector) - .next(undefined) - .isDone(); - }); - - it("does nothing after service detail load if the related organization name exist in the organizations redux store", () => { - testSaga(handleOrganizationNameUpdateSaga, mockedService) - .next() - .select(organizationNamesByFiscalCodeSelector) - .next(mockedOrganizationsNameByFiscalCodeUpdated) - .select(visibleServicesSelector) - .next(mockedVisibleServices) - .isDone(); - }); - - it("add the organization name of the loaded service detail if the related fiscal code does NOT exist in the organizations redux state", () => { - testSaga(handleOrganizationNameUpdateSaga, mockedService) - .next() - .select(organizationNamesByFiscalCodeSelector) - .next({}) - .put(updateOrganizations(mockedService)) - .next() - .isDone(); - }); - - it("add the organization name of the loaded service detail if the related fiscal code exists in the organizations redux state related to a different name", () => { - testSaga(handleOrganizationNameUpdateSaga, mockedService) - .next() - .select(organizationNamesByFiscalCodeSelector) - .next(mockedOrganizationsNameByFiscalCode) - .select(visibleServicesSelector) - .next(mockedVisibleServices) - .put(updateOrganizations(mockedService)) - .next() - .isDone(); - }); -}); diff --git a/ts/sagas/services/__tests__/handleServiceReadabilitySaga.test.ts b/ts/sagas/services/__tests__/handleServiceReadabilitySaga.test.ts deleted file mode 100644 index 02cbec94577..00000000000 --- a/ts/sagas/services/__tests__/handleServiceReadabilitySaga.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { testSaga } from "redux-saga-test-plan"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { markServiceAsRead } from "../../../store/actions/services"; -import { isFirstVisibleServiceLoadCompletedSelector } from "../../../store/reducers/entities/services/firstServicesLoading"; -import { handleServiceReadabilitySaga } from "../handleServiceReadabilitySaga"; - -describe("handleServiceReadabilitySaga", () => { - const mockedServiceId = "0123" as ServiceId; - - it("makes the service with the given id being marked as read if the first service loading is not complete", () => { - testSaga(handleServiceReadabilitySaga, mockedServiceId) - .next() - .select(isFirstVisibleServiceLoadCompletedSelector) - .next(false) - .put(markServiceAsRead(mockedServiceId)) - .next() - .isDone(); - }); - - it("do nothing if the first service loading has been completed ", () => { - testSaga(handleServiceReadabilitySaga, mockedServiceId) - .next() - .select(isFirstVisibleServiceLoadCompletedSelector) - .next(true) - .isDone(); - }); -}); diff --git a/ts/sagas/services/__tests__/refreshStoredServices.test.ts b/ts/sagas/services/__tests__/refreshStoredServices.test.ts deleted file mode 100644 index 806898fb85d..00000000000 --- a/ts/sagas/services/__tests__/refreshStoredServices.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { OrganizationFiscalCode } from "@pagopa/ts-commons/lib/strings"; -import { testSaga } from "redux-saga-test-plan"; -import { DepartmentName } from "../../../../definitions/backend/DepartmentName"; -import { OrganizationName } from "../../../../definitions/backend/OrganizationName"; -import { PaginatedServiceTupleCollection } from "../../../../definitions/backend/PaginatedServiceTupleCollection"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { ServiceName } from "../../../../definitions/backend/ServiceName"; -import { ServicePublic } from "../../../../definitions/backend/ServicePublic"; -import { loadServicesDetail } from "../../../store/actions/services"; -import { - servicesByIdSelector, - ServicesByIdState -} from "../../../features/services/details/store/reducers/servicesById"; -import { refreshStoredServices } from "../refreshStoredServices"; - -describe("refreshStoredServices", () => { - const mockedService: ServicePublic = { - service_id: "S01" as ServiceId, - service_name: "servizio1" as ServiceName, - organization_name: "ente1" as OrganizationName, - department_name: "dipartimento1" as DepartmentName, - organization_fiscal_code: "01" as OrganizationFiscalCode, - version: 1 - }; - - it("loads again the services if it is visible and an old version is stored", () => { - const mockedNewVisibleServices: PaginatedServiceTupleCollection["items"] = [ - { service_id: mockedService.service_id, version: 2 } - ]; - const mockedServicesById: ServicesByIdState = { - [mockedService.service_id]: pot.some(mockedService) - }; - - testSaga(refreshStoredServices, mockedNewVisibleServices) - .next() - .select(servicesByIdSelector) - .next(mockedServicesById) - .put(loadServicesDetail([mockedService.service_id])) - .next() - .isDone(); - }); - - it("loads the services if it is visible and not yet stored", () => { - const mockedNewVisibleServices: PaginatedServiceTupleCollection["items"] = [ - { service_id: mockedService.service_id, version: 1 } - ]; - - testSaga(refreshStoredServices, mockedNewVisibleServices) - .next() - .select(servicesByIdSelector) - .next({}) - .put(loadServicesDetail([mockedService.service_id])) - .next() - .isDone(); - }); - - it("does nothing if all the latest versions of visible services are stored", () => { - const mockedVisibleServices: PaginatedServiceTupleCollection["items"] = [ - { service_id: mockedService.service_id, version: mockedService.version } - ]; - const mockedServicesById: ServicesByIdState = { - [mockedService.service_id]: pot.some(mockedService) - }; - - testSaga(refreshStoredServices, mockedVisibleServices) - .next() - .select(servicesByIdSelector) - .next(mockedServicesById) - .next() - .isDone(); - }); -}); diff --git a/ts/sagas/services/handleFirstVisibleServiceLoadSaga.ts b/ts/sagas/services/handleFirstVisibleServiceLoadSaga.ts deleted file mode 100644 index 14fc7a0a287..00000000000 --- a/ts/sagas/services/handleFirstVisibleServiceLoadSaga.ts +++ /dev/null @@ -1,24 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { SagaIterator } from "redux-saga"; -import { put, select } from "typed-redux-saga/macro"; -import { firstServiceLoadSuccess } from "../../store/actions/services"; -import { visibleServicesDetailLoadStateSelector } from "../../store/reducers/entities/services"; -import { isFirstVisibleServiceLoadCompletedSelector } from "../../store/reducers/entities/services/firstServicesLoading"; - -/** - * A function to check if all services detail and scopes are loaded with success. - * If it is true, by dispatching firstServiceLoadSuccess the app stop considering loaded services as read - */ -export function* handleFirstVisibleServiceLoadSaga(): SagaIterator { - const isFirstVisibleServiceLoadCompleted: ReturnType< - typeof isFirstVisibleServiceLoadCompletedSelector - > = yield* select(isFirstVisibleServiceLoadCompletedSelector); - if (!isFirstVisibleServiceLoadCompleted) { - const visibleServicesDetailsLoadState: ReturnType< - typeof visibleServicesDetailLoadStateSelector - > = yield* select(visibleServicesDetailLoadStateSelector); - if (pot.isSome(visibleServicesDetailsLoadState)) { - yield* put(firstServiceLoadSuccess()); - } - } -} diff --git a/ts/sagas/services/handleOrganizationNameUpdateSaga.ts b/ts/sagas/services/handleOrganizationNameUpdateSaga.ts deleted file mode 100644 index 76f056f9d79..00000000000 --- a/ts/sagas/services/handleOrganizationNameUpdateSaga.ts +++ /dev/null @@ -1,52 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { SagaIterator } from "redux-saga"; -import { put, select } from "typed-redux-saga/macro"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import { updateOrganizations } from "../../store/actions/organizations"; -import { - organizationNamesByFiscalCodeSelector, - OrganizationNamesByFiscalCodeState -} from "../../store/reducers/entities/organizations/organizationsByFiscalCodeReducer"; -import { - visibleServicesSelector, - VisibleServicesState -} from "../../store/reducers/entities/services/visibleServices"; -import { isVisibleService } from "../../utils/services"; - -/** - * A function to check if the organization_name included in the service detail is different - * from the stored organization name (for the same organization_fiscal_code). - * If true, the incoming one is saved into the redux store. - * @param service - */ -export function* handleOrganizationNameUpdateSaga( - service: ServicePublic -): SagaIterator { - // If the organization fiscal code is associated to different organization names, - // it is considered valid the one declared for a visible service - const organizations: OrganizationNamesByFiscalCodeState = yield* select( - organizationNamesByFiscalCodeSelector - ); - if (organizations) { - const fc = service.organization_fiscal_code; - - // The organization is stored if the corresponding fiscal code has no maches among those stored - const organization = organizations[fc]; - if (!organization) { - yield* put(updateOrganizations(service)); - return; - } - const visibleServices: VisibleServicesState = yield* select( - visibleServicesSelector - ); - const isVisible = - isVisibleService(visibleServices, pot.some(service)) || false; - - // If the organization has been previously saved in the organization entity, - // the organization name is updated only if the related service is visible - // and the name has been updated - if (isVisible && organization !== service.organization_name) { - yield* put(updateOrganizations(service)); - } - } -} diff --git a/ts/sagas/services/handleServiceReadabilitySaga.ts b/ts/sagas/services/handleServiceReadabilitySaga.ts deleted file mode 100644 index 468dae30e6c..00000000000 --- a/ts/sagas/services/handleServiceReadabilitySaga.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { SagaIterator } from "redux-saga"; -import { put, select } from "typed-redux-saga/macro"; -import { ServiceId } from "../../../definitions/backend/ServiceId"; -import { markServiceAsRead } from "../../store/actions/services"; -import { isFirstVisibleServiceLoadCompletedSelector } from "../../store/reducers/entities/services/firstServicesLoading"; - -/** - * A function to check if a service is loaded for the first time (at first startup or when the cache - * is cleaned). If true, the app shows the service list item without badge - * @param serviceId - */ -export function* handleServiceReadabilitySaga(serviceId: string): SagaIterator { - const isFirstVisibleServiceLoadCompleted: ReturnType< - typeof isFirstVisibleServiceLoadCompletedSelector - > = yield* select(isFirstVisibleServiceLoadCompletedSelector); - - if (!isFirstVisibleServiceLoadCompleted) { - yield* put(markServiceAsRead(serviceId as ServiceId)); - } -} diff --git a/ts/sagas/services/refreshStoredServices.ts b/ts/sagas/services/refreshStoredServices.ts deleted file mode 100644 index a5363fefbe9..00000000000 --- a/ts/sagas/services/refreshStoredServices.ts +++ /dev/null @@ -1,44 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { SagaIterator } from "redux-saga"; -import { put, select } from "typed-redux-saga/macro"; -import { PaginatedServiceTupleCollection } from "../../../definitions/backend/PaginatedServiceTupleCollection"; -import { loadServicesDetail } from "../../store/actions/services"; -import { servicesByIdSelector } from "../../features/services/details/store/reducers/servicesById"; - -/** - * Check which services detail must be loaded. If there are, loading action will be dispatched - * A service detail has to be loaded if one of these conditions is true - * - it is not into the store (servicesByIdSelector) - * - the relative stored value is a pot none (but not loading) - * - the relative stored value is some and its version is less than the visible one - * @param visibleServices - */ -export function* refreshStoredServices( - visibleServices: PaginatedServiceTupleCollection["items"] -): SagaIterator { - const storedServicesById: ReturnType = - yield* select(servicesByIdSelector); - - const serviceDetailIdsToLoad = visibleServices - .filter(service => { - const serviceId = service.service_id; - const storedService = storedServicesById[serviceId]; - return ( - // The service detail: - // - is not in the redux store - storedService === undefined || - // retry to load those services that are in error state - pot.isError(storedService) || - // - is in the redux store as PotNone and not loading - pot.isNone(storedService) || - // - is in the redux store as PotSome, is not updating and is outdated - (pot.isSome(storedService) && - !pot.isUpdating(storedService) && - storedService.value.version < service.version) - ); - }) - .map(_ => _.service_id); - if (serviceDetailIdsToLoad.length > 0) { - yield* put(loadServicesDetail(serviceDetailIdsToLoad)); - } -} diff --git a/ts/sagas/services/removeUnusedStoredServices.ts b/ts/sagas/services/removeUnusedStoredServices.ts deleted file mode 100644 index bbc5d81d7a2..00000000000 --- a/ts/sagas/services/removeUnusedStoredServices.ts +++ /dev/null @@ -1,60 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { ITuple2, Tuple2 } from "@pagopa/ts-commons/lib/tuples"; -import { SagaIterator } from "redux-saga"; -import { put, select } from "typed-redux-saga/macro"; -import { PaginatedServiceTupleCollection } from "../../../definitions/backend/PaginatedServiceTupleCollection"; -import { removeServiceTuples } from "../../store/actions/services"; -import { servicesByIdSelector } from "../../features/services/details/store/reducers/servicesById"; - -type VisibleServiceVersionById = { - [index: string]: number | undefined; -}; - -export function* removeUnusedStoredServices( - visibleServices: PaginatedServiceTupleCollection["items"] -): SagaIterator { - const visibleServiceVersionById = - visibleServices.reduce( - (accumulator, currentValue) => ({ - ...accumulator, - [currentValue.service_id]: currentValue.version - }), - {} - ); - - const storedServicesById: ReturnType = - yield* select(servicesByIdSelector); - - // Create an array of tuples containing: - // - serviceId (to remove service from both the servicesById and the servicesMetadataById sections of the redux store) - // - organizationFiscalCode (to remove service from serviceIdsByOrganizationFiscalCode - // section of the redux store) - const serviceTuplesToRemove = Object.keys(storedServicesById).reduce< - ReadonlyArray> - >((accumulator, serviceId) => { - // Check if this service id must be removed - // A service must be removed if is no more visible and not used by any loaded message. - const mustRemoveServiceId = - visibleServiceVersionById[serviceId] === undefined; - - if (!mustRemoveServiceId) { - return accumulator; - } - - const storedPotService = storedServicesById[serviceId]; - - if (storedPotService !== undefined) { - // If the service detail is also loaded get the organization fiscal code - const organizationFiscalCode = pot.toUndefined( - pot.map(storedPotService, _ => _.organization_fiscal_code) - ); - - return [...accumulator, Tuple2(serviceId, organizationFiscalCode)]; - } - - return accumulator; - }, []); - - // Dispatch action to remove the services from the redux store - yield* put(removeServiceTuples(serviceTuplesToRemove)); -} diff --git a/ts/sagas/services/watchLoadServicesSaga.ts b/ts/sagas/services/watchLoadServicesSaga.ts deleted file mode 100644 index a084c99caad..00000000000 --- a/ts/sagas/services/watchLoadServicesSaga.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { SagaIterator } from "redux-saga"; -import { fork, put, takeEvery } from "typed-redux-saga/macro"; -import { getType } from "typesafe-actions"; -import { BackendClient } from "../../api/backend"; -import { loadServiceDetail } from "../../features/services/details/store/actions/details"; -import { loadVisibleServices } from "../../store/actions/services"; -import { watchServicesDetailLoadSaga } from "../startup/loadServiceDetailRequestHandler"; -import { loadVisibleServicesRequestHandler } from "../startup/loadVisibleServicesHandler"; -import { watchServicesDetailsSaga } from "../../features/services/details/saga"; -import { handleFirstVisibleServiceLoadSaga } from "./handleFirstVisibleServiceLoadSaga"; - -/** - * A saga for managing requests to load/refresh services data from backend - * @param backendClient - */ -export function* watchLoadServicesSaga( - backendClient: ReturnType -): SagaIterator { - yield* takeEvery( - getType(loadVisibleServices.request), - loadVisibleServicesRequestHandler, - backendClient.getVisibleServices - ); - - yield* fork(watchServicesDetailsSaga, backendClient); - - // start a watcher to handle the load of services details in a bunch (i.e when visible services are loaded) - yield* fork(watchServicesDetailLoadSaga, backendClient.getService); - - // TODO: it could be implemented in a forked saga being canceled as soon as - // isFirstServiceLoadCOmpleted is true (https://redux-saga.js.org/docs/advanced/TaskCancellation.html) - yield* takeEvery( - getType(loadServiceDetail.success), - handleFirstVisibleServiceLoadSaga - ); - - // Load/refresh services content - yield* put(loadVisibleServices.request()); -} diff --git a/ts/sagas/startup.ts b/ts/sagas/startup.ts index 0864c0b8b00..fda6e1b9017 100644 --- a/ts/sagas/startup.ts +++ b/ts/sagas/startup.ts @@ -309,7 +309,7 @@ export function* initializeApplicationSaga( backendClient.deleteUserDataProcessingRequest ); - // Start watching for services actions + // Start watching for Services actions yield* fork(watchServicesSaga, backendClient, sessionToken); // Start watching for Messages actions diff --git a/ts/sagas/startup/__tests__/checkEmailNotificationPreferencesSaga.test.ts b/ts/sagas/startup/__tests__/checkEmailNotificationPreferencesSaga.test.ts index 47f3956bcac..2cf5141d0bf 100644 --- a/ts/sagas/startup/__tests__/checkEmailNotificationPreferencesSaga.test.ts +++ b/ts/sagas/startup/__tests__/checkEmailNotificationPreferencesSaga.test.ts @@ -1,14 +1,7 @@ import * as pot from "@pagopa/ts-commons/lib/pot"; import { testSaga } from "redux-saga-test-plan"; -import { customEmailChannelSetEnabled } from "../../../store/actions/persistedPreferences"; -import { visibleServicesSelector } from "../../../store/reducers/entities/services/visibleServices"; import { isCustomEmailChannelEnabledSelector } from "../../../store/reducers/persistedPreferences"; -import { profileSelector } from "../../../store/reducers/profile"; -import { - checkEmailNotificationPreferencesSaga, - emailNotificationPreferencesSaga, - watchEmailNotificationPreferencesSaga -} from "../checkEmailNotificationPreferencesSaga"; +import { watchEmailNotificationPreferencesSaga } from "../checkEmailNotificationPreferencesSaga"; describe("watchEmailNotificationPreferencesSaga", () => { it("if the store has information about user preferences the saga should end", () => { @@ -23,54 +16,6 @@ describe("watchEmailNotificationPreferencesSaga", () => { testSaga(watchEmailNotificationPreferencesSaga) .next() .select(isCustomEmailChannelEnabledSelector) - .next(pot.none) // have no information about user preferences - .fork(checkEmailNotificationPreferencesSaga) - .next(); - }); -}); - -describe("emailNotificationPreferencesSaga", () => { - it("if profile has is_email_enabled to false, isCustomEmailChannelEnabled should be false", () => { - testSaga(emailNotificationPreferencesSaga) - .next() - .select(profileSelector) - .next(pot.some({ is_email_enabled: false })) // profile - .select(visibleServicesSelector) - .next(pot.some([])) // visible services - .put(customEmailChannelSetEnabled(false)) - .next() - .isDone(); - }); - - it("if profile has is_email_enabled to true but not blocked email, isCustomEmailChannelEnabled should be false", () => { - testSaga(emailNotificationPreferencesSaga) - .next() - .select(profileSelector) - .next(pot.some({ is_email_enabled: true, blocked_inbox_or_channels: {} })) // profile - .select(visibleServicesSelector) - .next(pot.some([])) // visible services - .put(customEmailChannelSetEnabled(false)) - .next() - .isDone(); - }); - - it("if profile has is_email_enabled to true and blocked emails, isCustomEmailChannelEnabled should be true", () => { - testSaga(emailNotificationPreferencesSaga) - .next() - .select(profileSelector) - .next( - pot.some({ - is_email_enabled: true, - blocked_inbox_or_channels: { - service1: ["EMAIL"], - service2: ["EMAIL"] - } - }) - ) // profile - .select(visibleServicesSelector) - .next(pot.some([{ service_id: "service1" }])) // visible services - .put(customEmailChannelSetEnabled(true)) - .next() - .isDone(); + .next(pot.none); // have no information about user preferences }); }); diff --git a/ts/sagas/startup/__tests__/loadVisibleServicesHandler.test.ts b/ts/sagas/startup/__tests__/loadVisibleServicesHandler.test.ts deleted file mode 100644 index 0d659f2f3bf..00000000000 --- a/ts/sagas/startup/__tests__/loadVisibleServicesHandler.test.ts +++ /dev/null @@ -1,74 +0,0 @@ -import * as E from "fp-ts/lib/Either"; -import { testSaga } from "redux-saga-test-plan"; -import { PaginatedServiceTupleCollection } from "../../../../definitions/backend/PaginatedServiceTupleCollection"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { loadVisibleServices } from "../../../store/actions/services"; -import { loadVisibleServicesRequestHandler } from "../loadVisibleServicesHandler"; -import { withRefreshApiCall } from "../../../features/fastLogin/saga/utils"; - -describe("loadVisibleServicesHandler", () => { - describe("loadVisibleServicesRequestHandler", () => { - const getVisibleServices = jest.fn(); - - const mockedVisibleServices: PaginatedServiceTupleCollection["items"] = [ - { service_id: "A01" as ServiceId, version: 1 }, - { service_id: "A02" as ServiceId, version: 5 }, - { service_id: "A03" as ServiceId, version: 2 } - ]; - - it("returns a generic error if backend response is 500", () => { - testSaga(loadVisibleServicesRequestHandler, getVisibleServices) - .next() - .call(withRefreshApiCall, getVisibleServices({}), { - skipThrowingError: true - }) - .next( - E.right({ - status: 500, - value: "An error occurred loading visible services" - }) - ) - .put( - loadVisibleServices.failure( - new Error("An error occurred loading visible services") - ) - ) - .next() - .isDone(); - }); - - describe("returns an error even if the backend response is 401", () => { - it("the session expiration is handled by withRefreshApiCall", () => { - testSaga(loadVisibleServicesRequestHandler, getVisibleServices) - .next() - .call(withRefreshApiCall, getVisibleServices({}), { - skipThrowingError: true - }) - .next( - E.right({ - status: 403, - value: "An error occurred loading visible services" - }) - ) - .put( - loadVisibleServices.failure( - new Error("An error occurred loading visible services") - ) - ) - .next() - .isDone(); - }); - }); - - it("return an array of visibile services if backend response is 200", () => { - testSaga(loadVisibleServicesRequestHandler, getVisibleServices) - .next() - .call(withRefreshApiCall, getVisibleServices({}), { - skipThrowingError: true - }) - .next(E.right({ status: 200, value: { items: mockedVisibleServices } })) - .put(loadVisibleServices.success(mockedVisibleServices)) - .next(); - }); - }); -}); diff --git a/ts/sagas/startup/checkEmailNotificationPreferencesSaga.ts b/ts/sagas/startup/checkEmailNotificationPreferencesSaga.ts index ccfaadacbfc..d0446ca5f37 100644 --- a/ts/sagas/startup/checkEmailNotificationPreferencesSaga.ts +++ b/ts/sagas/startup/checkEmailNotificationPreferencesSaga.ts @@ -1,4 +1,3 @@ -import * as O from "fp-ts/lib/Option"; import * as pot from "@pagopa/ts-commons/lib/pot"; import { SagaIterator } from "redux-saga"; import { @@ -10,17 +9,9 @@ import { takeEvery } from "typed-redux-saga/macro"; import { getType } from "typesafe-actions"; -import { pipe } from "fp-ts/lib/function"; -import { BlockedInboxOrChannels } from "../../../definitions/backend/BlockedInboxOrChannels"; import { customEmailChannelSetEnabled } from "../../store/actions/persistedPreferences"; import { profileLoadSuccess } from "../../store/actions/profile"; -import { loadVisibleServices } from "../../store/actions/services"; -import { - visibleServicesSelector, - VisibleServicesState -} from "../../store/reducers/entities/services/visibleServices"; import { isCustomEmailChannelEnabledSelector } from "../../store/reducers/persistedPreferences"; -import { profileSelector, ProfileState } from "../../store/reducers/profile"; import { ReduxSagaEffect } from "../../types/utils"; /** @@ -49,51 +40,11 @@ export function* watchEmailNotificationPreferencesSaga(): Generator< export function* checkEmailNotificationPreferencesSaga(): SagaIterator { yield* takeEvery( - [getType(profileLoadSuccess), getType(loadVisibleServices.success)], + getType(profileLoadSuccess), emailNotificationPreferencesSaga ); } export function* emailNotificationPreferencesSaga(): SagaIterator { - const potProfile: ProfileState = yield* select(profileSelector); - const potVisibleServices: VisibleServicesState = yield* select( - visibleServicesSelector - ); - /** - * if we have a visible services and a profile (with a defined blocked_inbox_or_channels) - * check if there is at least a service with EMAIL channel blocked. This means user has done - * a custom choice - */ - const potCustomEmailChannelEnabled = pot.map( - potVisibleServices, - visibleService => { - const maybeSomeEmailBlocked = pot.map(potProfile, profile => { - // custom email could be true only if profile.is_email_enabled === true - // and the user made some optin on email channels - if (profile.is_email_enabled === false) { - return false; - } - const blockedChannels: BlockedInboxOrChannels = pipe( - profile.blocked_inbox_or_channels, - O.fromNullable, - O.getOrElse(() => ({})) - ); - return ( - visibleService.findIndex( - service => - blockedChannels[service.service_id] && - blockedChannels[service.service_id].indexOf("EMAIL") !== -1 - ) !== -1 - ); - }); - return pot.getOrElse(maybeSomeEmailBlocked, false); - } - ); - // If the email notification for visible services are partially disabled - // (only for some services), the customization is enabled - yield* put( - customEmailChannelSetEnabled( - pot.getOrElse(potCustomEmailChannelEnabled, false) - ) - ); + yield* put(customEmailChannelSetEnabled(false)); } diff --git a/ts/sagas/startup/loadServiceDetailRequestHandler.ts b/ts/sagas/startup/loadServiceDetailRequestHandler.ts deleted file mode 100644 index 023036e5825..00000000000 --- a/ts/sagas/startup/loadServiceDetailRequestHandler.ts +++ /dev/null @@ -1,190 +0,0 @@ -import { Millisecond } from "@pagopa/ts-commons/lib/units"; -import { buffers, channel, Channel } from "redux-saga"; -import { call, fork, take, takeLatest } from "typed-redux-saga/macro"; -import { ActionType, getType } from "typesafe-actions"; -import { BackendClient } from "../../api/backend"; -import { totServiceFetchWorkers } from "../../config"; -import { applicationChangeState } from "../../store/actions/application"; -import { loadServiceDetail } from "../../features/services/details/store/actions/details"; -import { loadServicesDetail } from "../../store/actions/services"; -import { trackServiceDetailLoadingStatistics } from "../../utils/analytics"; -import { handleServiceDetails } from "../../features/services/details/saga/handleServiceDetails"; - -/** - * A generator that listen for loadServiceDetail.request from a channel and perform the - * handling. - * - * @param requestsChannel The channel where to take the loadServiceDetail.request actions - * @param getService API call to fetch the service detail - */ -function* handleServiceLoadRequest( - requestsChannel: Channel>, - getService: ReturnType["getService"] -) { - // Infinite loop that wait and process loadServiceDetail requests from the channel - while (true) { - const action: ActionType = yield* take( - requestsChannel - ); - yield* call(handleServiceDetails, getService, action); - } -} - -/** - * create an event channel to buffer all services detail loading requests - * it watches for loadServicesDetail (multiple services id) and for each of them, it puts a - * loadServiceDetail.request event into that channel - * The workers (the handlers) will consume the channel data - * @param getService - */ -export function* watchServicesDetailLoadSaga( - getService: ReturnType["getService"] -) { - // start a saga to track services detail load stats - yield* fork(watchLoadServicesDetailToTrack); - - // Create the channel used for the communication with the handlers. - const requestsChannel = (yield* call( - channel, - buffers.expanding() - )) as Channel>; - - // fork the handlers - // eslint-disable-next-line - for (let i = 0; i < totServiceFetchWorkers; i++) { - yield* fork(handleServiceLoadRequest, requestsChannel, getService); - } - - while (true) { - // Take the loadServicesDetail action and for each service id - // put back a loadServiceDetail.request in the channel - // to be processed by the handlers. - const action = yield* take(loadServicesDetail); - - action.payload.forEach((serviceId: string) => - requestsChannel.put(loadServiceDetail.request(serviceId)) - ); - } -} - -const calculateLoadingTime = (startTime: Millisecond): Millisecond => - (startTime !== 0 ? new Date().getTime() - startTime : 0) as Millisecond; - -/** - * listen for loading services details events to extract some track information - * like amount of details to load and how much time they take - */ -function* watchLoadServicesDetailToTrack() { - yield* takeLatest( - [loadServicesDetail, loadServiceDetail.success, applicationChangeState], - action => { - switch (action.type) { - // request to load a set of services detail - // copying object is needed to avoid "immutable" error on frozen objects - case getType(loadServicesDetail): - const stats: ServicesDetailLoadTrack = { - ...servicesDetailLoadTrack, - kind: undefined, - startTime: new Date().getTime() as Millisecond, - servicesId: new Set([...action.payload]), - loaded: 0, - toLoad: action.payload.length - }; - servicesDetailLoadTrack = stats; - break; - // single service detail is been loaded - case getType(loadServiceDetail.success): - servicesDetailLoadTrack.servicesId.delete(action.payload.service_id); - const statsServiceLoad: ServicesDetailLoadTrack = { - ...servicesDetailLoadTrack, - loaded: - servicesDetailLoadTrack.toLoad - - servicesDetailLoadTrack.servicesId.size - }; - servicesDetailLoadTrack = statsServiceLoad; - if ( - statsServiceLoad.servicesId.size === 0 && - statsServiceLoad.loaded > 0 - ) { - // all service are been loaded - trackServicesDetailLoad({ - ...servicesDetailLoadTrack, - kind: "COMPLETE", - loadingTime: calculateLoadingTime( - servicesDetailLoadTrack.startTime - ) - }); - } - - break; - // app changes state - case getType(applicationChangeState): - /** - * if the app went in inactive or background state these measurements - * could be not valid since the OS could apply a freeze or a limitation around the app context - * so the app could run but with few limitations - */ - if ( - action.payload !== "active" && - servicesDetailLoadTrack.servicesId.size > 0 - ) { - trackServicesDetailLoad({ - ...servicesDetailLoadTrack, - loadingTime: calculateLoadingTime( - servicesDetailLoadTrack.startTime - ), - kind: "PARTIAL" - }); - } - // app comes back active, restore stats - else if (action.payload === "active") { - servicesDetailLoadTrack = { - ...servicesDetailLoadTrack, - kind: undefined, - startTime: new Date().getTime() as Millisecond, - loaded: 0, - toLoad: servicesDetailLoadTrack.servicesId.size - }; - } - break; - } - } - ); -} - -export type ServicesDetailLoadTrack = { - // when loading starts - startTime: Millisecond; - // the amount of loading millis - loadingTime: Millisecond; - // the amount of services detail to load - toLoad: number; - // the amount of services detail loaded - loaded: number; - // the set of the services id that remain to be loaded - servicesId: Set; - // COMPLETE: all services detail are been loaded - // PARTIAL: a sub-set of services detail to load are been loaded - kind?: "COMPLETE" | "PARTIAL"; -}; - -const defaultDetailLoadTrack = (): ServicesDetailLoadTrack => ({ - startTime: 0 as Millisecond, - loadingTime: 0 as Millisecond, - toLoad: 0, - loaded: 0, - servicesId: new Set() -}); - -// eslint-disable-next-line functional/no-let -let servicesDetailLoadTrack = defaultDetailLoadTrack(); - -const trackServicesDetailLoad = (trackingStats: ServicesDetailLoadTrack) => { - trackServiceDetailLoadingStatistics(trackingStats); - // reset on complete - // when it is "PARTIAL" data must be keep to be used when the app come active again - if (trackingStats.kind === "COMPLETE") { - // reset data - servicesDetailLoadTrack = defaultDetailLoadTrack(); - } -}; diff --git a/ts/sagas/startup/loadVisibleServicesHandler.ts b/ts/sagas/startup/loadVisibleServicesHandler.ts deleted file mode 100644 index 8826c0a0527..00000000000 --- a/ts/sagas/startup/loadVisibleServicesHandler.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { readableReport } from "@pagopa/ts-commons/lib/reporters"; -import * as E from "fp-ts/lib/Either"; -import { call, put, select } from "typed-redux-saga/macro"; -import { BackendClient } from "../../api/backend"; -import { loadVisibleServices } from "../../store/actions/services"; -import { ReduxSagaEffect, SagaCallReturnType } from "../../types/utils"; -import { convertUnknownToError } from "../../utils/errors"; -import { refreshStoredServices } from "../services/refreshStoredServices"; -import { removeUnusedStoredServices } from "../services/removeUnusedStoredServices"; -import { withRefreshApiCall } from "../../features/fastLogin/saga/utils"; -import { isFastLoginEnabledSelector } from "../../features/fastLogin/store/selectors"; - -/** - * A generator to load the service details from the Backend - * - * @param {function} getService - The function that makes the Backend request - * @param {string} id - The id of the service to load - * @returns {IterableIterator>} - */ -export function* loadVisibleServicesRequestHandler( - getVisibleServices: ReturnType["getVisibleServices"] -): Generator< - ReduxSagaEffect, - void, - SagaCallReturnType -> { - try { - const response = (yield* call(withRefreshApiCall, getVisibleServices({}), { - skipThrowingError: true - })) as unknown as SagaCallReturnType; - - if (E.isLeft(response)) { - throw Error(readableReport(response.left)); - } - if (response.right.status === 401) { - const isFastLoginEnabled = yield* select(isFastLoginEnabledSelector); - if (isFastLoginEnabled) { - return; - } - } - if (response.right.status === 200) { - const { items: visibleServices } = response.right.value; - yield* put(loadVisibleServices.success(visibleServices)); - - // Check if old version of services are stored and load new available versions of services - yield* call(removeUnusedStoredServices, visibleServices); - yield* call(refreshStoredServices, visibleServices); - } else { - throw Error("An error occurred loading visible services"); - } - } catch (e) { - yield* put(loadVisibleServices.failure(convertUnknownToError(e))); - } -} diff --git a/ts/screens/profile/EmailForwardingScreen.tsx b/ts/screens/profile/EmailForwardingScreen.tsx index 3c0158fcd45..4d086d27069 100644 --- a/ts/screens/profile/EmailForwardingScreen.tsx +++ b/ts/screens/profile/EmailForwardingScreen.tsx @@ -16,7 +16,6 @@ import I18n from "../../i18n"; import { BodyProps } from "../../components/core/typography/ComposedBodyFromArray"; import { useIODispatch, useIOSelector } from "../../store/hooks"; import { - ProfileState, isEmailEnabledSelector, profileEmailSelector, profileSelector @@ -24,11 +23,6 @@ import { import { ContextualHelpPropsMarkdown } from "../../components/screens/BaseScreenComponent"; import { profileUpsert } from "../../store/actions/profile"; import { customEmailChannelSetEnabled } from "../../store/actions/persistedPreferences"; -import { getProfileChannelsforServicesList } from "../../utils/profile"; -import { - VisibleServicesState, - visibleServicesSelector -} from "../../store/reducers/entities/services/visibleServices"; import { usePrevious } from "../../utils/hooks/usePrevious"; const contextualHelpMarkdown: ContextualHelpPropsMarkdown = { @@ -43,15 +37,6 @@ const EmailForwardingScreen = () => { const dispatch = useIODispatch(); const profile = useIOSelector(profileSelector, _.isEqual); const prevProfile = usePrevious(profile); - const potVisibleServices: VisibleServicesState = useIOSelector( - visibleServicesSelector - ); - const visibleServicesId = pot.getOrElse( - pot.map(potVisibleServices, services => - services.map(service => service.service_id) - ), - [] - ); const isEmailEnabled = useIOSelector(isEmailEnabledSelector, _.isEqual); const UserEmailSelector = useIOSelector(profileEmailSelector, _.isEqual); const userEmail = pipe( @@ -81,20 +66,13 @@ const EmailForwardingScreen = () => { ); const disableOrEnableAllEmailNotifications = useCallback( - (servicesId: ReadonlyArray, profile: ProfileState) => { - const newBlockedChannels = getProfileChannelsforServicesList( - servicesId, - profile, - true, - "EMAIL" - ); + () => dispatch( profileUpsert.request({ - blocked_inbox_or_channels: newBlockedChannels, + blocked_inbox_or_channels: {}, is_email_enabled: true }) - ); - }, + ), [dispatch] ); @@ -117,17 +95,12 @@ const EmailForwardingScreen = () => { // eslint-disable-next-line functional/immutable-data isCustomChannelEnabledChoice.current = false; if (canSendEmail) { - disableOrEnableAllEmailNotifications(visibleServicesId, profile); + disableOrEnableAllEmailNotifications(); } else { setEmailChannel(false); } }, - [ - disableOrEnableAllEmailNotifications, - profile, - setEmailChannel, - visibleServicesId - ] + [disableOrEnableAllEmailNotifications, setEmailChannel] ); useEffect(() => { diff --git a/ts/screens/services/LegacyServiceDetailsScreen.tsx b/ts/screens/services/LegacyServiceDetailsScreen.tsx deleted file mode 100644 index 8edfdc1bac4..00000000000 --- a/ts/screens/services/LegacyServiceDetailsScreen.tsx +++ /dev/null @@ -1,221 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { pipe } from "fp-ts/lib/function"; -import * as O from "fp-ts/lib/Option"; -import * as React from "react"; -import { useEffect, useState } from "react"; -import { View, SafeAreaView, ScrollView } from "react-native"; -import { connect } from "react-redux"; -import { ContentWrapper, VSpacer } from "@pagopa/io-app-design-system"; -import { Route, useRoute } from "@react-navigation/native"; -import { ServiceId } from "../../../definitions/backend/ServiceId"; -import { SpecialServiceMetadata } from "../../../definitions/backend/SpecialServiceMetadata"; -import { IOStyles } from "../../components/core/variables/IOStyles"; -import ExtractedCTABar from "../../components/cta/ExtractedCTABar"; -import OrganizationHeader from "../../components/OrganizationHeader"; -import BaseScreenComponent, { - ContextualHelpPropsMarkdown -} from "../../components/screens/BaseScreenComponent"; -import { EdgeBorderComponent } from "../../components/screens/EdgeBorderComponent"; -import ContactPreferencesToggles from "../../components/services/ContactPreferencesToggles"; -import ServiceMetadataComponent from "../../components/services/ServiceMetadata"; -import LegacySpecialServicesCTA from "../../components/services/SpecialServices/LegacySpecialServicesCTA"; -import TosAndPrivacyBox from "../../components/services/TosAndPrivacyBox"; -import LegacyMarkdown from "../../components/ui/Markdown/LegacyMarkdown"; -import { FooterTopShadow } from "../../components/FooterTopShadow"; -import I18n from "../../i18n"; -import { useIONavigation } from "../../navigation/params/AppParamsList"; -import { loadServiceDetail } from "../../features/services/details/store/actions/details"; -import { Dispatch } from "../../store/actions/types"; -import { contentSelector } from "../../store/reducers/content"; -import { isDebugModeEnabledSelector } from "../../store/reducers/debug"; -import { serviceByIdPotSelector } from "../../features/services/details/store/reducers/servicesById"; -import { - isEmailEnabledSelector, - isInboxEnabledSelector, - isProfileEmailValidatedSelector, - profileSelector -} from "../../store/reducers/profile"; -import { GlobalState } from "../../store/reducers/types"; -import { getServiceCTA } from "../../features/messages/utils/messages"; -import { logosForService } from "../../utils/services"; -import { handleItemOnPress } from "../../utils/url"; -import { useIOSelector } from "../../store/hooks"; -import { ServiceDetailsScreenRouteParams } from "../../features/services/details/screens/ServiceDetailsScreen"; - -type Props = ReturnType & - ReturnType; - -type SpecialServiceWrapper = { - isSpecialService: boolean; - customSpecialFlowOpt?: string; -}; - -const contextualHelpMarkdown: ContextualHelpPropsMarkdown = { - title: "serviceDetail.headerTitle", - body: "serviceDetail.contextualHelpContent" -}; - -/** - * Screen displaying the details of a selected service. The user - * can enable/disable the service and customize the notification settings. - */ -const LegacyServiceDetailsScreen = (props: Props) => { - const [isMarkdownLoaded, setIsMarkdownLoaded] = useState(false); - const navigation = useIONavigation(); - const { serviceId, activate } = - useRoute>().params; - - const service = useIOSelector(state => - pipe(serviceByIdPotSelector(state, serviceId), pot.toUndefined) - ); - - // const serviceId = props.route.params.serviceId; - // const activate = props.route.params.activate; - - const { loadServiceDetail } = props; - useEffect(() => { - loadServiceDetail(serviceId); - }, [serviceId, loadServiceDetail]); - - const onMarkdownEnd = () => setIsMarkdownLoaded(true); - - // This has been considered just to avoid compiling errors - // once we navigate from list or a message we always have the service data since they're previously loaded - if (service === undefined) { - return null; - } - - const metadata = service.service_metadata; - - // if markdown content is not available, render immediately what is possible - // but we must wait for metadata load to be completed to avoid flashes - const isMarkdownAvailable = metadata?.description; - // if markdown data is available, wait for it to be rendered - const canRenderItems = isMarkdownAvailable ? isMarkdownLoaded : true; - - const specialServiceInfoOpt = SpecialServiceMetadata.is(metadata) - ? ({ - isSpecialService: true, - customSpecialFlowOpt: metadata.custom_special_flow - } as SpecialServiceWrapper) - : undefined; - - const maybeCTA = getServiceCTA(metadata); - const showCTA = - (O.isSome(maybeCTA) || !!specialServiceInfoOpt) && canRenderItems; - - return ( - navigation.goBack()} - headerTitle={I18n.t("serviceDetail.headerTitle")} - contextualHelpMarkdown={contextualHelpMarkdown} - faqCategories={["services_detail"]} - > - - - - - - - {metadata?.description && ( - <> - - {metadata.description} - - - - )} - - {canRenderItems && ( - <> - {metadata && ( - <> - - - - )} - - - - - - - - - )} - - - - {showCTA && ( - - {O.isSome(maybeCTA) && ( - - - - )} - {!!specialServiceInfoOpt && ( - <> - - - - )} - - )} - - - ); -}; - -const mapStateToProps = (state: GlobalState) => ({ - isInboxEnabled: isInboxEnabledSelector(state), - isEmailEnabled: isEmailEnabledSelector(state), - isEmailValidated: isProfileEmailValidatedSelector(state), - content: contentSelector(state), - profile: profileSelector(state), - isDebugModeEnabled: isDebugModeEnabledSelector(state) -}); - -const mapDispatchToProps = (dispatch: Dispatch) => ({ - loadServiceDetail: (id: ServiceId) => dispatch(loadServiceDetail.request(id)), - dispatch -}); - -export default connect( - mapStateToProps, - mapDispatchToProps -)(LegacyServiceDetailsScreen); diff --git a/ts/screens/services/ServicesHomeScreen.tsx b/ts/screens/services/ServicesHomeScreen.tsx deleted file mode 100644 index 0bc9d6552e3..00000000000 --- a/ts/screens/services/ServicesHomeScreen.tsx +++ /dev/null @@ -1,541 +0,0 @@ -/** - * A screen that contains all the available servives. - * - Local tab: services sections related to the areas of interest selected by the user - * - National tab: national services sections - * - All: local and national services sections, not including the user areas of interest - * - * A 'loading component' is displayed (hiding the tabs content) if: - * - visible servcices are loading, or - * - userMetadata is loading, or - * - servicesByScope is loading - * - * An 'error component' is displayed (hiding the tabs content) if: - * - userMetadata load fails, or - * - visible services load fails - * - * A loader on tabs is displayed (not hiding the tabs content) if: - * - userMetadata is updating, or - * - visible services are refreshed - * - * If toastContent is undefined, when userMetadata/visible services are loading/error, - * tabs are hidden and they are displayed renderServiceLoadingPlaceholder/renderErrorPlaceholder - * - */ -import { IOColors, IOToast, VSpacer } from "@pagopa/io-app-design-system"; -import * as pot from "@pagopa/ts-commons/lib/pot"; -import * as O from "fp-ts/lib/Option"; -import { pipe } from "fp-ts/lib/function"; -import * as React from "react"; -import { - Image, - KeyboardAvoidingView, - Platform, - StyleSheet, - View -} from "react-native"; -import { connect } from "react-redux"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import SectionStatusComponent from "../../components/SectionStatus"; -import { Body } from "../../components/core/typography/Body"; -import { IOStyles } from "../../components/core/variables/IOStyles"; -import { ContextualHelpPropsMarkdown } from "../../components/screens/BaseScreenComponent"; -import GenericErrorComponent from "../../components/screens/GenericErrorComponent"; -import TopScreenComponent from "../../components/screens/TopScreenComponent"; -import { MIN_CHARACTER_SEARCH_TEXT } from "../../components/search/SearchButton"; -import { SearchNoResultMessage } from "../../components/search/SearchNoResultMessage"; -import ServicesSearch from "../../components/services/ServicesSearch"; -import FocusAwareStatusBar from "../../components/ui/FocusAwareStatusBar"; -import I18n from "../../i18n"; -import ServicesHomeTabNavigator from "../../navigation/ServicesHomeTabNavigator"; -import { - navigateToServiceDetailsScreen, - navigateToServicePreferenceScreen -} from "../../store/actions/navigation"; -import { profileUpsert } from "../../store/actions/profile"; -import { - loadVisibleServices, - showServiceDetails -} from "../../store/actions/services"; -import { Dispatch } from "../../store/actions/types"; -import { - userMetadataLoad, - userMetadataUpsert -} from "../../store/actions/userMetadata"; -import { - ServicesSectionState, - nationalServicesSectionsSelector, - notSelectedServicesSectionsSelector, - selectedLocalServicesSectionsSelector, - servicesSelector, - visibleServicesDetailLoadStateSelector -} from "../../store/reducers/entities/services"; -import { readServicesByIdSelector } from "../../store/reducers/entities/services/readStateByServiceId"; -import { servicesByIdSelector } from "../../features/services/details/store/reducers/servicesById"; -import { visibleServicesSelector } from "../../store/reducers/entities/services/visibleServices"; -import { wasServiceAlertDisplayedOnceSelector } from "../../store/reducers/persistedPreferences"; -import { ProfileState, profileSelector } from "../../store/reducers/profile"; -import { - isSearchServicesEnabledSelector, - searchTextSelector -} from "../../store/reducers/search"; -import { GlobalState } from "../../store/reducers/types"; -import { - UserMetadata, - userMetadataSelector -} from "../../store/reducers/userMetadata"; -import customVariables from "../../theme/variables"; -import { - getChannelsforServicesList, - getProfileChannelsforServicesList -} from "../../utils/profile"; -import { ServiceDetailsScreenRouteParams } from "../../features/services/details/screens/ServiceDetailsScreen"; - -type ReduxMergedProps = Readonly<{ - updateOrganizationsOfInterestMetadata: ( - selectedItemIds: O.Option> - ) => void; -}>; - -type Props = ReturnType & - ReturnType & - ReduxMergedProps; - -type State = { - currentTab: number; - currentTabServicesId: ReadonlyArray; - isLongPressEnabled: boolean; - enableServices: boolean; - toastErrorMessage: string; - isInnerContentRendered: boolean; -}; - -type DataLoadFailure = - | "servicesLoadFailure" - | "userMetadaLoadFailure" - | undefined; - -const customSpacerHeight = 64; - -const styles = StyleSheet.create({ - container: { - flex: 1 - }, - topScreenContainer: { - flex: 1, - justifyContent: "flex-end" - }, - center: { - alignItems: "center" - }, - padded: { - paddingHorizontal: customVariables.contentPadding - }, - customSpacer: { - height: customSpacerHeight - } -}); - -const contextualHelpMarkdown: ContextualHelpPropsMarkdown = { - title: "services.contextualHelpTitle", - body: "services.contextualHelpContent" -}; - -class ServicesHomeScreen extends React.Component { - constructor(props: Props) { - super(props); - this.state = { - currentTab: 0, - currentTabServicesId: [], - isLongPressEnabled: false, - enableServices: false, - toastErrorMessage: I18n.t("global.genericError"), - isInnerContentRendered: false - }; - } - - /** - * return true if all services have INBOX channel disabled - */ - private areAllServicesInboxChannelDisabled = (): boolean => { - const currentTabServicesChannels = this.props.getServicesChannels( - this.props.tabsServicesId[this.state.currentTab], - this.props.profile - ); - - const disabledServices: number = Object.keys( - currentTabServicesChannels - ).filter( - id => currentTabServicesChannels[id].indexOf("INBOX") !== -1 - ).length; - - return ( - disabledServices > 0 && - disabledServices === Object.keys(currentTabServicesChannels).length - ); - }; - - /** - * if we are displaying the loading screen and we got no errors on loading - * data, then we can show the content - */ - private canRenderContent = () => { - if ( - !this.state.isInnerContentRendered && - pot.isSome(this.props.visibleServicesContentLoadState) && - this.props.loadDataFailure === undefined - ) { - this.setState({ isInnerContentRendered: true }); - } - }; - - public componentDidMount() { - // On mount, update visible services and user metadata if their - // refresh fails - if (pot.isError(this.props.potUserMetadata)) { - this.props.refreshUserMetadata(); - } - - this.canRenderContent(); - - if (pot.isError(this.props.visibleServicesContentLoadState)) { - this.props.refreshVisibleServices(); - } - } - - // TODO: evaluate if it can be replaced by the component introduced within https://www.pivotaltracker.com/story/show/168247501 - private renderServiceLoadingPlaceholder() { - return ( - - {Platform.OS === "ios" && } - - - - - {I18n.t("services.loading.title")} - {I18n.t("services.loading.subtitle")} - - ); - } - - // eslint-disable-next-line - public componentDidUpdate(prevProps: Props, prevState: State) { - // if some errors occur while updating profile, we will show a message in a toast - // profile could be updated by enabling/disabling on or more channel of a service - if ( - pot.isError(this.props.profile) && - !pot.isError(prevProps.profile) && - this.props.profile.error.type !== "PROFILE_EMAIL_IS_NOT_UNIQUE_ERROR" - ) { - IOToast.error(I18n.t("serviceDetail.onUpdateEnabledChannelsFailure")); - } - - const enableServices = this.areAllServicesInboxChannelDisabled(); - if (enableServices !== prevState.enableServices) { - this.setState({ enableServices }); - } - - this.canRenderContent(); - - if (this.state.isInnerContentRendered) { - if ( - pot.isError(this.props.potUserMetadata) && - (pot.isUpdating(prevProps.potUserMetadata) || - pot.isLoading(prevProps.potUserMetadata)) - ) { - // A toast is displayed if upsert userMetadata load fails - IOToast.error(this.state.toastErrorMessage); - } - - if ( - pot.isLoading(prevProps.visibleServicesContentLoadState) && - pot.isError(this.props.visibleServicesContentLoadState) - ) { - // A toast is displayed if refresh visible services fails (on content or metadata load) - IOToast.error(this.state.toastErrorMessage); - } - } - } - - private onServiceSelect = (service: ServicePublic) => { - // when a service gets selected the service is recorded as read - this.props.serviceDetailsLoad(service); - this.props.navigateToServiceDetailsScreen({ - serviceId: service.service_id - }); - }; - - private renderErrorContent = () => { - if (this.state.isInnerContentRendered) { - return undefined; - } - - switch (this.props.loadDataFailure) { - case "userMetadaLoadFailure": - return ( - this.refreshScreenContent(true)} - /> - ); - case "servicesLoadFailure": - return ; - default: - return undefined; - } - }; - - private renderInnerContent = () => { - if (this.state.isInnerContentRendered) { - return this.renderTabs(); - } else { - return this.renderServiceLoadingPlaceholder(); - } - }; - - public render() { - return ( - - - - - {this.renderErrorContent() ? ( - this.renderErrorContent() - ) : this.props.isSearchEnabled ? ( - this.renderSearch() - ) : ( - - {/* */} - {this.renderInnerContent()} - - )} - - - - - ); - } - - /** - * Render ServicesSearch component. - */ - private renderSearch = () => - pipe( - this.props.searchText, - O.map(_ => - _.length < MIN_CHARACTER_SEARCH_TEXT ? ( - - ) : ( - - ) - ), - O.getOrElse(() => ( - - )) - ); - - private refreshServices = () => { - this.setState({ - toastErrorMessage: I18n.t("global.genericError") - }); - this.props.refreshVisibleServices(); - }; - - private refreshScreenContent = (hideToast: boolean = false) => { - if (!hideToast) { - this.setState({ toastErrorMessage: I18n.t("global.genericError") }); - } - this.props.refreshUserMetadata(); - this.props.refreshVisibleServices(); - }; - - /** - * Render Locals, Nationals and Other services tabs. - */ - private renderTabs = () => ( - - - - ); -} - -const mapStateToProps = (state: GlobalState) => { - const potUserMetadata = userMetadataSelector(state); - const userMetadata = pot.getOrElse(potUserMetadata, undefined); - - const localTabSections = selectedLocalServicesSectionsSelector(state); - const nationalTabSections = nationalServicesSectionsSelector(state); - const allTabSections = notSelectedServicesSectionsSelector(state); - - // All visibile services organized in sections - const allSections: ReadonlyArray = [ - ...localTabSections, - ...allTabSections - ]; - - const getTabSevicesId = (tabServices: ReadonlyArray) => - tabServices.reduce( - (acc: ReadonlyArray, curr: ServicesSectionState) => { - const sectionServices = curr.data.reduce( - ( - acc2: ReadonlyArray, - curr2: pot.Pot - ) => { - if (pot.isSome(curr2)) { - return [...acc2, curr2.value.service_id]; - } - return acc2; - }, - [] - ); - return [...acc, ...sectionServices]; - }, - [] - ); - - const tabsServicesId: { [k: number]: ReadonlyArray } = { - [0]: getTabSevicesId(nationalTabSections), - [1]: getTabSevicesId(localTabSections), - [2]: getTabSevicesId(allTabSections) - }; - - const visibleServicesContentLoadState = - visibleServicesDetailLoadStateSelector(state); - - const isLoadingServices = pot.isLoading(visibleServicesContentLoadState); - - const servicesLoadingFailure = - !pot.isLoading(potUserMetadata) && - pot.isError(visibleServicesContentLoadState); - - const loadDataFailure: DataLoadFailure = pot.isError(potUserMetadata) - ? "userMetadaLoadFailure" - : servicesLoadingFailure - ? "servicesLoadFailure" - : undefined; - - return { - debugONLYServices: servicesSelector(state), - isLoadingServices, - visibleServicesContentLoadState, - loadDataFailure, - profile: profileSelector(state), - visibleServices: visibleServicesSelector(state), - readServices: readServicesByIdSelector(state), - allSections, - localTabSections, - nationalTabSections, - allTabSections, - tabsServicesId, - wasServiceAlertDisplayedOnce: wasServiceAlertDisplayedOnceSelector(state), - servicesById: servicesByIdSelector(state), - potUserMetadata, - userMetadata, - isSearchEnabled: isSearchServicesEnabledSelector(state), - searchText: searchTextSelector(state) - }; -}; - -const mapDispatchToProps = (dispatch: Dispatch) => ({ - navigateToServicePreference: () => navigateToServicePreferenceScreen(), - refreshUserMetadata: () => dispatch(userMetadataLoad.request()), - refreshVisibleServices: () => dispatch(loadVisibleServices.request()), - getServicesChannels: ( - servicesId: ReadonlyArray, - profile: ProfileState - ) => getChannelsforServicesList(servicesId, profile), - disableOrEnableServices: ( - servicesId: ReadonlyArray, - profile: ProfileState, - enable: boolean - ) => { - const newBlockedChannels = getProfileChannelsforServicesList( - servicesId, - profile, - enable - ); - dispatch( - profileUpsert.request({ - blocked_inbox_or_channels: newBlockedChannels - }) - ); - }, - saveSelectedOrganizationItems: ( - userMetadata: UserMetadata, - selectedItemIds: ReadonlyArray - ) => { - const metadata = userMetadata.metadata; - const currentVersion: number = userMetadata.version; - dispatch( - userMetadataUpsert.request({ - ...userMetadata, - version: currentVersion + 1, - metadata: { - ...metadata, - organizationsOfInterest: selectedItemIds - } - }) - ); - }, - navigateToServiceDetailsScreen: (params: ServiceDetailsScreenRouteParams) => - navigateToServiceDetailsScreen(params), - serviceDetailsLoad: (service: ServicePublic) => - dispatch(showServiceDetails(service)) -}); - -const mergeProps = ( - stateProps: ReturnType, - dispatchProps: ReturnType -) => { - // If the user updates the area of interest, the upsert of - // the user metadata stored on backend is triggered - const updateOrganizationsOfInterestMetadata = ( - selectedItemIds: O.Option> - ) => { - if (O.isSome(selectedItemIds) && stateProps.userMetadata) { - const updatedAreasOfInterest = Array.from(selectedItemIds.value); - dispatchProps.saveSelectedOrganizationItems( - stateProps.userMetadata, - updatedAreasOfInterest - ); - } - }; - - return { - ...stateProps, - ...dispatchProps, - ...{ - updateOrganizationsOfInterestMetadata - } - }; -}; - -export default connect( - mapStateToProps, - mapDispatchToProps, - mergeProps -)(ServicesHomeScreen); diff --git a/ts/screens/services/ServicesLocalScreen.tsx b/ts/screens/services/ServicesLocalScreen.tsx deleted file mode 100644 index dbcf1cdf60f..00000000000 --- a/ts/screens/services/ServicesLocalScreen.tsx +++ /dev/null @@ -1,43 +0,0 @@ -import React, { useCallback } from "react"; -import { View, StyleSheet } from "react-native"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import { IOStyles } from "../../components/core/variables/IOStyles"; -import LocalServicesWebView from "../../components/services/LocalServicesWebView"; -import { showServiceDetails } from "../../store/actions/services"; -import { useIODispatch } from "../../store/hooks"; -import { useIONavigation } from "../../navigation/params/AppParamsList"; -import { SERVICES_ROUTES } from "../../features/services/common/navigation/routes"; - -const styles = StyleSheet.create({ - contentWrapper: { - flex: 1 - } -}); - -const ServicesLocalScreen = () => { - const dispatch = useIODispatch(); - const navigation = useIONavigation(); - - const onServiceSelect = useCallback( - (service: ServicePublic) => { - // when a service gets selected the service is recorded as read - dispatch(showServiceDetails(service)); - navigation.navigate(SERVICES_ROUTES.SERVICES_NAVIGATOR, { - screen: SERVICES_ROUTES.SERVICE_DETAIL, - params: { serviceId: service.service_id } - }); - }, - [dispatch, navigation] - ); - - return ( - - {/* TODO: This is a workaround to make sure that the list is not placed under the tab bar - https://pagopa.atlassian.net/jira/software/projects/IOAPPFD0/boards/313?selectedIssue=IOAPPFD0-40 */} - - - - ); -}; - -export default ServicesLocalScreen; diff --git a/ts/screens/services/ServicesNationalScreen.tsx b/ts/screens/services/ServicesNationalScreen.tsx deleted file mode 100644 index 57d02bca73e..00000000000 --- a/ts/screens/services/ServicesNationalScreen.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import * as React from "react"; -import { useCallback } from "react"; -import { Animated } from "react-native"; -import { ServicePublic } from "../../../definitions/backend/ServicePublic"; -import ServicesTab from "../../components/services/ServicesTab"; -import { - loadVisibleServices, - showServiceDetails -} from "../../store/actions/services"; -import { userMetadataLoad } from "../../store/actions/userMetadata"; -import { useIODispatch, useIOSelector } from "../../store/hooks"; -import { - nationalServicesSectionsSelector, - visibleServicesDetailLoadStateSelector -} from "../../store/reducers/entities/services"; -import { userMetadataSelector } from "../../store/reducers/userMetadata"; -import { useIONavigation } from "../../navigation/params/AppParamsList"; -import { SERVICES_ROUTES } from "../../features/services/common/navigation/routes"; - -const tabScrollOffset = new Animated.Value(0); - -const ServicesNationalScreen = () => { - const navigation = useIONavigation(); - const dispatch = useIODispatch(); - const nationalTabSections = useIOSelector(nationalServicesSectionsSelector); - const visibleServicesContentLoadState = useIOSelector( - visibleServicesDetailLoadStateSelector - ); - const potUserMetadata = useIOSelector(userMetadataSelector); - const isLoadingServices = pot.isLoading(visibleServicesContentLoadState); - - const isRefreshing = - isLoadingServices || - pot.isLoading(potUserMetadata) || - pot.isUpdating(potUserMetadata); - - const refreshContent = useCallback(() => { - dispatch(userMetadataLoad.request()); - dispatch(loadVisibleServices.request()); - }, [dispatch]); - - const onServiceSelect = useCallback( - (service: ServicePublic) => { - // when a service gets selected the service is recorded as read - dispatch(showServiceDetails(service)); - navigation.navigate(SERVICES_ROUTES.SERVICES_NAVIGATOR, { - screen: SERVICES_ROUTES.SERVICE_DETAIL, - params: { serviceId: service.service_id } - }); - }, - [dispatch, navigation] - ); - - return ( - - ); -}; - -export default ServicesNationalScreen; diff --git a/ts/screens/services/__tests__/ServiceDetailsScreen.test.tsx b/ts/screens/services/__tests__/ServiceDetailsScreen.test.tsx deleted file mode 100644 index d544ae2b9eb..00000000000 --- a/ts/screens/services/__tests__/ServiceDetailsScreen.test.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import configureMockStore from "redux-mock-store"; -import { OrganizationFiscalCode } from "@pagopa/ts-commons/lib/strings"; -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { ServicePublic } from "../../../../definitions/backend/ServicePublic"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { ServiceName } from "../../../../definitions/backend/ServiceName"; -import { OrganizationName } from "../../../../definitions/backend/OrganizationName"; -import { DepartmentName } from "../../../../definitions/backend/DepartmentName"; -import { applicationChangeState } from "../../../store/actions/application"; -import { appReducer } from "../../../store/reducers"; -import { GlobalState } from "../../../store/reducers/types"; -import { renderScreenWithNavigationStoreContext } from "../../../utils/testWrapper"; -import ServiceDetailsScreen from "../LegacyServiceDetailsScreen"; -import { loadServiceDetail } from "../../../features/services/details/store/actions/details"; -import { loadVisibleServices } from "../../../store/actions/services"; -import { SERVICES_ROUTES } from "../../../features/services/common/navigation/routes"; - -jest.useFakeTimers(); - -const service: ServicePublic = { - service_id: "A01" as ServiceId, - service_name: "ciao service" as ServiceName, - organization_name: "org" as OrganizationName, - department_name: "dep" as DepartmentName, - organization_fiscal_code: "12341234" as OrganizationFiscalCode, - version: 1 -}; - -describe("ServiceDetailsScreen", () => { - describe("when service's data load fails", () => { - it("should render the organization's fiscal code even if services list load is in failure", () => { - const { component, store } = renderComponent(); - store.dispatch(loadVisibleServices.failure(new Error("load failed"))); - expect( - component.getByText(service.organization_fiscal_code) - ).toBeDefined(); - }); - - it("should render the organization's fiscal code even if service detail load is in failure", () => { - const { component, store } = renderComponent(); - store.dispatch( - loadServiceDetail.failure({ - error: new Error("load failed"), - service_id: service.service_id - }) - ); - expect( - component.getByText(service.organization_fiscal_code) - ).toBeDefined(); - }); - }); -}); - -const renderComponent = () => { - const globalState = appReducer(undefined, applicationChangeState("active")); - - const mockStore = configureMockStore(); - const store: ReturnType = mockStore({ - ...globalState, - entities: { - ...globalState.entities, - services: { - ...globalState.entities.services, - byId: { - [service.service_id]: pot.some(service) - } - } - } - } as GlobalState); - - return { - component: renderScreenWithNavigationStoreContext( - ServiceDetailsScreen, - SERVICES_ROUTES.SERVICE_DETAIL, - { serviceId: service.service_id }, - store - ), - store - }; -}; diff --git a/ts/store/actions/navigation.ts b/ts/store/actions/navigation.ts index d794d1bdf6b..66735790f57 100644 --- a/ts/store/actions/navigation.ts +++ b/ts/store/actions/navigation.ts @@ -116,16 +116,6 @@ export const navigateToServicesPreferenceModeSelectionScreen = ( * Service */ -/** - * @deprecated - */ -export const navigateToServiceHomeScreen = () => - NavigationService.dispatchNavigationAction( - CommonActions.navigate(SERVICES_ROUTES.SERVICES_NAVIGATOR, { - screen: SERVICES_ROUTES.SERVICES_HOME - }) - ); - /** * @deprecated */ @@ -153,16 +143,6 @@ export const navigateToEmailForwardingPreferenceScreen = () => }) ); -/** - * @deprecated - */ -export const navigateToServicePreferenceScreen = () => - NavigationService.dispatchNavigationAction( - CommonActions.navigate(ROUTES.PROFILE_NAVIGATOR, { - screen: ROUTES.PROFILE_PREFERENCES_SERVICES - }) - ); - /** * @deprecated */ diff --git a/ts/store/actions/search.ts b/ts/store/actions/search.ts index f64ef6b1221..4b6a69986e7 100644 --- a/ts/store/actions/search.ts +++ b/ts/store/actions/search.ts @@ -9,10 +9,6 @@ export const searchMessagesEnabled = createStandardAction( "SEARCH_MESSAGES_ENABLED" )(); -export const searchServicesEnabled = createStandardAction( - "SEARCH_SERVICES_ENABLED" -)(); - export const updateSearchText = createStandardAction("UPDATE_SEARCH_TEXT")>(); @@ -20,6 +16,5 @@ export const disableSearch = createStandardAction("DISABLE_SEARCH")(); export type SearchActions = | ActionType - | ActionType | ActionType | ActionType; diff --git a/ts/store/actions/services/index.ts b/ts/store/actions/services/index.ts deleted file mode 100644 index c721203fcbf..00000000000 --- a/ts/store/actions/services/index.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Action types and action creator related to Services. - */ - -import { ITuple2 } from "@pagopa/ts-commons/lib/tuples"; -import { - ActionType, - createAsyncAction, - createStandardAction -} from "typesafe-actions"; - -import { PaginatedServiceTupleCollection } from "../../../../definitions/backend/PaginatedServiceTupleCollection"; -import { ServiceId } from "../../../../definitions/backend/ServiceId"; -import { ServicePublic } from "../../../../definitions/backend/ServicePublic"; - -// -// service loading at startup -// - -export const firstServiceLoadSuccess = createStandardAction( - "FIRST_SERVICES_LOAD_SUCCESS" -)(); - -// -// load visible services -// - -export const loadVisibleServices = createAsyncAction( - "SERVICES_VISIBLE_LOAD_REQUEST", - "SERVICES_VISIBLE_LOAD_SUCCESS", - "SERVICES_VISIBLE_LOAD_FAILURE" -)(); - -// a specific action used when a requested service is not found -export const loadServiceDetailNotFound = createStandardAction( - "LOAD_SERVICE_DETAIL_NOT_FOUND" -)(); - -export const loadServicesDetail = createStandardAction( - "LOAD_SERVICES_DETAIL_REQUEST" -)>(); - -// -// mark service as read -// - -export const markServiceAsRead = createStandardAction( - "MARK_SERVICE_AS_READ" -)(); - -// -// show service detail -// - -export const showServiceDetails = createStandardAction( - "SERVICE_SHOW_DETAILS" -)(); - -// Remove services passing a list of tuples with serviceId and organizationFiscalCode -export const removeServiceTuples = createStandardAction( - "SERVICES_REMOVE_TUPLES" -)>>(); - -export type ServicesActions = - | ActionType - | ActionType - | ActionType - | ActionType - | ActionType - | ActionType - | ActionType; diff --git a/ts/store/actions/types.ts b/ts/store/actions/types.ts index ef131771e49..1f037b8f02e 100644 --- a/ts/store/actions/types.ts +++ b/ts/store/actions/types.ts @@ -22,7 +22,7 @@ import { AbiActions } from "../../features/wallet/onboarding/bancomat/store/acti import { BPayActions } from "../../features/wallet/onboarding/bancomatPay/store/actions"; import { CoBadgeActions } from "../../features/wallet/onboarding/cobadge/store/actions"; import { PayPalOnboardingActions } from "../../features/wallet/onboarding/paypal/store/actions"; -import { ServicesActions as NewServicesActions } from "../../features/services/common/store/actions"; +import { ServicesActions } from "../../features/services/common/store/actions"; import { WhatsNewActions } from "../../features/whatsnew/store/actions"; import { ZendeskSupportActions } from "../../features/zendesk/store/actions"; import { NotificationsActions } from "../../features/pushNotifications/store/actions/notifications"; @@ -53,7 +53,6 @@ import { PreferencesActions } from "./preferences"; import { ProfileActions } from "./profile"; import { ProfileEmailValidationAction } from "./profileEmailValidationChange"; import { SearchActions } from "./search"; -import { ServicesActions } from "./services"; import { StartupActions } from "./startup"; import { UserDataProcessingActions } from "./userDataProcessing"; import { UserMetadataActions } from "./userMetadata"; @@ -107,7 +106,6 @@ export type Action = | PaymentsFeatureActions | NewWalletActions | CieLoginConfigActions - | NewServicesActions | FimsActions | ItwActions | TrialSystemActions diff --git a/ts/store/reducers/entities/index.ts b/ts/store/reducers/entities/index.ts index 50216ec9b59..21525123719 100644 --- a/ts/store/reducers/entities/index.ts +++ b/ts/store/reducers/entities/index.ts @@ -24,12 +24,10 @@ import messagesStatusReducer, { import calendarEventsReducer, { CalendarEventsState } from "./calendarEvents"; import organizationsReducer, { OrganizationsState } from "./organizations"; import { paymentByRptIdReducer, PaymentByRptIdState } from "./payments"; -import servicesReducer, { ServicesState } from "./services"; export type EntitiesState = Readonly<{ messages: MessagesState; messagesStatus: MessagesStatus; - services: ServicesState; organizations: OrganizationsState; paymentByRptId: PaymentByRptIdState; calendarEvents: CalendarEventsState; @@ -37,17 +35,12 @@ export type EntitiesState = Readonly<{ export type PersistedEntitiesState = EntitiesState & PersistPartial; -const CURRENT_REDUX_ENTITIES_STORE_VERSION = 2; +const CURRENT_REDUX_ENTITIES_STORE_VERSION = 3; const migrations: MigrationManifest = { // version 0 // remove "currentSelectedService" section - "0": (state: PersistedState): PersistedEntitiesState => { - const entities = state as PersistedEntitiesState; - return { - ...entities, - services: { ..._.omit(entities.services, "currentSelectedService") } - }; - }, + "0": (state: PersistedState) => + _.omit(state, "services.currentSelectedService"), // version 1 // remove services section from persisted entities // TO avoid the proliferation of too many API requests until paged messages' API has been introduced @@ -67,7 +60,10 @@ const migrations: MigrationManifest = { ..._.omit(entities.messages, "allIds", "idsByServiceId", "byId") } }; - } + }, + // version 3 + // remove services from persisted entities + "3": (state: PersistedState) => _.omit(state, "services") }; // A custom configuration to avoid persisting messages section @@ -83,7 +79,6 @@ export const entitiesPersistConfig: PersistConfig = { const reducer = combineReducers({ messages: messagesReducer, messagesStatus: messagesStatusReducer, - services: servicesReducer, organizations: organizationsReducer, paymentByRptId: paymentByRptIdReducer, calendarEvents: calendarEventsReducer diff --git a/ts/store/reducers/entities/services/__tests__/index.test.ts b/ts/store/reducers/entities/services/__tests__/index.test.ts deleted file mode 100644 index 67a82bb73f9..00000000000 --- a/ts/store/reducers/entities/services/__tests__/index.test.ts +++ /dev/null @@ -1,337 +0,0 @@ -// TODO: it has to be updated due to https://www.pivotaltracker.com/story/show/169013940 - -// It implies item 42, not having the corresponding serviceMetadata being loaded, is not included among the local sections -// Check what happen with items 41 and 42 beign someLoading and someError -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { - NonEmptyString, - OrganizationFiscalCode -} from "@pagopa/ts-commons/lib/strings"; -import { - localServicesSectionsSelector, - nationalServicesSectionsSelector, - notSelectedServicesSectionsSelector, - organizationsOfInterestSelector, - servicesBadgeValueSelector, - ServicesSectionState, - ServicesState, - visibleServicesDetailLoadStateSelector -} from ".."; -import { DepartmentName } from "../../../../../../definitions/backend/DepartmentName"; -import { OrganizationName } from "../../../../../../definitions/backend/OrganizationName"; -import { ServiceId } from "../../../../../../definitions/backend/ServiceId"; -import { ServiceName } from "../../../../../../definitions/backend/ServiceName"; -import { ServiceTuple } from "../../../../../../definitions/backend/ServiceTuple"; -import { UserMetadataState } from "../../../userMetadata"; -import { OrganizationsState } from "../../organizations"; -import { ServicesByIdState } from "../../../../../features/services/details/store/reducers/servicesById"; -import { VisibleServicesState } from "../visibleServices"; -import { ServiceScopeEnum } from "../../../../../../definitions/backend/ServiceScope"; -import { StandardServiceCategoryEnum } from "../../../../../../definitions/backend/StandardServiceCategory"; - -const customPotUserMetadata: UserMetadataState = pot.some({ - version: 1, - metadata: { - experimentalFeatures: true, - organizationsOfInterest: ["1", "2", "3", "4"] - } -}); - -const customServices: ServicesState = { - servicePreference: pot.none, - byId: { - ["11"]: pot.noneError(Error()), - ["21"]: pot.some({ - department_name: "test" as DepartmentName, - organization_fiscal_code: "2" as OrganizationFiscalCode, - organization_name: "organization2" as OrganizationName, - service_id: "21" as ServiceId, - service_name: "service1" as ServiceName, - version: 1, - service_metadata: { - category: StandardServiceCategoryEnum.STANDARD, - scope: ServiceScopeEnum.LOCAL - } - }), - ["22"]: undefined, - ["31"]: pot.someLoading({ - department_name: "test" as DepartmentName, - organization_fiscal_code: "3" as OrganizationFiscalCode, - organization_name: "organization3" as OrganizationName, - service_id: "31" as ServiceId, - service_name: "service1" as ServiceName, - version: 1 - }), - ["41"]: pot.someError( - { - department_name: "test" as DepartmentName, - organization_fiscal_code: "4" as OrganizationFiscalCode, - organization_name: "organization4" as OrganizationName, - service_id: "41" as ServiceId, - service_name: "service1" as ServiceName, - version: 1, - service_metadata: { - category: StandardServiceCategoryEnum.STANDARD, - - scope: ServiceScopeEnum.LOCAL - } - }, - Error("Generic error") - ), - ["42"]: pot.someLoading({ - department_name: "test" as DepartmentName, - organization_fiscal_code: "4" as OrganizationFiscalCode, - organization_name: "organization4" as OrganizationName, - service_id: "42" as ServiceId, - service_name: "service1" as ServiceName, - version: 1 - }), - ["43"]: pot.someLoading({ - department_name: "test" as DepartmentName, - organization_fiscal_code: "5" as OrganizationFiscalCode, - organization_name: "same_organization_name" as OrganizationName, - service_id: "43" as ServiceId, - service_name: "service1" as ServiceName, - version: 1 - }), - ["44"]: pot.someLoading({ - department_name: "test" as DepartmentName, - organization_fiscal_code: "6" as OrganizationFiscalCode, - organization_name: "same_organization_name" as OrganizationName, - service_id: "44" as ServiceId, - service_name: "service1" as ServiceName, - version: 1 - }) - }, - byOrgFiscalCode: { - ["2"]: ["21" as ServiceId, "22" as ServiceId] as ReadonlyArray, - ["3"]: ["31" as ServiceId] as ReadonlyArray, - ["4"]: ["41" as ServiceId, "42" as ServiceId] as ReadonlyArray, - ["5"]: ["43" as ServiceId] as ReadonlyArray, - ["6"]: ["44" as ServiceId] as ReadonlyArray - }, - visible: pot.some([ - { service_id: "11", version: 1 } as ServiceTuple, - { service_id: "21", version: 1 } as ServiceTuple, - { service_id: "22", version: 1 } as ServiceTuple, - { service_id: "41", version: 1 } as ServiceTuple, - { service_id: "43", version: 1 } as ServiceTuple, - { service_id: "44", version: 1 } as ServiceTuple - ]), - readState: { - ["21"]: true - }, - firstLoading: { - isFirstServicesLoadingCompleted: true - } -}; - -const customOrganizations: OrganizationsState = { - all: [ - { - name: "organizzazion2", - fiscalCode: "2" - }, - { - name: "organization3", - fiscalCode: "3" - }, - { - name: "organization4", - fiscalCode: "4" - }, - { - name: "same_organization_name", - fiscalCode: "5" - }, - { - name: "same_organization_name", - fiscalCode: "6" - } - ], - nameByFiscalCode: { - ["2" as OrganizationFiscalCode]: "organizzazion2" as NonEmptyString, - ["3" as OrganizationFiscalCode]: "organizzazion3" as NonEmptyString, - ["4" as OrganizationFiscalCode]: "organizzazion4" as NonEmptyString, - ["5" as OrganizationFiscalCode]: "same_organization_name" as NonEmptyString, - ["6" as OrganizationFiscalCode]: "same_organization_name" as NonEmptyString - } -}; - -const localServices: ReadonlyArray = [ - { - organizationName: customOrganizations.nameByFiscalCode["2"] as string, - organizationFiscalCode: "2" as OrganizationFiscalCode, - data: [customServices.byId["21"]] - } as ServicesSectionState, - { - organizationName: customOrganizations.nameByFiscalCode["4"] as string, - organizationFiscalCode: "4" as OrganizationFiscalCode, - data: [customServices.byId["41"]] - } as ServicesSectionState -]; - -const nationalServices: ReadonlyArray = []; - -describe("organizationsOfInterestSelector", () => { - it("should include organizations in the user organizationsOfInterest and providing visible services among those properly loaded", () => { - expect( - organizationsOfInterestSelector.resultFunc( - customPotUserMetadata, - customServices - ) - ).toStrictEqual(["2", "4"]); - }); -}); - -describe("nationalServicesSectionsSelector", () => { - it("should return the services having scope equal to NATIONAL", () => { - expect( - nationalServicesSectionsSelector.resultFunc( - customServices, - customOrganizations.nameByFiscalCode - ) - ).toStrictEqual(nationalServices); - }); -}); - -describe("localServicesSectionsSelector", () => { - it("should return the services having metadata and scope equal to LOCAL", () => { - expect( - localServicesSectionsSelector.resultFunc( - customServices, - customOrganizations.nameByFiscalCode - ) - ).toStrictEqual(localServices); - }); -}); - -describe("notSelectedServicesSectionsSelector", () => { - it("should return all the visible services with scope equal to both NATIONAL and LOCAL if the user organizationsOfInterest is empty", () => { - expect( - notSelectedServicesSectionsSelector.resultFunc( - customServices, - customOrganizations.nameByFiscalCode, - [""] - ) - ).toStrictEqual([ - { - organizationName: customOrganizations.nameByFiscalCode["2"] as string, - organizationFiscalCode: "2" as OrganizationFiscalCode, - data: [customServices.byId["21"]] - }, - { - organizationName: customOrganizations.nameByFiscalCode["4"] as string, - organizationFiscalCode: "4" as OrganizationFiscalCode, - data: [customServices.byId["41"]] - }, - { - organizationName: customOrganizations.nameByFiscalCode["5"] as string, - organizationFiscalCode: "5" as OrganizationFiscalCode, - data: [customServices.byId["43"], customServices.byId["44"]] - } - ]); - }); -}); - -describe("notSelectedServicesSectionsSelector", () => { - it("should return all the visible services with scope equal to both NATIONAL and LOCAL not included in organizationsOfInterest", () => { - expect( - notSelectedServicesSectionsSelector.resultFunc( - customServices, - customOrganizations.nameByFiscalCode, - ["4", "5"] // this organization has the same name of another organization (id:6) - ) - ).toStrictEqual([ - { - organizationName: customOrganizations.nameByFiscalCode["2"] as string, - organizationFiscalCode: "2" as OrganizationFiscalCode, - data: [customServices.byId["21"]] - } - ]); - }); -}); - -describe("visibleServicesDetailLoadStateSelector", () => { - it("should do be pot.noneLoading if at least one visible service is loading", () => { - expect( - visibleServicesDetailLoadStateSelector.resultFunc( - customServices.byId, - customServices.visible - ) - ).toBe(pot.noneLoading); - }); - - it("should do be pot.some when a service is loading but it is some", () => { - const data = { - byId: { - "azure-deployc49a": { - kind: "PotSomeLoading", - value: { - available_notification_channels: ["EMAIL", "WEBHOOK"], - department_name: "Progetto IO", - organization_fiscal_code: "15376371009", - organization_name: "IO - L'app dei servizi pubblici", - service_id: "azure-deployc49a", - service_name: "Novità e aggiornamenti", - version: 2 - } - } - }, - byOrgFiscalCode: { - "15376371009": ["azure-deployc49a"] - }, - visible: { - kind: "PotSome", - value: [ - { - scope: "NATIONAL", - service_id: "azure-deployc49a", - version: 1 - } - ] - } - }; - expect( - visibleServicesDetailLoadStateSelector.resultFunc( - data.byId as ServicesByIdState, - data.visible as VisibleServicesState - ) - ).toEqual(pot.some(undefined)); - }); -}); - -describe("servicesBadgeValueSelector", () => { - it("should return the number of unread services", () => { - expect( - servicesBadgeValueSelector.resultFunc( - [...nationalServices], - [...localServices], - customServices.readState, - true - ) - ).toBe(1); - }); - - it("should return 0 if the first load is not yet completed", () => { - expect( - servicesBadgeValueSelector.resultFunc( - [...nationalServices], - [...localServices], - customServices.readState, - false - ) - ).toBe(0); - }); - - it("should return 1 even if we have few duplication in services array", () => { - expect( - servicesBadgeValueSelector.resultFunc( - [...nationalServices], - [...localServices, ...localServices, ...localServices], - customServices.readState, - true - ) - ).toBe(1); - }); -}); diff --git a/ts/store/reducers/entities/services/__tests__/readStateByServiceId.test.ts b/ts/store/reducers/entities/services/__tests__/readStateByServiceId.test.ts deleted file mode 100644 index 47fa8c38a2e..00000000000 --- a/ts/store/reducers/entities/services/__tests__/readStateByServiceId.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { OrganizationFiscalCode } from "@pagopa/ts-commons/lib/strings"; -import { appReducer } from "../../../index"; -import { - loadServiceDetailNotFound, - markServiceAsRead, - showServiceDetails -} from "../../../../actions/services"; -import { ServicePublic } from "../../../../../../definitions/backend/ServicePublic"; -import { ServiceId } from "../../../../../../definitions/backend/ServiceId"; -import { ServiceName } from "../../../../../../definitions/backend/ServiceName"; -import { NotificationChannelEnum } from "../../../../../../definitions/backend/NotificationChannel"; -import { OrganizationName } from "../../../../../../definitions/backend/OrganizationName"; -import { DepartmentName } from "../../../../../../definitions/backend/DepartmentName"; - -const mockService: ServicePublic = { - department_name: "dev department name" as DepartmentName, - organization_fiscal_code: "00000000001" as OrganizationFiscalCode, - organization_name: "Ramella, Zanetti and Maggiani [1]" as OrganizationName, - service_id: "id1" as ServiceId, - service_name: "reinventate next-generation architetture" as ServiceName, - available_notification_channels: [NotificationChannelEnum.EMAIL], - version: 1 -}; - -describe("readServicesByIdReducer", () => { - it("should be read", () => { - const state = appReducer(undefined, showServiceDetails(mockService)); - expect(state.entities.services.readState.id1).toBeTruthy(); - }); - - it("should be read", () => { - const state = appReducer(undefined, markServiceAsRead("id2" as ServiceId)); - expect(state.entities.services.readState.id2).toBeTruthy(); - }); - - it("should be undefined", () => { - const state = appReducer(undefined, showServiceDetails(mockService)); - expect(state.entities.services.readState.id3).toBeUndefined(); - }); - - it("should remove a specific not found service read state", () => { - const state1 = appReducer(undefined, markServiceAsRead("id1" as ServiceId)); - const state2 = appReducer(state1, markServiceAsRead("id2" as ServiceId)); - expect(state2.entities.services.readState.id1).toBeTruthy(); - expect(state2.entities.services.readState.id2).toBeTruthy(); - const updateState = appReducer( - state2, - loadServiceDetailNotFound("id1" as ServiceId) - ); - expect(updateState.entities.services.readState.id1).toBeUndefined(); - expect(state2.entities.services.readState.id2).toBeTruthy(); - }); -}); diff --git a/ts/store/reducers/entities/services/__tests__/servicesByOrganizationFiscalCode.test.ts b/ts/store/reducers/entities/services/__tests__/servicesByOrganizationFiscalCode.test.ts deleted file mode 100644 index 0c8212c3156..00000000000 --- a/ts/store/reducers/entities/services/__tests__/servicesByOrganizationFiscalCode.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { Tuple2 } from "@pagopa/ts-commons/lib/tuples"; - -import { removeServiceTuples } from "../../../../actions/services"; -import { serviceIdsByOrganizationFiscalCodeReducer } from "../servicesByOrganizationFiscalCode"; - -const initialState = { - a: ["s1", "s2", "s3"], - b: ["s4", "s5", "s6", "s7"] -}; - -describe("servicesByOrganizationFiscalCode", () => { - it("should handle removeServiceTuples correctly", () => { - const action = removeServiceTuples([ - Tuple2("s2", "a"), - Tuple2("s3", "a"), - Tuple2("s6", "b"), - // Not existing serviceId - Tuple2("s8", "b"), - // Not existing organizationFiscalCode - Tuple2("s9", "c") - ]); - - const expectedState = { - a: ["s1"], - b: ["s4", "s5", "s7"] - }; - - const obtainedState = serviceIdsByOrganizationFiscalCodeReducer( - initialState as any, - action - ); - - expect(obtainedState).toMatchObject(expectedState); - }); -}); diff --git a/ts/store/reducers/entities/services/firstServicesLoading.ts b/ts/store/reducers/entities/services/firstServicesLoading.ts deleted file mode 100644 index 46c078f3a9d..00000000000 --- a/ts/store/reducers/entities/services/firstServicesLoading.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { getType } from "typesafe-actions"; -import { firstServiceLoadSuccess } from "../../../actions/services"; -import { Action } from "../../../actions/types"; -import { GlobalState } from "../../types"; - -export type FirstLoadingState = Readonly<{ - isFirstServicesLoadingCompleted: boolean; -}>; - -const INITIAL_STATE: FirstLoadingState = { - isFirstServicesLoadingCompleted: false -}; - -// Reducer -export const firstLoadingReducer = ( - state: FirstLoadingState = INITIAL_STATE, - action: Action -): FirstLoadingState => { - switch (action.type) { - case getType(firstServiceLoadSuccess): { - return { - isFirstServicesLoadingCompleted: true - }; - } - - default: - return state; - } -}; - -// Selectors -export const isFirstVisibleServiceLoadCompletedSelector = ( - state: GlobalState -) => state.entities.services.firstLoading.isFirstServicesLoadingCompleted; diff --git a/ts/store/reducers/entities/services/index.ts b/ts/store/reducers/entities/services/index.ts deleted file mode 100644 index 6a699761edd..00000000000 --- a/ts/store/reducers/entities/services/index.ts +++ /dev/null @@ -1,426 +0,0 @@ -/** - * Services reducer - */ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { pipe } from "fp-ts/lib/function"; -import * as O from "fp-ts/lib/Option"; -import { combineReducers } from "redux"; -import { createSelector } from "reselect"; -import { ServicePublic } from "../../../../../definitions/backend/ServicePublic"; -import { ServiceScopeEnum } from "../../../../../definitions/backend/ServiceScope"; -import servicePreferenceReducer, { - ServicePreferenceState -} from "../../../../features/services/details/store/reducers/servicePreference"; -import servicesByIdReducer, { - servicesByIdSelector, - ServicesByIdState -} from "../../../../features/services/details/store/reducers/servicesById"; -import { isDefined } from "../../../../utils/guards"; -import { isVisibleService } from "../../../../utils/services"; -import { Action } from "../../../actions/types"; -import { GlobalState } from "../../types"; -import { userMetadataSelector } from "../../userMetadata"; -import { - organizationNamesByFiscalCodeSelector, - OrganizationNamesByFiscalCodeState -} from "../organizations/organizationsByFiscalCodeReducer"; -import { - firstLoadingReducer, - FirstLoadingState, - isFirstVisibleServiceLoadCompletedSelector -} from "./firstServicesLoading"; -import readServicesByIdReducer, { - readServicesByIdSelector, - ReadStateByServicesId -} from "./readStateByServiceId"; -import { - serviceIdsByOrganizationFiscalCodeReducer, - ServiceIdsByOrganizationFiscalCodeState -} from "./servicesByOrganizationFiscalCode"; -import { - visibleServicesReducer, - visibleServicesSelector, - VisibleServicesState -} from "./visibleServices"; - -export type ServicesState = Readonly<{ - // Section to hold the preference for services - servicePreference: ServicePreferenceState; - byId: ServicesByIdState; - byOrgFiscalCode: ServiceIdsByOrganizationFiscalCodeState; - visible: VisibleServicesState; - readState: ReadStateByServicesId; - firstLoading: FirstLoadingState; -}>; - -export type ServicesSectionState = Readonly<{ - organizationName: string; - organizationFiscalCode: string; - data: ReadonlyArray>; -}>; - -const reducer = combineReducers({ - servicePreference: servicePreferenceReducer, - byId: servicesByIdReducer, - byOrgFiscalCode: serviceIdsByOrganizationFiscalCodeReducer, - visible: visibleServicesReducer, - readState: readServicesByIdReducer, - firstLoading: firstLoadingReducer -}); - -/** - * Selectors - */ - -export const servicesSelector = (state: GlobalState) => state.entities.services; - -/** - * The function returns: - * - pot.none if visibleServices is not loaded or the related services load is not yet started - * - pot.noneLoading if visibleServices or at least one visible service is loading - * - pot.noneError if visibleServices or at least one visible service load fails - * - pot.some if both visible services and all services load successfully - * @param visibleServices - list of visible services - * @param services - collection of services related data indexed with respect to the services id - * (applied for entities.services.byId state) - */ -function getServicesLoadState( - visibleServices: VisibleServicesState, - services: Readonly<{ - [key: string]: pot.Pot | undefined; - }> -): pot.Pot { - if (pot.isSome(visibleServices) && Object.keys(services).length > 0) { - const visibleServicesById = visibleServices.value.map( - service => services[service.service_id] - ); - - // check if there is at least one service in loading state - const areServicesLoading = - pot.isLoading(visibleServices) || - visibleServicesById.some( - vs => vs === undefined || (pot.isNone(vs) && pot.isLoading(vs)) - ); - - // check if there is at least one service in error state - const isServicesLoadFailed = - pot.isError(visibleServices) || - visibleServicesById.some( - service => service !== undefined && pot.isError(service) - ); - - if (areServicesLoading) { - return pot.noneLoading; - } else if (isServicesLoadFailed) { - return pot.noneError(Error(`Unable to load one or more services`)); - } else { - return pot.some(undefined); - } - } - - // If visibleServices is none - if (pot.isLoading(visibleServices)) { - return pot.noneLoading; - } else if (pot.isError(visibleServices)) { - return pot.noneError(Error("Unable to load visible services")); - } else { - return pot.none; - } -} - -// A selector to monitor the state of the service detail loading -export const visibleServicesDetailLoadStateSelector = createSelector( - [servicesByIdSelector, visibleServicesSelector], - (servicesById, visibleServices) => - getServicesLoadState(visibleServices, servicesById) -); - -/** - * A selector to get the organizations selected by the user as areas of interests - * which provide visible services - */ -export const organizationsOfInterestSelector = createSelector( - [userMetadataSelector, servicesSelector], - (potUserMetadata, services) => { - const visibleServices = new Set( - pot.getOrElse(services.visible, []).map(_ => _.service_id) - ); - - // If the user never select areas of interest, return an undefined object - return pot.toUndefined( - pot.map(potUserMetadata, _ => - // filter organization by selecting those ones having - // at least 1 visible service inside - _.metadata.organizationsOfInterest - ? _.metadata.organizationsOfInterest.filter(org => { - const organizationServices = services.byOrgFiscalCode[org] || []; - return organizationServices.some(serviceId => - visibleServices.has(serviceId) - ); - }) - : [] - ) - ); - } -); - -/** - * Functions and selectors to get services organized in sections - */ - -// Check if the passed service is local or national through data included into serviceByScope store item. -// If the scope parameter is expressed, the corresponding item is not included into the section if: -// - the scope parameter is different to the service scope -// - service detail or serviceByScope loading fails -const isInScope = ( - service: pot.Pot, - scope?: ServiceScopeEnum -) => { - if (scope === undefined) { - return true; - } - - // if service is in Error, the item is not included into the section - return pot.getOrElse( - pot.map(service, s => s.service_metadata?.scope === scope), - false - ); -}; - -// NOTE: this is a workaround not a solution -// since a service can change its organization fiscal code we could have -// obsolete data in the store: byOrgFiscalCode could have services that don't belong to organization anymore -// this cleaning its a workaround, this should be fixed on data loading and not when data are loaded -// see https://www.pivotaltracker.com/story/show/172316333 -/** - * return true if service belongs to the given organization fiscal code - * @param service - * @param organizationFiscalCode - */ -const belongsToOrganization = ( - service: pot.Pot, - organizationsFiscalCode: ReadonlyArray -) => - pot.getOrElse( - pot.map( - service, - s => organizationsFiscalCode.indexOf(s.organization_fiscal_code) !== -1 - ), - false - ); - -/** - * A generalized function to generate sections of organizations including the available services for each organization - * optional input: - * - scope: if undefined, all available organizations are included. If expressed, it requires service metadata being loaded - * - organizationsFiscalCodesSelected: if provided, sections will include only the passed organizations - */ -const getServices = ( - services: ServicesState, - organizations: OrganizationNamesByFiscalCodeState, - scope?: ServiceScopeEnum, - selectedOrganizationsFiscalCodes?: ReadonlyArray -) => { - const organizationsFiscalCodes = - selectedOrganizationsFiscalCodes === undefined - ? Object.keys(services.byOrgFiscalCode) - : selectedOrganizationsFiscalCodes; - // another workaround to avoid to display same organizations name that have different cf - // we group services by organization name - // to avoid duplication we keep in a set all organization fiscal code processed - const orgFiscalCodeProcessed = new Set(); - return organizationsFiscalCodes - .map((fiscalCode: string) => { - const organizationName = organizations[fiscalCode] || fiscalCode; - const organizationFiscalCode = fiscalCode; - if (orgFiscalCodeProcessed.has(fiscalCode)) { - return { - organizationName, - organizationFiscalCode, - data: [] - }; - } - - const orgsFiscalCodes = Object.keys(organizations).filter(cf => - pipe( - organizations[cf], - O.fromNullable, - O.fold( - () => false, - name => organizationName === name // select all services that belong to organizations having organizationName - ) - ) - ); - orgsFiscalCodes.forEach(ocf => orgFiscalCodeProcessed.add(ocf)); - const serviceIdsForOrg = orgsFiscalCodes.reduce( - (acc: ReadonlyArray, curr: string) => [ - ...acc, - ...(services.byOrgFiscalCode[curr] || []) - ], - [] - ); - - const data = serviceIdsForOrg - .map(id => services.byId[id]) - .filter( - service => - isDefined(service) && - belongsToOrganization(service, orgsFiscalCodes) && // workaround: see comments above this function definition - isInScope(service, scope) && - isVisibleService(services.visible, service) - ) - .sort((a, b) => - a && pot.isSome(a) && b && pot.isSome(b) - ? a.value.service_name - .toLocaleLowerCase() - .localeCompare(b.value.service_name.toLocaleLowerCase()) - : 0 - ); - - return { - organizationName, - organizationFiscalCode, - data - } as ServicesSectionState; - }) - .filter(_ => _.data.length > 0) - .sort((a, b) => - a.organizationName - .toLocaleLowerCase() - .localeCompare(b.organizationName.toLocaleLowerCase()) - ); -}; - -// A selector providing sections related to national services -export const nationalServicesSectionsSelector = createSelector( - [servicesSelector, organizationNamesByFiscalCodeSelector], - (services, organizations) => - getServices(services, organizations, ServiceScopeEnum.NATIONAL) -); - -// A selector providing sections related to local services -export const localServicesSectionsSelector = createSelector( - [servicesSelector, organizationNamesByFiscalCodeSelector], - (services, organizations) => - getServices(services, organizations, ServiceScopeEnum.LOCAL) -); - -// A selector providing sections related to the organizations selected by the user -export const selectedLocalServicesSectionsSelector = createSelector( - [ - servicesSelector, - organizationNamesByFiscalCodeSelector, - organizationsOfInterestSelector - ], - (services, organizations, selectedOrganizations) => - getServices(services, organizations, undefined, selectedOrganizations) -); - -// A selector providing sections related to: -// - all national services -// - local services not included into the user areas of interest -export const notSelectedServicesSectionsSelector = createSelector( - [ - servicesSelector, - organizationNamesByFiscalCodeSelector, - organizationsOfInterestSelector - ], - (services, organizations, selectedOrganizations) => { - const notSelectedOrganizations = pipe( - organizations, - O.fromNullable, - O.map(orgs => { - // add to organizations all cf of other organizations having the same organization name - const organizationsWithSameNames = pipe( - selectedOrganizations, - O.fromNullable, - O.map(so => - so.reduce((acc, curr) => { - const orgName = O.fromNullable(orgs[curr]); - return pipe( - orgName, - O.fold( - () => acc, - on => { - if (organizations !== undefined) { - const orgsFiscalCodes = Object.keys(organizations).filter( - cf => - pipe( - organizations[cf], - O.fromNullable, - O.fold( - () => false, - name => on === name // select all services that belong to organizations having organizationName - ) - ) - ); - orgsFiscalCodes.forEach(ofc => acc.add(ofc)); - } - return acc; - } - ) - ); - }, new Set()) - ), - O.fold( - () => [], - s => Array.from(s) - ) - ); - return Object.keys(orgs).filter( - fiscalCode => - organizationsWithSameNames && - organizationsWithSameNames.indexOf(fiscalCode) === -1 - ); - }) - ); - - return getServices( - services, - organizations, - undefined, - O.toUndefined(notSelectedOrganizations) - ); - } -); - -/** - * Get the sum of selected local services + national that are not yet marked as read - */ - -export const servicesBadgeValueSelector = createSelector( - [ - nationalServicesSectionsSelector, - selectedLocalServicesSectionsSelector, - readServicesByIdSelector, - isFirstVisibleServiceLoadCompletedSelector - ], - ( - nationalService, - localService, - readServicesById, - isFirstVisibleServiceLoadCompleted - ) => { - if (isFirstVisibleServiceLoadCompleted) { - const servicesSet: Set = new Set([ - ...nationalService, - ...localService - ]); - return [...servicesSet].reduce( - (acc: number, service: ServicesSectionState) => { - const servicesNotRead = service.data.filter( - data => - pot.isSome(data) && - readServicesById[data.value.service_id] === undefined - ).length; - // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - return acc + servicesNotRead; - }, - 0 - ); - } - return 0; - } -); - -export default reducer; diff --git a/ts/store/reducers/entities/services/readStateByServiceId.ts b/ts/store/reducers/entities/services/readStateByServiceId.ts deleted file mode 100644 index b6bf43d7481..00000000000 --- a/ts/store/reducers/entities/services/readStateByServiceId.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { getType } from "typesafe-actions"; -import _ from "lodash"; -import { - loadServiceDetailNotFound, - markServiceAsRead, - showServiceDetails -} from "../../../actions/services"; -import { Action } from "../../../actions/types"; -import { GlobalState } from "../../types"; -import { differentProfileLoggedIn } from "../../../actions/crossSessions"; - -export type ReadStateByServicesId = Readonly<{ - [key: string]: boolean | undefined; -}>; - -const INITIAL_STATE: ReadStateByServicesId = {}; - -// Selectors -export const readServicesByIdSelector = ( - state: GlobalState -): ReadStateByServicesId => state.entities.services.readState; - -// Reducer -export function readServicesByIdReducer( - state = INITIAL_STATE, - action: Action -): ReadStateByServicesId { - switch (action.type) { - case getType(showServiceDetails): - // add the service to the read list - return { - ...state, - [action.payload.service_id]: true - }; - - case getType(markServiceAsRead): - return { - ...state, - [action.payload]: true - }; - case getType(loadServiceDetailNotFound): - return _.omit(state, [action.payload]); - // reset reading state if current profile is different from the previous one - case getType(differentProfileLoggedIn): - return INITIAL_STATE; - - default: - return state; - } -} - -export default readServicesByIdReducer; diff --git a/ts/store/reducers/entities/services/servicesByOrganizationFiscalCode.ts b/ts/store/reducers/entities/services/servicesByOrganizationFiscalCode.ts deleted file mode 100644 index 417942c5a18..00000000000 --- a/ts/store/reducers/entities/services/servicesByOrganizationFiscalCode.ts +++ /dev/null @@ -1,95 +0,0 @@ -/** - * A reducer to store the serviceIds by organization fiscal codes - */ - -import { pipe } from "fp-ts/lib/function"; -import * as O from "fp-ts/lib/Option"; -import { getType } from "typesafe-actions"; - -import { ServiceId } from "../../../../../definitions/backend/ServiceId"; -import { logoutSuccess, sessionExpired } from "../../../actions/authentication"; -import { loadServiceDetail } from "../../../../features/services/details/store/actions/details"; -import { removeServiceTuples } from "../../../actions/services"; -import { Action } from "../../../actions/types"; - -/** - * Maps organization fiscal code to serviceId - */ -export type ServiceIdsByOrganizationFiscalCodeState = Readonly<{ - [key: string]: ReadonlyArray | undefined; -}>; - -const INITIAL_STATE: ServiceIdsByOrganizationFiscalCodeState = {}; - -export function serviceIdsByOrganizationFiscalCodeReducer( - state: ServiceIdsByOrganizationFiscalCodeState = INITIAL_STATE, - action: Action -): ServiceIdsByOrganizationFiscalCodeState { - switch (action.type) { - case getType(loadServiceDetail.success): - const { organization_fiscal_code, service_id } = action.payload; - // get the current serviceIds for the organization fiscal code - const servicesForOrganization = state[organization_fiscal_code]; - - if ( - servicesForOrganization !== undefined && - servicesForOrganization.indexOf(service_id) >= 0 - ) { - // the service is already in the organization - return state; - } - - // add the service to the organization - const updatedServicesForOrganization = - servicesForOrganization === undefined - ? [service_id] - : [...servicesForOrganization, service_id]; - - return { - ...state, - [organization_fiscal_code]: updatedServicesForOrganization - }; - - case getType(logoutSuccess): - case getType(sessionExpired): - return INITIAL_STATE; - - case getType(removeServiceTuples): { - const serviceTuples = action.payload; - - // Remove service id from the array keyed by organizationFiscalCode - const stateUpdate = - serviceTuples.reduce( - (accumulator, tuple) => { - const serviceId = tuple.e1; - const organizationFiscalCode = tuple.e2; - const ids = pipe( - organizationFiscalCode, - O.fromNullable, - O.map(_ => - accumulator[_] !== undefined ? accumulator[_] : state[_] - ), - O.toNullable - ); - if (organizationFiscalCode && ids) { - const filteredIds = ids.filter(id => id !== serviceId); - return { - ...accumulator, - [organizationFiscalCode]: filteredIds - }; - } - return accumulator; - }, - {} - ); - - return { - ...state, - ...stateUpdate - }; - } - - default: - return state; - } -} diff --git a/ts/store/reducers/entities/services/transformers.ts b/ts/store/reducers/entities/services/transformers.ts index e8565fa1b99..333fd0790d6 100644 --- a/ts/store/reducers/entities/services/transformers.ts +++ b/ts/store/reducers/entities/services/transformers.ts @@ -1,5 +1,5 @@ import { ServicePublic } from "../../../../../definitions/backend/ServicePublic"; -import { logosForService } from "../../../../utils/services"; +import { logosForService } from "../../../../features/services/common/utils"; import { UIService } from "./types"; diff --git a/ts/store/reducers/entities/services/visibleServices.ts b/ts/store/reducers/entities/services/visibleServices.ts deleted file mode 100644 index 7a6dbe82c02..00000000000 --- a/ts/store/reducers/entities/services/visibleServices.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** - * A reducer to store the services normalized by id - * It only manages SUCCESS actions because all UI state properties (like * loading/error) - * are managed by different global reducers. - */ -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { getType } from "typesafe-actions"; - -import { PaginatedServiceTupleCollection } from "../../../../../definitions/backend/PaginatedServiceTupleCollection"; -import { logoutSuccess, sessionExpired } from "../../../actions/authentication"; -import { loadVisibleServices } from "../../../actions/services"; -import { Action } from "../../../actions/types"; -import { GlobalState } from "../../types"; - -export type VisibleServicesState = pot.Pot< - PaginatedServiceTupleCollection["items"], - Error ->; - -const INITIAL_STATE: VisibleServicesState = pot.none; - -export const visibleServicesReducer = ( - state: VisibleServicesState = INITIAL_STATE, - action: Action -): VisibleServicesState => { - switch (action.type) { - case getType(loadVisibleServices.request): - return pot.toLoading(state); - - case getType(loadVisibleServices.success): - return pot.some(action.payload); - - case getType(loadVisibleServices.failure): - return pot.toError(state, action.payload); - - case getType(logoutSuccess): - case getType(sessionExpired): - return INITIAL_STATE; - - default: - return state; - } -}; - -// Selectors -export const visibleServicesSelector = ( - state: GlobalState -): VisibleServicesState => state.entities.services.visible; diff --git a/ts/store/reducers/index.ts b/ts/store/reducers/index.ts index 32b00065550..2476e37f967 100644 --- a/ts/store/reducers/index.ts +++ b/ts/store/reducers/index.ts @@ -212,7 +212,6 @@ export function createRootReducer( crossSessions: state.crossSessions, // data should be kept across multiple sessions entities: { - services: state.entities.services, organizations: state.entities.organizations, messagesStatus: state.entities.messagesStatus, paymentByRptId: state.entities.paymentByRptId, diff --git a/ts/store/reducers/search.ts b/ts/store/reducers/search.ts index 4ef9fa8beb9..8d7ee737013 100644 --- a/ts/store/reducers/search.ts +++ b/ts/store/reducers/search.ts @@ -7,7 +7,6 @@ import * as O from "fp-ts/lib/Option"; import { disableSearch, searchMessagesEnabled, - searchServicesEnabled, updateSearchText } from "../actions/search"; import { Action } from "../actions/types"; @@ -17,14 +16,12 @@ export type SearchState = Readonly<{ searchText: O.Option; isSearchEnabled: boolean; isSearchMessagesEnabled: boolean; - isSearchServicesEnabled: boolean; }>; const INITIAL_STATE: SearchState = { searchText: O.none, isSearchEnabled: false, - isSearchMessagesEnabled: false, - isSearchServicesEnabled: false + isSearchMessagesEnabled: false }; // Selectors @@ -37,9 +34,6 @@ export const isSearchEnabledSelector = (state: GlobalState): boolean => export const isSearchMessagesEnabledSelector = (state: GlobalState): boolean => state.search.isSearchMessagesEnabled; -export const isSearchServicesEnabledSelector = (state: GlobalState): boolean => - state.search.isSearchServicesEnabled; - const reducer = ( state: SearchState = INITIAL_STATE, action: Action @@ -52,13 +46,6 @@ const reducer = ( isSearchMessagesEnabled: action.payload }; - case getType(searchServicesEnabled): - return { - ...state, - isSearchEnabled: action.payload, - isSearchServicesEnabled: action.payload - }; - case getType(updateSearchText): return { ...state, searchText: action.payload }; diff --git a/ts/types/ServicesWebviewParams.ts b/ts/types/ServicesWebviewParams.ts deleted file mode 100644 index be8cee5c0bf..00000000000 --- a/ts/types/ServicesWebviewParams.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * this type models an object that represents the params needed by the ServicesWebviewScreen to work - * see https://www.pivotaltracker.com/story/show/174801117 - */ -import * as t from "io-ts"; -import { ServiceId } from "../../definitions/backend/ServiceId"; - -export const ServicesWebviewParams = t.interface({ - serviceId: ServiceId, - url: t.string -}); - -export type ServicesWebviewParams = t.TypeOf; diff --git a/ts/types/WebviewMessage.ts b/ts/types/WebviewMessage.ts index 207f7eabdea..fc61c8ab8e6 100644 --- a/ts/types/WebviewMessage.ts +++ b/ts/types/WebviewMessage.ts @@ -1,5 +1,5 @@ /** - * these models describe the incoming data sent from web pages that include app injected JS (see RegionServiceWebView) + * these models describe the incoming data sent from web pages that include app injected JS */ import * as t from "io-ts"; diff --git a/ts/types/__tests__/ServicesWebviewParams.test.ts b/ts/types/__tests__/ServicesWebviewParams.test.ts deleted file mode 100644 index 79a90a837d0..00000000000 --- a/ts/types/__tests__/ServicesWebviewParams.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -import * as E from "fp-ts/lib/Either"; -import { ServicesWebviewParams } from "../ServicesWebviewParams"; - -const validParams = { - serviceId: "service_id", - url: "http://google.com" -}; - -const invalidParams1 = { - url: "http://google.com" -}; - -const invalidParams2 = { - serviceId: "service_id" -}; - -const invalidParams3 = { - serviceId: "", - url: "http://google.com" -}; - -describe("WebviewMessage", () => { - it("Should recognize a valid payload for Params", () => { - expect(E.isRight(ServicesWebviewParams.decode(validParams))).toBeTruthy(); - }); - - it("Should recognize an invalid payload for Params", () => { - expect(E.isRight(ServicesWebviewParams.decode(invalidParams1))).toBeFalsy(); - }); - - it("Should recognize an invalid payload for Params", () => { - expect(E.isRight(ServicesWebviewParams.decode(invalidParams2))).toBeFalsy(); - }); - - it("Should recognize an invalid payload for Params", () => { - expect(E.isRight(ServicesWebviewParams.decode(invalidParams3))).toBeFalsy(); - }); -}); diff --git a/ts/utils/analytics.ts b/ts/utils/analytics.ts index 0e1e6afeb3a..f70ef947016 100644 --- a/ts/utils/analytics.ts +++ b/ts/utils/analytics.ts @@ -10,7 +10,6 @@ import EUCOVIDCERT_ROUTES from "../features/euCovidCert/navigation/routes"; import { euCovidCertificateEnabled } from "../config"; import { mixpanelTrack } from "../mixpanel"; import { isLoginUtilsError } from "../features/lollipop/utils/login"; -import { ServicesDetailLoadTrack } from "../sagas/startup/loadServiceDetailRequestHandler"; const blackListRoutes: ReadonlyArray = []; @@ -93,20 +92,6 @@ export const buildEventProperties = ( flow }); -// Services related events - -export function trackServiceDetailLoadingStatistics( - trackingStats: ServicesDetailLoadTrack -) { - void mixpanelTrack("SERVICES_DETAIL_LOADING_STATS", { - ...trackingStats, - // drop servicesId since it is not serialized in mixpanel and it could be an extra overhead on sending - servicesId: undefined - }); -} - -// End of Services related events - // Lollipop events export function trackLollipopKeyGenerationSuccess(keyType?: string) { void mixpanelTrack("LOLLIPOP_KEY_GENERATION_SUCCESS", { diff --git a/ts/utils/organizations.ts b/ts/utils/organizations.ts deleted file mode 100644 index 614702c096c..00000000000 --- a/ts/utils/organizations.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Generic utilities for organizations - */ -import { contentRepoUrl } from "../config"; - -/** - * This is a partial duplication of ./services/logosForService. - * TODO: remove it in favour of the generic one - * - * @deprecated - * @param orgFiscalCode - * @param logosRepoUrl - */ -export function getLogoForOrganization( - orgFiscalCode: string, - logosRepoUrl: string = `${contentRepoUrl}/logos` -) { - return [`organizations/${orgFiscalCode.replace(/^0+/, "")}`].map(u => ({ - uri: `${logosRepoUrl}/${u}.png` - })); -} diff --git a/ts/utils/profile.ts b/ts/utils/profile.ts index 166d4caee0e..3ec42c92ba4 100644 --- a/ts/utils/profile.ts +++ b/ts/utils/profile.ts @@ -1,12 +1,6 @@ import * as pot from "@pagopa/ts-commons/lib/pot"; -import { pipe } from "fp-ts/lib/function"; -import * as O from "fp-ts/lib/Option"; -import { BlockedInboxOrChannels } from "../../definitions/backend/BlockedInboxOrChannels"; import { FiscalCode } from "../../definitions/backend/FiscalCode"; -import { InitializedProfile } from "../../definitions/backend/InitializedProfile"; -import { ServiceId } from "../../definitions/backend/ServiceId"; import { Municipality } from "../../definitions/content/Municipality"; -import { ProfileState } from "../store/reducers/profile"; import { pad } from "./dates"; type GenderType = "M" | "F" | undefined; @@ -103,142 +97,3 @@ export interface EnabledChannels { push: boolean; can_access_message_read_status: boolean; } - -const INBOX_CHANNEL = "INBOX"; -const EMAIL_CHANNEL = "EMAIL"; -const PUSH_CHANNEL = "WEBHOOK"; -const SEND_READ_MESSAGE_STATUS_CHANNEL = "SEND_READ_MESSAGE_STATUS_CHANNEL"; - -export function getChannelsforServicesList( - servicesId: ReadonlyArray, - profile: ProfileState -): BlockedInboxOrChannels { - const profileBlockedChannels = pot.getOrElse( - pot.mapNullable(profile, up => up.blocked_inbox_or_channels), - {} as BlockedInboxOrChannels - ); - - return servicesId.reduce( - (acc, serviceId) => ({ - ...acc, - [serviceId]: profileBlockedChannels[serviceId] || [] - }), - {} as BlockedInboxOrChannels - ); -} - -/** - * Provide new BlockedInboxOrChannels object to disable - * or enable (if enableListedServices is true) - * a list of services (listed as servicesId). - * If not declared, the enabled/disabled channel is the INBOX, - * otherwise it is updated the channel expressed as channelOfInterest - */ -export function getProfileChannelsforServicesList( - servicesId: ReadonlyArray, - profile: ProfileState, - enableListedServices: boolean, - channelOfInterest: string = INBOX_CHANNEL -): BlockedInboxOrChannels { - const profileBlockedChannels = pot.getOrElse( - pot.mapNullable( - profile, - userProfile => userProfile.blocked_inbox_or_channels - ), - {} as BlockedInboxOrChannels - ); - - servicesId.forEach(id => { - const channels = - Object.keys(profileBlockedChannels).indexOf(id) !== -1 - ? profileBlockedChannels[id] - : []; - - const updatedBlockedChannels = - channels.indexOf(channelOfInterest) === -1 - ? enableListedServices - ? channels - : channels.concat(channelOfInterest) - : enableListedServices - ? channels.filter(item => item !== channelOfInterest) - : channels; - - if (updatedBlockedChannels.length !== 0) { - // eslint-disable-next-line - profileBlockedChannels[id] = updatedBlockedChannels; - } else { - // eslint-disable-next-line - delete profileBlockedChannels[id]; - } - }); - - return profileBlockedChannels; -} - -/** - * Finds out which channels are enabled in the profile for the provided service - */ -export function getEnabledChannelsForService( - potProfile: ProfileState, - serviceId: ServiceId -): EnabledChannels { - return pipe( - pot.toOption(potProfile), - O.chainNullableK(profile => - InitializedProfile.is(profile) ? profile.blocked_inbox_or_channels : null - ), - O.chainNullableK(blockedChannels => blockedChannels[serviceId]), - O.map(_ => ({ - inbox: _.indexOf(INBOX_CHANNEL) === -1, - email: _.indexOf(EMAIL_CHANNEL) === -1, - push: _.indexOf(PUSH_CHANNEL) === -1, - can_access_message_read_status: - _.indexOf(SEND_READ_MESSAGE_STATUS_CHANNEL) === -1 - })), - O.getOrElseW(() => ({ - inbox: true, - email: true, - push: true, - can_access_message_read_status: true - })) - ); -} - -/** - * Returns a function that generates updated blocked channels from the - * enabled channels of one service - */ -export const getBlockedChannels = - (potProfile: ProfileState, serviceId: ServiceId) => - (enabled: EnabledChannels): BlockedInboxOrChannels => { - // get the current blocked channels from the profile - const profileBlockedChannels = pot.getOrElse( - pot.mapNullable( - potProfile, - userProfile => userProfile.blocked_inbox_or_channels - ), - {} as BlockedInboxOrChannels - ); - - // compute the blocked channels array for this service - const blockedChannelsForService = [ - !enabled.inbox ? INBOX_CHANNEL : "", - !enabled.push ? PUSH_CHANNEL : "", - !enabled.email ? EMAIL_CHANNEL : "", - !enabled.can_access_message_read_status - ? SEND_READ_MESSAGE_STATUS_CHANNEL - : "" - ].filter(_ => _ !== ""); - - if (blockedChannelsForService.length === 0) { - // eslint-disable-next-line functional/immutable-data - delete profileBlockedChannels[serviceId]; - } else { - // eslint-disable-next-line functional/immutable-data - profileBlockedChannels[serviceId] = blockedChannelsForService; - } - - return { - ...profileBlockedChannels - }; - }; diff --git a/ts/utils/services.ts b/ts/utils/services.ts deleted file mode 100644 index 3dafbf24e50..00000000000 --- a/ts/utils/services.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Generic utilities for services - */ - -import * as pot from "@pagopa/ts-commons/lib/pot"; -import { ImageURISource } from "react-native"; -import { ServicePublic } from "../../definitions/backend/ServicePublic"; -import { contentRepoUrl } from "../config"; -import { VisibleServicesState } from "../store/reducers/entities/services/visibleServices"; -import { isTextIncludedCaseInsensitive } from "./strings"; - -/** - * Returns an array of ImageURISource pointing to possible logos for the - * provided service. - * - * The returned array is suitable for being used with the MultiImage component. - * The arrays will have first the service logo, then the organization logo. - */ -export function logosForService( - service: ServicePublic, - logosRepoUrl: string = `${contentRepoUrl}/logos` -): ReadonlyArray { - return [ - `services/${service.service_id.toLowerCase()}`, - `organizations/${service.organization_fiscal_code.replace(/^0+/, "")}` - ].map(u => ({ - uri: `${logosRepoUrl}/${u}.png` - })); -} - -export function serviceContainsText( - service: ServicePublic, - searchText: string -) { - return ( - isTextIncludedCaseInsensitive(service.department_name, searchText) || - isTextIncludedCaseInsensitive(service.organization_name, searchText) || - isTextIncludedCaseInsensitive(service.service_name, searchText) - ); -} - -// Return true if the given service is available (visible) -export const isVisibleService = ( - visibleServices: VisibleServicesState, - potService: pot.Pot -) => { - const service = pot.toUndefined(potService); - return ( - service && - pot.getOrElse( - pot.map(visibleServices, services => - services.some(item => service.service_id === item.service_id) - ), - false - ) - ); -};