From d036243d64f22fe4aad3e4df8875a4375ac20969 Mon Sep 17 00:00:00 2001 From: Taso Date: Tue, 8 Jun 2021 12:07:47 -0400 Subject: [PATCH 1/8] refactor(contacts): Refactor contacts to efficient data fetching --- phone/src/Phone.tsx | 2 - .../apps/contacts/components/ContactsApp.tsx | 39 +------- .../contacts/components/List/ContactList.tsx | 56 +++++------- .../components/List/SearchContacts.tsx | 18 +++- .../contacts/components/views/ContactInfo.tsx | 72 ++++++++++++--- phone/src/apps/contacts/hooks/state.ts | 58 ++++++++++-- .../apps/contacts/hooks/useContactActions.ts | 91 +++++++++++++++++++ phone/src/apps/contacts/hooks/useContacts.ts | 55 ----------- .../apps/contacts/hooks/useContactsService.ts | 24 ----- .../contacts/hooks/useFilteredContacts.ts | 12 --- phone/src/apps/contacts/hooks/useModal.ts | 12 --- phone/src/apps/contacts/utils/constants.ts | 24 +++++ .../src/apps/dialer/components/DialerApp.tsx | 11 ++- .../dialer/components/views/DialerHistory.tsx | 4 +- .../components/form/NewMessageGroupForm.tsx | 6 +- .../components/modal/MessageGroupModal.tsx | 11 ++- .../components/modal/MessageModal.tsx | 4 +- .../call/components/CallContactContainer.tsx | 4 +- phone/src/os/phone/hooks/useDebounce.ts | 16 ++++ phone/src/ui/components/LoadingSpinner.tsx | 8 ++ phone/src/utils/misc.ts | 3 + phone/yarn.lock | 16 ++-- resources/client/cl_contacts.ts | 45 ++------- resources/client/cl_utils.ts | 2 +- .../server/contacts/contacts.controller.ts | 52 ++++++----- resources/server/contacts/contacts.db.ts | 26 ++++-- .../server/contacts/contacts.interfaces.ts | 8 -- resources/server/contacts/contacts.service.ts | 86 +++++++----------- typings/contact.ts | 4 + 29 files changed, 417 insertions(+), 352 deletions(-) create mode 100644 phone/src/apps/contacts/hooks/useContactActions.ts delete mode 100644 phone/src/apps/contacts/hooks/useContacts.ts delete mode 100644 phone/src/apps/contacts/hooks/useContactsService.ts delete mode 100644 phone/src/apps/contacts/hooks/useFilteredContacts.ts delete mode 100644 phone/src/apps/contacts/hooks/useModal.ts create mode 100644 phone/src/apps/contacts/utils/constants.ts create mode 100644 phone/src/os/phone/hooks/useDebounce.ts create mode 100644 phone/src/ui/components/LoadingSpinner.tsx create mode 100644 phone/src/utils/misc.ts delete mode 100644 resources/server/contacts/contacts.interfaces.ts diff --git a/phone/src/Phone.tsx b/phone/src/Phone.tsx index bde796a..bcdb2c0 100644 --- a/phone/src/Phone.tsx +++ b/phone/src/Phone.tsx @@ -10,7 +10,6 @@ import { useSimcardService } from './os/simcard/hooks/useSimcardService'; import { usePhoneService } from './os/phone/hooks/usePhoneService'; import { useApps } from './os/apps/hooks/useApps'; import { useNuiRequest } from 'fivem-nui-react-lib'; -import { useContactsService } from './apps/contacts/hooks/useContactsService'; import { useTwitterService } from './apps/twitter/hooks/useTwitterService'; import { useMatchService } from './apps/match/hooks/useMatchService'; import { useMarketplaceService } from './apps/marketplace/hooks/useMarketplaceService'; @@ -71,7 +70,6 @@ function Phone() { useKeyboardService(); usePhoneService(); useSimcardService(); - useContactsService(); useTwitterService(); useMatchService(); useMarketplaceService(); diff --git a/phone/src/apps/contacts/components/ContactsApp.tsx b/phone/src/apps/contacts/components/ContactsApp.tsx index bc4f685..74e72fc 100644 --- a/phone/src/apps/contacts/components/ContactsApp.tsx +++ b/phone/src/apps/contacts/components/ContactsApp.tsx @@ -5,11 +5,11 @@ import { AppContent } from '../../../ui/components/AppContent'; import { useApp } from '../../../os/apps/hooks/useApps'; import InjectDebugData from '../../../os/debug/InjectDebugData'; import { Route } from 'react-router-dom'; - import ContactsInfoPage from './views/ContactInfo'; import { ContactPage } from './views/ContactsPage'; import { ContactsThemeProvider } from '../providers/ContactsThemeProvider'; import { ContactEvents } from '../../../../../typings/contact'; +import { LoadingSpinner } from '../../../ui/components/LoadingSpinner'; export const ContactsApp = () => { const contacts = useApp('CONTACTS'); @@ -19,41 +19,12 @@ export const ContactsApp = () => { - - + }> + + + ); }; - -InjectDebugData([ - { - app: 'CONTACTS', - method: ContactEvents.SEND_CONTACTS, - data: [ - { - id: 1, - display: 'Ruqen', - number: '555-15196', - }, - { - id: 2, - display: 'Taso', - number: '215-8139', - avatar: 'http://i.tasoagc.dev/i9Ig', - }, - { - id: 3, - display: 'Chip', - number: '603-275-8373', - avatar: 'http://i.tasoagc.dev/2QYV', - }, - { - id: 4, - display: 'Kidz', - number: '444-4444', - }, - ], - }, -]); diff --git a/phone/src/apps/contacts/components/List/ContactList.tsx b/phone/src/apps/contacts/components/List/ContactList.tsx index e376c45..d250c2c 100644 --- a/phone/src/apps/contacts/components/List/ContactList.tsx +++ b/phone/src/apps/contacts/components/List/ContactList.tsx @@ -1,24 +1,21 @@ import React from 'react'; import ListItemText from '@material-ui/core/ListItemText'; import { Button, ListItemAvatar, Avatar as MuiAvatar, List, ListItem } from '@material-ui/core'; -import { useFilteredContacts } from '../../hooks/useFilteredContacts'; import PhoneIcon from '@material-ui/icons/Phone'; import ChatIcon from '@material-ui/icons/Chat'; import MoreVertIcon from '@material-ui/icons/MoreVert'; -import { useContacts } from '../../hooks/useContacts'; import { SearchContacts } from './SearchContacts'; import { useHistory } from 'react-router-dom'; import LogDebugEvent from '../../../../os/debug/LogDebugEvents'; import { CallEvents } from '../../../../../../typings/call'; import { useNuiRequest } from 'fivem-nui-react-lib'; +import { useFilteredContacts } from '../../hooks/state'; export const ContactList = () => { - const { filteredContacts } = useFilteredContacts(); + const filteredContacts = useFilteredContacts(); const history = useHistory(); const Nui = useNuiRequest(); - const { contacts } = useContacts(); - const openContactInfo = (contactId: number) => { history.push(`/contacts/${contactId}`); }; @@ -43,38 +40,31 @@ export const ContactList = () => { history.push(`/messages/new/${phoneNumber}`); }; - const filteredRegEx = new RegExp(filteredContacts, 'gi'); - return ( <> - {contacts - .filter( - (contact) => - contact.display.match(filteredRegEx) || contact.number.match(filteredRegEx), - ) - .map((contact) => ( - - - {contact.avatar ? ( - - ) : ( - {contact.display.slice(0, 1).toUpperCase()} - )} - - - - - - - ))} + {filteredContacts.map((contact) => ( + + + {contact.avatar ? ( + + ) : ( + {contact.display.slice(0, 1).toUpperCase()} + )} + + + + + + + ))} ); diff --git a/phone/src/apps/contacts/components/List/SearchContacts.tsx b/phone/src/apps/contacts/components/List/SearchContacts.tsx index dc6be54..4b3f3e3 100644 --- a/phone/src/apps/contacts/components/List/SearchContacts.tsx +++ b/phone/src/apps/contacts/components/List/SearchContacts.tsx @@ -1,21 +1,29 @@ -import React from 'react'; +import React, { useEffect, useState } from 'react'; import { Box } from '@material-ui/core'; import { useTranslation } from 'react-i18next'; -import { useFilteredContacts } from '../../hooks/useFilteredContacts'; import { SearchField } from '../../../../ui/components/SearchField'; +import { useDebounce } from '../../../../os/phone/hooks/useDebounce'; +import { useSetContactFilterInput } from '../../hooks/state'; export const SearchContacts = () => { - const { setFilteredContacts, filteredContacts } = useFilteredContacts(); const { t } = useTranslation(); + const setFilterVal = useSetContactFilterInput(); + const [inputVal, setInputVal] = useState(''); + + const debouncedVal = useDebounce(inputVal, 500); + + useEffect(() => { + setFilterVal(debouncedVal); + }, [debouncedVal, setFilterVal]); return ( setFilteredContacts(e.target.value)} + onChange={(e) => setInputVal(e.target.value)} placeholder={t('APPS_CONTACT_PLACEHOLDER_SEARCH_CONTACTS')} - value={filteredContacts} + value={inputVal} /> ); diff --git a/phone/src/apps/contacts/components/views/ContactInfo.tsx b/phone/src/apps/contacts/components/views/ContactInfo.tsx index e877857..cce1ddf 100644 --- a/phone/src/apps/contacts/components/views/ContactInfo.tsx +++ b/phone/src/apps/contacts/components/views/ContactInfo.tsx @@ -3,13 +3,15 @@ import { Avatar as MuiAvatar, Box, Button, Paper } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; import { useTranslation } from 'react-i18next'; import { useHistory, useParams } from 'react-router-dom'; -import { useContacts } from '../../hooks/useContacts'; -import { useNuiRequest } from 'fivem-nui-react-lib'; +import { useContactActions } from '../../hooks/useContactActions'; import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import LogDebugEvent from '../../../../os/debug/LogDebugEvents'; import { useQueryParams } from '../../../../common/hooks/useQueryParams'; -import { ContactEvents } from '../../../../../../typings/contact'; +import { Contact, ContactEvents } from '../../../../../../typings/contact'; import { TextField } from '../../../../ui/components/Input'; +import { fetchNui } from '../../../../utils/fetchNui'; +import { ServerPromiseResp } from '../../../../../../typings/common'; +import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; interface ContactInfoRouteParams { mode: string; @@ -49,11 +51,12 @@ const useStyles = makeStyles({ }); const ContactsInfoPage = () => { - const Nui = useNuiRequest(); const classes = useStyles(); const history = useHistory(); - const { getContact } = useContacts(); + const { getContact, addContact, updateContact, deleteContact } = useContactActions(); + + const { addAlert } = useSnackbar(); const { id } = useParams(); const { addNumber, referal } = useQueryParams({ @@ -81,12 +84,27 @@ const ContactsInfoPage = () => { data: contact, level: 2, }); - Nui.send(ContactEvents.ADD_CONTACT, { + fetchNui>(ContactEvents.ADD_CONTACT, { display: name, number, avatar, + }).then((serverResp) => { + if (serverResp.status !== 'ok') { + return addAlert({ + message: t('APPS_CONTACT_ADD_FAILED'), + type: 'error', + }); + } + + // Sanity checks maybe? + + addContact(serverResp.data); + addAlert({ + message: t('APPS_CONTACT_ADD_SUCCESS'), + type: 'error', + }); + history.replace(referal); }); - history.replace(referal); }; const handleContactSave = () => { @@ -95,13 +113,33 @@ const ContactsInfoPage = () => { data: contact, level: 2, }); - Nui.send(ContactEvents.UPDATE_CONTACT, { + fetchNui(ContactEvents.UPDATE_CONTACT, { id: contact.id, display: name, number, avatar, + }).then((resp) => { + if (resp.status !== 'ok') { + return addAlert({ + message: t('APPS_CONTACT_UPDATE_FAILED'), + type: 'error', + }); + } + + updateContact({ + id: contact.id, + display: name, + number, + avatar, + }); + + addAlert({ + message: t('APPS_CONTACT_UPDATE_SUCCESS'), + type: 'success', + }); + + history.goBack(); }); - history.goBack(); }; const handleContactDelete = () => { @@ -110,8 +148,20 @@ const ContactsInfoPage = () => { data: contact, level: 2, }); - Nui.send(ContactEvents.DELETE_CONTACT, contact.id); - history.goBack(); + fetchNui(ContactEvents.DELETE_CONTACT, { id: contact.id }).then((resp) => { + if (resp.status !== 'ok') { + return addAlert({ + message: t('APPS_CONTACT_DELETE_FAILED'), + type: 'error', + }); + } + history.goBack(); + deleteContact(contact.id); + addAlert({ + message: t('APPS_CONTACT_DELETE_SUCCESS'), + type: 'error', + }); + }); }; return ( diff --git a/phone/src/apps/contacts/hooks/state.ts b/phone/src/apps/contacts/hooks/state.ts index 1483da9..58079dc 100644 --- a/phone/src/apps/contacts/hooks/state.ts +++ b/phone/src/apps/contacts/hooks/state.ts @@ -1,17 +1,57 @@ -import { atom } from 'recoil'; -import { Contact } from '../../../../../typings/contact'; +import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'; +import { Contact, ContactEvents } from '../../../../../typings/contact'; +import { fetchNui } from '../../../utils/fetchNui'; +import { ServerPromiseResp } from '../../../../../typings/common'; +import { isEnvBrowser } from '../../../utils/misc'; +import LogDebugEvent from '../../../os/debug/LogDebugEvents'; +import { BrowserContactsState } from '../utils/constants'; export const contactsState = { contacts: atom({ key: 'contactsList', - default: [], + default: selector({ + key: 'contactsListDefault', + get: async () => { + try { + const resp = await fetchNui>(ContactEvents.GET_CONTACTS); + LogDebugEvent({ action: 'ContactsFetched', data: resp.data }); + return resp.data; + } catch (e) { + if (isEnvBrowser()) { + return BrowserContactsState; + } + console.error(e); + return []; + } + }, + }), }), - showModal: atom({ - key: 'showModal', - default: false, - }), - filterContacts: atom({ - key: 'filterContacts', + filterInput: atom({ + key: 'filterInput', default: '', }), + filteredContacts: selector({ + key: 'filteredContacts', + get: ({ get }) => { + const filterInputVal: string = get(contactsState.filterInput); + const contacts: Contact[] = get(contactsState.contacts); + + if (!filterInputVal) return contacts; + + const regExp = new RegExp(filterInputVal, 'gi'); + + return contacts.filter( + (contact) => contact.display.match(regExp) || contact.number.match(regExp), + ); + }, + }), }; + +export const useSetContacts = () => useSetRecoilState(contactsState.contacts); +export const useContacts = () => useRecoilState(contactsState.contacts); +export const useContactsValue = () => useRecoilValue(contactsState.contacts); + +export const useFilteredContacts = () => useRecoilValue(contactsState.filteredContacts); + +export const useContactFilterInput = () => useRecoilState(contactsState.filterInput); +export const useSetContactFilterInput = () => useSetRecoilState(contactsState.filterInput); diff --git a/phone/src/apps/contacts/hooks/useContactActions.ts b/phone/src/apps/contacts/hooks/useContactActions.ts new file mode 100644 index 0000000..8b6a974 --- /dev/null +++ b/phone/src/apps/contacts/hooks/useContactActions.ts @@ -0,0 +1,91 @@ +import { useContacts } from './state'; + +import { Contact } from '../../../../../typings/contact'; +import { useCallback } from 'react'; + +interface UseContactsValue { + getDisplayByNumber: (number: string) => string; + getContactByNumber: (number: string) => Contact | null; + getContact: (id: number) => Contact | null; + getPictureByNumber: (number: string) => string | null; + deleteContact: (id: number) => void; + addContact: (contact: Contact) => void; + updateContact: (contact: Contact) => void; +} + +export const useContactActions = (): UseContactsValue => { + const [contacts, setContacts] = useContacts(); + + const getDisplayByNumber = useCallback( + (number: string) => { + const found = contacts.find((contact) => contact.number === number); + return found ? found.display : number; + }, + [contacts], + ); + + const getPictureByNumber = useCallback( + (number: string) => { + const found = contacts.find((contact) => contact.number === number); + return found ? found.avatar : null; + }, + [contacts], + ); + + const getContactByNumber = useCallback( + (number: string): Contact | null => { + for (const contact of contacts) { + if (contact.number === number) return contact; + } + return null; + }, + [contacts], + ); + + const getContact = useCallback( + (id: number): Contact | null => { + for (const contact of contacts) { + if (contact.id === id) return contact; + } + return null; + }, + [contacts], + ); + + const deleteContact = useCallback( + (id: number): void => { + const contactIndex = contacts.findIndex((contact) => contact.id === id); + const newContacts = [...contacts].slice(contactIndex); + setContacts(newContacts); + }, + [contacts, setContacts], + ); + + const addContact = useCallback( + (contact: Contact) => { + const newContactState = [...contacts, contact]; + setContacts(newContactState); + }, + [contacts, setContacts], + ); + + const updateContact = useCallback( + (updatedContact: Contact) => { + const targetContactIndex = contacts.findIndex((contact) => contact.id === updatedContact.id); + const newContactsArray = [...contacts]; + newContactsArray[targetContactIndex] = updatedContact; + setContacts(newContactsArray); + }, + [contacts, setContacts], + ); + + return { + getDisplayByNumber, + getContact, + getContactByNumber, + getPictureByNumber, + deleteContact, + updateContact, + addContact, + }; +}; diff --git a/phone/src/apps/contacts/hooks/useContacts.ts b/phone/src/apps/contacts/hooks/useContacts.ts deleted file mode 100644 index e1381a6..0000000 --- a/phone/src/apps/contacts/hooks/useContacts.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { useRecoilValue } from 'recoil'; -import { contactsState } from './state'; - -import { Contact } from '../../../../../typings/contact'; -import { useCallback } from 'react'; - -interface IUseContacts { - contacts: Contact[]; - getDisplayByNumber: (number: string) => string; - getContactByNumber: (number: string) => Contact | null; - getContact: (id: number) => Contact | null; - getPictureByNumber: (number: string) => string | null; -} - -export const useContacts = (): IUseContacts => { - const contacts = useRecoilValue(contactsState.contacts); - - const getDisplayByNumber = useCallback( - (number: string) => { - const found = contacts.find((contact) => contact.number === number); - return found ? found.display : number; - }, - [contacts], - ); - - const getPictureByNumber = useCallback( - (number: string) => { - const found = contacts.find((contact) => contact.number === number); - return found ? found.avatar : null; - }, - [contacts], - ); - - const getContactByNumber = useCallback( - (number: string): Contact | null => { - for (const contact of contacts) { - if (contact.number === number) return contact; - } - return null; - }, - [contacts], - ); - - const getContact = useCallback( - (id: number): Contact | null => { - for (const contact of contacts) { - if (contact.id === id) return contact; - } - return null; - }, - [contacts], - ); - - return { contacts, getDisplayByNumber, getContact, getContactByNumber, getPictureByNumber }; -}; diff --git a/phone/src/apps/contacts/hooks/useContactsService.ts b/phone/src/apps/contacts/hooks/useContactsService.ts deleted file mode 100644 index 721553a..0000000 --- a/phone/src/apps/contacts/hooks/useContactsService.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { useNuiEvent } from 'fivem-nui-react-lib'; -import { useSetRecoilState } from 'recoil'; -import { contactsState } from './state'; -import { useContacts } from './useContacts'; -import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar'; -import { useTranslation } from 'react-i18next'; -import { ContactEvents } from '../../../../../typings/contact'; - -export const useContactsService = () => { - const setContacts = useSetRecoilState(contactsState.contacts); - const { addAlert } = useSnackbar(); - const { t } = useTranslation(); - - const handleAddAlert = ({ message, type }: IAlert) => { - addAlert({ - message: t(`APPS_${message}`), - type, - }); - }; - - useNuiEvent('CONTACTS', ContactEvents.SEND_CONTACTS, setContacts); - useNuiEvent('CONTACTS', ContactEvents.SEND_ALERT, handleAddAlert); - return useContacts(); -}; diff --git a/phone/src/apps/contacts/hooks/useFilteredContacts.ts b/phone/src/apps/contacts/hooks/useFilteredContacts.ts deleted file mode 100644 index 75f761b..0000000 --- a/phone/src/apps/contacts/hooks/useFilteredContacts.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { useRecoilState } from 'recoil'; -import { contactsState } from './state'; - -interface FilterdContactsProps { - filteredContacts: string; - setFilteredContacts: (searchTerm: string) => void; -} - -export const useFilteredContacts = (): FilterdContactsProps => { - const [filteredContacts, setFilteredContacts] = useRecoilState(contactsState.filterContacts); - return { filteredContacts, setFilteredContacts }; -}; diff --git a/phone/src/apps/contacts/hooks/useModal.ts b/phone/src/apps/contacts/hooks/useModal.ts deleted file mode 100644 index 5591877..0000000 --- a/phone/src/apps/contacts/hooks/useModal.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { useRecoilState } from 'recoil'; -import { contactsState } from './state'; - -interface ModalProps { - showModal: boolean; - setShowModal: (show: boolean) => void; -} - -export const useModal = (): ModalProps => { - const [showModal, setShowModal] = useRecoilState(contactsState.showModal); - return { showModal, setShowModal }; -}; diff --git a/phone/src/apps/contacts/utils/constants.ts b/phone/src/apps/contacts/utils/constants.ts new file mode 100644 index 0000000..6062b18 --- /dev/null +++ b/phone/src/apps/contacts/utils/constants.ts @@ -0,0 +1,24 @@ +export const BrowserContactsState = [ + { + id: 1, + display: 'Ruqen', + number: '555-15196', + }, + { + id: 2, + display: 'Taso', + number: '215-8139', + avatar: 'http://i.tasoagc.dev/i9Ig', + }, + { + id: 3, + display: 'Chip', + number: '603-275-8373', + avatar: 'http://i.tasoagc.dev/2QYV', + }, + { + id: 4, + display: 'Kidz', + number: '444-4444', + }, +]; diff --git a/phone/src/apps/dialer/components/DialerApp.tsx b/phone/src/apps/dialer/components/DialerApp.tsx index fe6e92c..86649e2 100644 --- a/phone/src/apps/dialer/components/DialerApp.tsx +++ b/phone/src/apps/dialer/components/DialerApp.tsx @@ -12,6 +12,13 @@ import InjectDebugData from '../../../os/debug/InjectDebugData'; import { ContactList } from '../../contacts/components/List/ContactList'; import { DialerThemeProvider } from '../providers/DialerThemeProvider'; import { CallEvents } from '../../../../../typings/call'; +import { Box, CircularProgress } from '@material-ui/core'; + +const LoadingSpinner: React.FC = () => ( + + + +); export const DialerApp = () => { const history = useDialHistory(); @@ -27,7 +34,9 @@ export const DialerApp = () => { - + }> + + diff --git a/phone/src/apps/dialer/components/views/DialerHistory.tsx b/phone/src/apps/dialer/components/views/DialerHistory.tsx index e9aaba9..3b3e07c 100644 --- a/phone/src/apps/dialer/components/views/DialerHistory.tsx +++ b/phone/src/apps/dialer/components/views/DialerHistory.tsx @@ -7,7 +7,7 @@ import { List } from '../../../../ui/components/List'; import { ListItem } from '../../../../ui/components/ListItem'; import { useNuiRequest } from 'fivem-nui-react-lib'; import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; -import { useContacts } from '../../../contacts/hooks/useContacts'; +import { useContactActions } from '../../../contacts/hooks/useContactActions'; import { CallEvents, CallHistoryItem } from '../../../../../../typings/call'; import { useTranslation } from 'react-i18next'; import { Box, IconButton, ListItemIcon, ListItemText } from '@material-ui/core'; @@ -27,7 +27,7 @@ const useStyles = makeStyles((theme: Theme) => ({ export const DialerHistory = ({ calls }) => { const Nui = useNuiRequest(); const { number: myNumber } = useSimcard(); - const { getDisplayByNumber } = useContacts(); + const { getDisplayByNumber } = useContactActions(); const classes = useStyles(); diff --git a/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx b/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx index 6911c52..fe95365 100644 --- a/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx +++ b/phone/src/apps/messages/components/form/NewMessageGroupForm.tsx @@ -4,12 +4,13 @@ import { Box, Button } from '@material-ui/core'; import { useNuiRequest } from 'fivem-nui-react-lib'; import { useHistory } from 'react-router-dom'; import { Autocomplete } from '@material-ui/lab'; -import { useContacts } from '../../../contacts/hooks/useContacts'; +import { useContactActions } from '../../../contacts/hooks/useContactActions'; import { Contact } from '../../../../../../typings/contact'; import { MessageEvents } from '../../../../../../typings/messages'; import { PHONE_NUMBER_REGEX } from '../../../../../../typings/phone'; import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; import { TextField } from '../../../../ui/components/Input'; +import { useContactsValue } from '../../../contacts/hooks/state'; const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => { const Nui = useNuiRequest(); @@ -18,7 +19,8 @@ const NewMessageGroupForm = ({ phoneNumber }: { phoneNumber?: string }) => { const { addAlert } = useSnackbar(); const [participants, setParticipants] = useState([]); const [label, setLabel] = useState(''); - const { getContactByNumber, contacts } = useContacts(); + const { getContactByNumber } = useContactActions(); + const contacts = useContactsValue(); useEffect(() => { if (phoneNumber) { diff --git a/phone/src/apps/messages/components/modal/MessageGroupModal.tsx b/phone/src/apps/messages/components/modal/MessageGroupModal.tsx index de5ac1e..4cfbfc4 100644 --- a/phone/src/apps/messages/components/modal/MessageGroupModal.tsx +++ b/phone/src/apps/messages/components/modal/MessageGroupModal.tsx @@ -4,6 +4,7 @@ import ArrowBackIcon from '@material-ui/icons/ArrowBack'; import useStyles from './modal.styles'; import NewMessageGroupForm from '../form/NewMessageGroupForm'; import { useHistory, useParams } from 'react-router-dom'; +import { LoadingSpinner } from '../../../../ui/components/LoadingSpinner'; const MessageGroupModal = () => { const classes = useStyles(); @@ -16,10 +17,12 @@ const MessageGroupModal = () => { return ( - - + }> + + + ); diff --git a/phone/src/apps/messages/components/modal/MessageModal.tsx b/phone/src/apps/messages/components/modal/MessageModal.tsx index 8673ddf..5765031 100644 --- a/phone/src/apps/messages/components/modal/MessageModal.tsx +++ b/phone/src/apps/messages/components/modal/MessageModal.tsx @@ -21,7 +21,7 @@ import { useNuiRequest } from 'fivem-nui-react-lib'; import { useHistory, useLocation, useParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import Modal from '../../../../ui/components/Modal'; -import { useContacts } from '../../../contacts/hooks/useContacts'; +import { useContactActions } from '../../../contacts/hooks/useContactActions'; import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import { MessageEvents } from '../../../../../../typings/messages'; @@ -56,7 +56,7 @@ export const MessageModal = () => { const { t } = useTranslation(); const { groupId } = useParams<{ groupId: string }>(); const { messages, setMessages, activeMessageGroup, setActiveMessageGroup } = useMessages(); - const { getContactByNumber, getDisplayByNumber } = useContacts(); + const { getContactByNumber, getDisplayByNumber } = useContactActions(); const [isLoaded, setLoaded] = useState(false); diff --git a/phone/src/os/call/components/CallContactContainer.tsx b/phone/src/os/call/components/CallContactContainer.tsx index e2cd528..a1df6f5 100644 --- a/phone/src/os/call/components/CallContactContainer.tsx +++ b/phone/src/os/call/components/CallContactContainer.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { Avatar, Box, Typography } from '@material-ui/core'; import { makeStyles } from '@material-ui/core/styles'; -import { useContacts } from '../../../apps/contacts/hooks/useContacts'; +import { useContactActions } from '../../../apps/contacts/hooks/useContactActions'; import { useCall } from '../hooks/useCall'; import { useTranslation } from 'react-i18next'; @@ -17,7 +17,7 @@ const CallContactContainer = () => { const { call } = useCall(); const classes = useStyles(); - const { getDisplayByNumber, getPictureByNumber } = useContacts(); + const { getDisplayByNumber, getPictureByNumber } = useContactActions(); const getDisplayOrNumber = () => call.isTransmitter ? getDisplayByNumber(call?.receiver) : getDisplayByNumber(call?.transmitter); diff --git a/phone/src/os/phone/hooks/useDebounce.ts b/phone/src/os/phone/hooks/useDebounce.ts new file mode 100644 index 0000000..10a152d --- /dev/null +++ b/phone/src/os/phone/hooks/useDebounce.ts @@ -0,0 +1,16 @@ +import { useEffect, useState } from 'react'; + +export const useDebounce = (value: T, delay = 100) => { + const [debouncedValue, setDebouncedValue] = useState(value); + + useEffect(() => { + const handler = setTimeout(() => { + setDebouncedValue(value); + }, delay); + return () => { + clearTimeout(handler); + }; + }, [value, delay]); + + return debouncedValue; +}; diff --git a/phone/src/ui/components/LoadingSpinner.tsx b/phone/src/ui/components/LoadingSpinner.tsx new file mode 100644 index 0000000..bf03067 --- /dev/null +++ b/phone/src/ui/components/LoadingSpinner.tsx @@ -0,0 +1,8 @@ +import React from 'react'; +import { Box, CircularProgress } from '@material-ui/core'; + +export const LoadingSpinner: React.FC = () => ( + + + +); diff --git a/phone/src/utils/misc.ts b/phone/src/utils/misc.ts new file mode 100644 index 0000000..3462f90 --- /dev/null +++ b/phone/src/utils/misc.ts @@ -0,0 +1,3 @@ +// Quickly determine whether we are in browser +export const isEnvBrowser = (): boolean => + process.env.NODE_ENV === 'development' && !(window as any).invokeNative; diff --git a/phone/yarn.lock b/phone/yarn.lock index c6f7cfd..8dc4fb7 100644 --- a/phone/yarn.lock +++ b/phone/yarn.lock @@ -9991,10 +9991,10 @@ readdirp@~3.5.0: dependencies: picomatch "^2.2.1" -recoil@^0.2.0: - version "0.2.0" - resolved "https://registry.yarnpkg.com/recoil/-/recoil-0.2.0.tgz#69344b5bec3129272560d8d9d6001ada3ee4d80c" - integrity sha512-VOJfYVQ3VgmfS7L5tV9QdOR+AJhvll8yGr1+3nJPCqADulImuScGZ2sJtejPps3zfTu/o98y5kO4lje8Tx6XHw== +recoil@^0.3.1: + version "0.3.1" + resolved "https://registry.yarnpkg.com/recoil/-/recoil-0.3.1.tgz#40ef544160d19d76e25de8929d7e512eace13b90" + integrity sha512-KNA3DRqgxX4rRC8E7fc6uIw7BACmMPuraIYy+ejhE8tsw7w32CetMm8w7AMZa34wzanKKkev3vl3H7Z4s0QSiA== dependencies: hamt_plus "1.0.2" @@ -11559,10 +11559,10 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@3.9.7: - version "3.9.7" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.7.tgz#98d600a5ebdc38f40cb277522f12dc800e9e25fa" - integrity sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw== +typescript@^4.3.2: + version "4.3.2" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.2.tgz#399ab18aac45802d6f2498de5054fcbbe716a805" + integrity sha512-zZ4hShnmnoVnAHpVHWpTcxdv7dWP60S2FsydQLV8V5PbS3FifjWFFRiHSWpDJahly88PRyV5teTSLoq4eG7mKw== unbox-primitive@^1.0.0: version "1.0.0" diff --git a/resources/client/cl_contacts.ts b/resources/client/cl_contacts.ts index ddcb9f8..e7daf9d 100644 --- a/resources/client/cl_contacts.ts +++ b/resources/client/cl_contacts.ts @@ -1,40 +1,7 @@ -import { ContactEvents, PreDBContact } from '../../typings/contact'; -import { sendContactsEvent } from '../utils/messages'; +import { ContactEvents } from '../../typings/contact'; +import { RegisterNuiProxy } from './cl_utils'; -onNet(ContactEvents.SEND_CONTACTS, (contacts: any) => { - sendContactsEvent(ContactEvents.SEND_CONTACTS, contacts); -}); - -RegisterNuiCallbackType(ContactEvents.ADD_CONTACT); -on(`__cfx_nui:${ContactEvents.ADD_CONTACT}`, (data: PreDBContact, cb: Function) => { - emitNet(ContactEvents.ADD_CONTACT, data); - cb(); -}); - -onNet(ContactEvents.ADD_CONTACT_SUCCESS, () => { - emitNet(ContactEvents.GET_CONTACTS); -}); - -RegisterNuiCallbackType(ContactEvents.UPDATE_CONTACT); -on(`__cfx_nui:${ContactEvents.UPDATE_CONTACT}`, (data: any, cb: Function) => { - emitNet(ContactEvents.UPDATE_CONTACT, data); - cb(); -}); - -onNet(ContactEvents.UPDATE_CONTACT_SUCCESS, () => { - emitNet(ContactEvents.GET_CONTACTS); -}); - -RegisterNuiCallbackType(ContactEvents.DELETE_CONTACT); -on(`__cfx_nui:${ContactEvents.DELETE_CONTACT}`, (data: any, cb: Function) => { - emitNet(ContactEvents.DELETE_CONTACT, data); - cb(); -}); - -onNet(ContactEvents.DELETE_CONTACT_SUCCESS, () => { - emitNet(ContactEvents.GET_CONTACTS); -}); - -onNet(ContactEvents.ACTION_RESULT, (alert: any) => { - sendContactsEvent(ContactEvents.SEND_ALERT, alert); -}); +RegisterNuiProxy(ContactEvents.GET_CONTACTS); +RegisterNuiProxy(ContactEvents.ADD_CONTACT); +RegisterNuiProxy(ContactEvents.DELETE_CONTACT); +RegisterNuiProxy(ContactEvents.UPDATE_CONTACT); diff --git a/resources/client/cl_utils.ts b/resources/client/cl_utils.ts index 71fe136..2b39a5b 100644 --- a/resources/client/cl_utils.ts +++ b/resources/client/cl_utils.ts @@ -12,7 +12,7 @@ interface ISettingsParams { export default class ClientUtils { private _settings: ISettings; private _defaultSettings: ISettings = { - promiseTimeout: 5000, + promiseTimeout: 15000, }; constructor(settings?: ISettingsParams) { diff --git a/resources/server/contacts/contacts.controller.ts b/resources/server/contacts/contacts.controller.ts index 1e46f82..cab0f7b 100644 --- a/resources/server/contacts/contacts.controller.ts +++ b/resources/server/contacts/contacts.controller.ts @@ -1,32 +1,40 @@ -import { Contact, ContactEvents, PreDBContact } from '../../../typings/contact'; -import { getSource } from '../utils/miscUtils'; +import { Contact, ContactDeleteDTO, ContactEvents, PreDBContact } from '../../../typings/contact'; import ContactService from './contacts.service'; import { contactsLogger } from './contacts.utils'; +import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise'; -onNet(ContactEvents.GET_CONTACTS, async (limit: number) => { - const src = getSource(); - ContactService.handleFetchContact(src, limit).catch((e) => - contactsLogger.error(`Error occured in fetch contacts event (${src}), Error: ${e.message}`), - ); +onNetPromise(ContactEvents.GET_CONTACTS, (reqObj, resp) => { + ContactService.handleFetchContacts(reqObj, resp).catch((e) => { + contactsLogger.error( + `Error occured in fetch contacts event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); + }); }); -onNet(ContactEvents.ADD_CONTACT, async (contact: PreDBContact) => { - const src = getSource(); - ContactService.handleAddContact(src, contact).catch((e) => - contactsLogger.error(`Error occured in fetch contacts event (${src}), Error: ${e.message}`), - ); +onNetPromise(ContactEvents.ADD_CONTACT, (reqObj, resp) => { + ContactService.handleAddContact(reqObj, resp).catch((e) => { + contactsLogger.error( + `Error occured in fetch contacts event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); + }); }); -onNet(ContactEvents.UPDATE_CONTACT, async (contact: Contact) => { - const src = getSource(); - ContactService.handleUpdateContact(src, contact).catch((e) => - contactsLogger.error(`Error occured in update contact event (${src}), Error: ${e.message}`), - ); +onNetPromise(ContactEvents.UPDATE_CONTACT, (reqObj, resp) => { + ContactService.handleUpdateContact(reqObj, resp).catch((e) => { + contactsLogger.error( + `Error occured in update contact event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); + }); }); -onNet(ContactEvents.DELETE_CONTACT, async (contactId: number) => { - const src = getSource(); - ContactService.handleDeleteContact(src, contactId).catch((e) => - contactsLogger.error(`Error occured in delete contact event (${src}), Error: ${e.message}`), - ); +onNetPromise(ContactEvents.DELETE_CONTACT, (reqObj, resp) => { + ContactService.handleDeleteContact(reqObj, resp).catch((e) => { + contactsLogger.error( + `Error occured in delete contact event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); + }); }); diff --git a/resources/server/contacts/contacts.db.ts b/resources/server/contacts/contacts.db.ts index 6da31a6..175b38e 100644 --- a/resources/server/contacts/contacts.db.ts +++ b/resources/server/contacts/contacts.db.ts @@ -1,23 +1,29 @@ import { pool } from '../db'; import { Contact, PreDBContact } from '../../../typings/contact'; -import { FetchDefaultLimits } from '../utils/ServerConstants'; +import { ResultSetHeader } from 'mysql2'; export class _ContactsDB { - async fetchAllContacts( - identifier: string, - limit = FetchDefaultLimits.CONTACTS_FETCH_LIMIT, - ): Promise { - const query = - 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC'; - const [results] = await pool.query(query, [identifier, limit]); + async fetchAllContacts(identifier: string): Promise { + const query = 'SELECT * FROM npwd_phone_contacts WHERE identifier = ? ORDER BY display ASC'; + const [results] = await pool.query(query, [identifier]); return results; } - async addContact(identifier: string, { display, avatar, number }: PreDBContact): Promise { + async addContact( + identifier: string, + { display, avatar, number }: PreDBContact, + ): Promise { const query = 'INSERT INTO npwd_phone_contacts (identifier, number, display, avatar) VALUES (?, ?, ?, ?)'; - await pool.query(query, [identifier, number, display, avatar]); + const [setResult] = await pool.query(query, [identifier, number, display, avatar]); + + return { + id: (setResult).insertId, + number, + avatar, + display, + }; } async updateContact(contact: Contact, identifier: string): Promise { diff --git a/resources/server/contacts/contacts.interfaces.ts b/resources/server/contacts/contacts.interfaces.ts deleted file mode 100644 index 0b41b01..0000000 --- a/resources/server/contacts/contacts.interfaces.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { FxServerRespError } from '../../../typings/phone'; -import { ContactEvents } from '../../../typings/contact'; - -export interface ContactServerResp { - data?: unknown; - error?: FxServerRespError; - action: ContactEvents; -} diff --git a/resources/server/contacts/contacts.service.ts b/resources/server/contacts/contacts.service.ts index fbc59a0..e91a0bc 100644 --- a/resources/server/contacts/contacts.service.ts +++ b/resources/server/contacts/contacts.service.ts @@ -13,79 +13,57 @@ class _ContactService { contactsLogger.debug('Contacts service started'); } - private responseBuilder(src: number, { data, action, error }: ContactServerResp): void { - const serverRespObj: FxServerResponse = { - app: 'CONTACTS', - error, - status: data ? 'success' : 'failure', - action, - }; - - emitNet(ContactEvents.MAIN_CLIENT_LISTER, src, serverRespObj); - } - - async handleUpdateContact(src: number, contact: Contact): Promise { - const identifier = PlayerService.getIdentifier(src); + async handleUpdateContact( + reqObj: PromiseRequest, + resp: PromiseEventResp, + ): Promise { + const identifier = PlayerService.getIdentifier(reqObj.source); try { - await this.contactsDB.updateContact(contact, identifier); + await this.contactsDB.updateContact(reqObj.data, identifier); - emitNet(ContactEvents.UPDATE_CONTACT_SUCCESS, src); - - emitNet(ContactEvents.ACTION_RESULT, src, { - message: 'CONTACT_UPDATE_SUCCESS', - type: 'success', - }); + resp({ status: 'ok' }); } catch (e) { contactsLogger.error(`Error in handleUpdateContact (${identifier}), ${e.message}`); - emitNet(ContactEvents.ACTION_RESULT, src, { - message: 'CONTACT_UPDATE_FAILED', - type: 'error', - }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); } } - async handleDeleteContact(src: number, contactId: number): Promise { - const identifier = PlayerService.getIdentifier(src); + async handleDeleteContact( + reqObj: PromiseRequest, + resp: PromiseEventResp, + ): Promise { + const identifier = PlayerService.getIdentifier(reqObj.source); try { - await this.contactsDB.deleteContact(contactId, identifier); - emitNet(ContactEvents.DELETE_CONTACT_SUCCESS, src); - emitNet(ContactEvents.ACTION_RESULT, src, { - message: 'CONTACT_DELETE_SUCCESS', - type: 'success', - }); + await this.contactsDB.deleteContact(reqObj.data.id, identifier); + resp({ status: 'ok' }); } catch (e) { - emitNet(ContactEvents.ACTION_RESULT, src, { - message: 'CONTACT_DELETE_FAILED', - type: 'error', - }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); contactsLogger.error(`Error in handleDeleteContact (${identifier}), ${e.message}`); } } - async handleAddContact(src: number, contact: PreDBContact): Promise { - const identifier = PlayerService.getIdentifier(src); + async handleAddContact( + reqObj: PromiseRequest, + resp: PromiseEventResp, + ): Promise { + const identifier = PlayerService.getIdentifier(reqObj.source); try { - await this.contactsDB.addContact(identifier, contact); + const contact = await this.contactsDB.addContact(identifier, reqObj.data); - emitNet(ContactEvents.ADD_CONTACT_SUCCESS, src); - emitNet(ContactEvents.ACTION_RESULT, src, { - message: 'CONTACT_ADD_SUCCESS', - type: 'success', - }); + resp({ status: 'ok', data: contact }); } catch (e) { contactsLogger.error(`Error in handleAddContact, ${e.message}`); - emitNet(ContactEvents.ACTION_RESULT, src, { - message: 'CONTACT_ADD_FAILED', - type: 'error', - }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); } } - async handleFetchContact(src: number, limit?: number): Promise { - const identifier = PlayerService.getIdentifier(src); - + async handleFetchContacts( + reqObj: PromiseRequest, + resp: PromiseEventResp, + ): Promise { + const identifier = PlayerService.getIdentifier(reqObj.source); try { - const contacts = await this.contactsDB.fetchAllContacts(identifier, limit); - - emitNet(ContactEvents.SEND_CONTACTS, src, contacts); + const contacts = await this.contactsDB.fetchAllContacts(identifier); + resp({ status: 'ok', data: contacts }); } catch (e) { + resp({ status: 'error', errorMsg: 'DB_ERROR' }); contactsLogger.error(`Error in handleFetchContact (${identifier}), ${e.message}`); } } diff --git a/typings/contact.ts b/typings/contact.ts index 42ab22e..94a3a5e 100644 --- a/typings/contact.ts +++ b/typings/contact.ts @@ -21,6 +21,10 @@ export interface Contact extends PreDBContact { id: number; } +export interface ContactDeleteDTO { + id: number; +} + export enum ContactEvents { SEND_CONTACTS = 'npwd:sendContacts', GET_CONTACTS = 'npwd:getContacts', From be8e9bfa39dc6430ac3121805f9e10d5fe3adda2 Mon Sep 17 00:00:00 2001 From: Taso Date: Tue, 8 Jun 2021 15:35:12 -0400 Subject: [PATCH 2/8] tweak(contacts): Misc changes to contact handling --- config.json | 2 +- phone/src/apps/contacts/components/views/ContactInfo.tsx | 2 +- phone/src/apps/contacts/hooks/useContactActions.ts | 3 +-- resources/server/contacts/contacts.service.ts | 5 ++--- 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/config.json b/config.json index 18200fe..3faa450 100644 --- a/config.json +++ b/config.json @@ -40,7 +40,7 @@ "showNotifications": true }, "debug": { - "level": "debug", + "level": "silly", "enabled": true } } diff --git a/phone/src/apps/contacts/components/views/ContactInfo.tsx b/phone/src/apps/contacts/components/views/ContactInfo.tsx index cce1ddf..2b30cd0 100644 --- a/phone/src/apps/contacts/components/views/ContactInfo.tsx +++ b/phone/src/apps/contacts/components/views/ContactInfo.tsx @@ -101,7 +101,7 @@ const ContactsInfoPage = () => { addContact(serverResp.data); addAlert({ message: t('APPS_CONTACT_ADD_SUCCESS'), - type: 'error', + type: 'success', }); history.replace(referal); }); diff --git a/phone/src/apps/contacts/hooks/useContactActions.ts b/phone/src/apps/contacts/hooks/useContactActions.ts index 8b6a974..6d2d8ef 100644 --- a/phone/src/apps/contacts/hooks/useContactActions.ts +++ b/phone/src/apps/contacts/hooks/useContactActions.ts @@ -54,8 +54,7 @@ export const useContactActions = (): UseContactsValue => { const deleteContact = useCallback( (id: number): void => { - const contactIndex = contacts.findIndex((contact) => contact.id === id); - const newContacts = [...contacts].slice(contactIndex); + const newContacts = [...contacts].filter((contact) => contact.id !== id); setContacts(newContacts); }, [contacts, setContacts], diff --git a/resources/server/contacts/contacts.service.ts b/resources/server/contacts/contacts.service.ts index e91a0bc..a325fe4 100644 --- a/resources/server/contacts/contacts.service.ts +++ b/resources/server/contacts/contacts.service.ts @@ -1,9 +1,8 @@ import PlayerService from '../players/player.service'; import { contactsLogger } from './contacts.utils'; import ContactsDB, { _ContactsDB } from './contacts.db'; -import { Contact, ContactEvents, PreDBContact } from '../../../typings/contact'; -import { FxServerResponse } from '../../../typings/phone'; -import { ContactServerResp } from './contacts.interfaces'; +import { Contact, ContactDeleteDTO, PreDBContact } from '../../../typings/contact'; +import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types'; class _ContactService { private readonly contactsDB: _ContactsDB; From 51d8aa632267b88160cba19cced3d8d595bc8165 Mon Sep 17 00:00:00 2001 From: Taso Date: Tue, 8 Jun 2021 15:36:56 -0400 Subject: [PATCH 3/8] types(contacts): Cleanup unused types --- typings/contact.ts | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/typings/contact.ts b/typings/contact.ts index 94a3a5e..36e8429 100644 --- a/typings/contact.ts +++ b/typings/contact.ts @@ -6,11 +6,6 @@ export type AlertCategory = | 'CONTACT_DELETE_SUCCESS' | 'CONTACT_DELETE_FAILED'; -export interface IContactAlert { - alert: AlertCategory; - setAlert: (type: string) => void; -} - export interface PreDBContact { display: string; number: string; @@ -26,15 +21,8 @@ export interface ContactDeleteDTO { } export enum ContactEvents { - SEND_CONTACTS = 'npwd:sendContacts', GET_CONTACTS = 'npwd:getContacts', ADD_CONTACT = 'npwd:addContacts', - ADD_CONTACT_SUCCESS = 'contacts:addSuccess', UPDATE_CONTACT = 'npwd:updateContact', DELETE_CONTACT = 'npwd:deleteContact', - DELETE_CONTACT_SUCCESS = 'npwd:deleteSuccess', - UPDATE_CONTACT_SUCCESS = 'npwd:updateContactSuccess', - ACTION_RESULT = 'npwd:contactActionResult', - SEND_ALERT = 'npwd:contactSetAlert', - MAIN_CLIENT_LISTER = 'npwd:contactMainListener', } From 2d1e1928926ade791a1b6ce1485155b54a360a4d Mon Sep 17 00:00:00 2001 From: Taso Date: Tue, 8 Jun 2021 15:45:47 -0400 Subject: [PATCH 4/8] tweak(server/onNetPromise): Enhance logging --- resources/server/utils/PromiseNetEvents/onNetPromise.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/resources/server/utils/PromiseNetEvents/onNetPromise.ts b/resources/server/utils/PromiseNetEvents/onNetPromise.ts index c388072..615a249 100644 --- a/resources/server/utils/PromiseNetEvents/onNetPromise.ts +++ b/resources/server/utils/PromiseNetEvents/onNetPromise.ts @@ -14,10 +14,13 @@ export function onNetPromise(eventName: string, cb: CBSignatur data, }; + netEventLogger.silly(`netPromise > ${eventName} > RequestObj`); + netEventLogger.silly(promiseRequest); + const promiseResp: PromiseEventResp

= (data: ServerPromiseResp

) => { emitNet(respEventName, src, data); - netEventLogger.debug(`Response Promise Event ${respEventName}, Data >>`); - netEventLogger.debug(data); + netEventLogger.silly(`Response Promise Event ${respEventName}, Data >>`); + netEventLogger.silly(data); }; // In case the cb is a promise, we use Promise.resolve @@ -26,7 +29,7 @@ export function onNetPromise(eventName: string, cb: CBSignatur `An error occured for a onNetPromise (${eventName}), Error: ${e.message}`, ); - promiseResp({ status: 'error', errorMsg: 'Server error occurred' }); + promiseResp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' }); }); }); } From 4afa9c691bd56dd03c18cf7a8581fa4c1197c35e Mon Sep 17 00:00:00 2001 From: Taso Date: Fri, 4 Jun 2021 10:48:02 -0400 Subject: [PATCH 5/8] refactor(phone/marketplace): Refactor state management and fetching --- .../marketplace/components/MarketplaceApp.tsx | 2 +- .../ListingActions.tsx | 47 +++++++++++-- .../MarketplaceItem.tsx | 4 +- .../MarketplaceList.tsx | 6 +- .../MarketplaceListContainer.tsx | 17 +++++ .../SelloutList/MarketplaceListContainer.tsx | 6 -- .../components/form/ListingForm.tsx | 23 +++++-- phone/src/apps/marketplace/hooks/state.ts | 49 +++++++++++-- .../src/apps/marketplace/hooks/useListing.ts | 7 -- .../hooks/useMarketplaceService.ts | 44 +++++++----- resources/client/cl_marketplace.ts | 68 +++++++++++-------- typings/marketplace.ts | 25 ++++++- 12 files changed, 211 insertions(+), 87 deletions(-) rename phone/src/apps/marketplace/components/{SelloutList => MarketplaceList}/ListingActions.tsx (64%) rename phone/src/apps/marketplace/components/{SelloutList => MarketplaceList}/MarketplaceItem.tsx (94%) rename phone/src/apps/marketplace/components/{SelloutList => MarketplaceList}/MarketplaceList.tsx (66%) create mode 100644 phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx delete mode 100644 phone/src/apps/marketplace/components/SelloutList/MarketplaceListContainer.tsx delete mode 100644 phone/src/apps/marketplace/hooks/useListing.ts diff --git a/phone/src/apps/marketplace/components/MarketplaceApp.tsx b/phone/src/apps/marketplace/components/MarketplaceApp.tsx index cff692e..d2aca04 100644 --- a/phone/src/apps/marketplace/components/MarketplaceApp.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceApp.tsx @@ -1,7 +1,7 @@ import React from 'react'; import { AppWrapper } from '../../../ui/components'; import { AppContent } from '../../../ui/components/AppContent'; -import { MarketplaceListContainer } from './SelloutList/MarketplaceListContainer'; +import { MarketplaceListContainer } from './MarketplaceList/MarketplaceListContainer'; import { NavigationBar } from './navigation/NavigationBar'; import { Switch, Route } from 'react-router-dom'; import { ListingFormContainer } from './form/ListingFormContainer'; diff --git a/phone/src/apps/marketplace/components/SelloutList/ListingActions.tsx b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx similarity index 64% rename from phone/src/apps/marketplace/components/SelloutList/ListingActions.tsx rename to phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx index ee3af55..baccfb4 100644 --- a/phone/src/apps/marketplace/components/SelloutList/ListingActions.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx @@ -1,7 +1,11 @@ import { Box, Tooltip, Button } from '@material-ui/core'; import { makeStyles, Theme } from '@material-ui/core/styles'; import React from 'react'; -import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace'; +import { + MarketplaceActionResp, + MarketplaceEvents, + MarketplaceListing, +} from '../../../../../../typings/marketplace'; import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import DeleteIcon from '@material-ui/icons/Delete'; import ReportIcon from '@material-ui/icons/Report'; @@ -11,6 +15,8 @@ import { useNuiRequest } from 'fivem-nui-react-lib'; import { useTranslation } from 'react-i18next'; import { useHistory } from 'react-router'; import { CallEvents } from '../../../../../../typings/call'; +import { fetchNui } from '../../../../utils/fetchNui'; +import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; const useStyles = makeStyles((theme: Theme) => ({ icon: { @@ -18,21 +24,48 @@ const useStyles = makeStyles((theme: Theme) => ({ }, })); -export const ListingActions = ({ listing }: { listing: MarketplaceListing }) => { +export const ListingActions: React.FC = ({ children, ...listing }) => { const Nui = useNuiRequest(); const classes = useStyles(); const { number: myNumber } = useSimcard(); const { t } = useTranslation(); const history = useHistory(); + const { addAlert } = useSnackbar(); const handleDeleteListing = () => { - Nui.send(MarketplaceEvents.DELETE_LISTING, { + fetchNui(MarketplaceEvents.DELETE_LISTING, { id: listing.id, + }).then(({ err, errMsg }) => { + if (err) { + return addAlert({ + message: t(errMsg), + type: 'error', + }); + } + + addAlert({ + message: t('APPS_MARKETPLACE_DELETE_LISTING_SUCCESS'), + type: 'success', + }); }); }; const handleReportListing = () => { - Nui.send(MarketplaceEvents.REPORT_LISTING, listing); + fetchNui(MarketplaceEvents.DELETE_LISTING, listing).then( + ({ err, errMsg }) => { + if (err) { + return addAlert({ + message: t(errMsg), + type: 'error', + }); + } + + addAlert({ + message: t('APPS_MARKETPLACE_REPORT_LISTING_SUCCESS'), + type: 'success', + }); + }, + ); }; const handleCall = () => { @@ -46,9 +79,9 @@ export const ListingActions = ({ listing }: { listing: MarketplaceListing }) => }; return ( - +

- {listing.number !== myNumber ? ( + {listing.number !== myNumber && ( <> - ) : null} + )}
diff --git a/phone/src/apps/marketplace/components/SelloutList/MarketplaceItem.tsx b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceItem.tsx similarity index 94% rename from phone/src/apps/marketplace/components/SelloutList/MarketplaceItem.tsx rename to phone/src/apps/marketplace/components/MarketplaceList/MarketplaceItem.tsx index 39ec38d..0951e26 100644 --- a/phone/src/apps/marketplace/components/SelloutList/MarketplaceItem.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceItem.tsx @@ -41,7 +41,7 @@ const useStyles = makeStyles((theme) => ({ }, })); -export const MarketplaceItem = (listing: MarketplaceListing) => { +export const MarketplaceItem: React.FC = ({ children, ...listing }) => { const classes = useStyles(); return ( @@ -73,7 +73,7 @@ export const MarketplaceItem = (listing: MarketplaceListing) => { {listing.description} - +
diff --git a/phone/src/apps/marketplace/components/SelloutList/MarketplaceList.tsx b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceList.tsx similarity index 66% rename from phone/src/apps/marketplace/components/SelloutList/MarketplaceList.tsx rename to phone/src/apps/marketplace/components/MarketplaceList/MarketplaceList.tsx index 00e5ea2..5af07de 100644 --- a/phone/src/apps/marketplace/components/SelloutList/MarketplaceList.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceList.tsx @@ -1,10 +1,10 @@ import React from 'react'; import { List } from '../../../../ui/components/List'; -import { useListing } from '../../hooks/useListing'; +import { useListingValue } from '../../hooks/state'; import { MarketplaceItem } from './MarketplaceItem'; -export const MarketplaceList = () => { - const listings = useListing(); +export const MarketplaceList: React.FC = () => { + const listings = useListingValue(); return ( diff --git a/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx new file mode 100644 index 0000000..a64af09 --- /dev/null +++ b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx @@ -0,0 +1,17 @@ +import React from 'react'; +import { MarketplaceList } from './MarketplaceList'; +import { Box, CircularProgress } from '@material-ui/core'; + +const LoadingListings: React.FC = () => ( + + + +); + +export const MarketplaceListContainer: React.FC = () => { + return ( + }> + + + ); +}; diff --git a/phone/src/apps/marketplace/components/SelloutList/MarketplaceListContainer.tsx b/phone/src/apps/marketplace/components/SelloutList/MarketplaceListContainer.tsx deleted file mode 100644 index 12e889d..0000000 --- a/phone/src/apps/marketplace/components/SelloutList/MarketplaceListContainer.tsx +++ /dev/null @@ -1,6 +0,0 @@ -import React from 'react'; -import { MarketplaceList } from './MarketplaceList'; - -export const MarketplaceListContainer = () => { - return ; -}; diff --git a/phone/src/apps/marketplace/components/form/ListingForm.tsx b/phone/src/apps/marketplace/components/form/ListingForm.tsx index c128b1b..5997802 100644 --- a/phone/src/apps/marketplace/components/form/ListingForm.tsx +++ b/phone/src/apps/marketplace/components/form/ListingForm.tsx @@ -1,7 +1,6 @@ import React, { useEffect, useState, useCallback } from 'react'; import { makeStyles, Button, Box } from '@material-ui/core'; -import { useNuiRequest } from 'fivem-nui-react-lib'; -import { MarketplaceEvents } from '../../../../../../typings/marketplace'; +import { MarketplaceActionResp, MarketplaceEvents } from '../../../../../../typings/marketplace'; import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; import { useTranslation } from 'react-i18next'; import ImageIcon from '@material-ui/icons/Image'; @@ -10,6 +9,7 @@ import qs from 'qs'; import { useQueryParams } from '../../../../common/hooks/useQueryParams'; import { deleteQueryFromLocation } from '../../../../common/utils/deleteQueryFromLocation'; import { TextField } from '../../../../ui/components/Input'; +import { fetchNui } from '../../../../utils/fetchNui'; const useStyles = makeStyles((theme) => ({ root: { @@ -36,7 +36,6 @@ const useStyles = makeStyles((theme) => ({ })); export const ListingForm = () => { - const Nui = useNuiRequest(); const classes = useStyles(); const { t } = useTranslation(); const { addAlert } = useSnackbar(); @@ -50,12 +49,24 @@ export const ListingForm = () => { const addListing = () => { if (title !== '' && description !== '') { - Nui.send(MarketplaceEvents.ADD_LISTING, { + fetchNui(MarketplaceEvents.ADD_LISTING, { title, - url, description, + url, + }).then(({ err, errMsg }) => { + if (err) { + return addAlert({ + message: t(errMsg), + type: 'error', + }); + } + + addAlert({ + message: t('APPS_MARKETPLACE_CREATE_LISTING_SUCCESS'), + type: 'success', + }); + history.push('/marketplace'); }); - history.push('/marketplace'); } else { addAlert({ message: t('APPS_MARKETPLACE_REQUIRED_FIELDS'), diff --git a/phone/src/apps/marketplace/hooks/state.ts b/phone/src/apps/marketplace/hooks/state.ts index 77481ed..2e336ab 100644 --- a/phone/src/apps/marketplace/hooks/state.ts +++ b/phone/src/apps/marketplace/hooks/state.ts @@ -1,9 +1,44 @@ -import { atom } from 'recoil'; -import { MarketplaceListing } from '../../../../../typings/marketplace'; +import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil'; +import { MarketplaceEvents, MarketplaceListing } from '../../../../../typings/marketplace'; +import { fetchNui } from '../../../utils/fetchNui'; -export const selloutState = { - listing: atom({ - key: 'listing', - default: [], +const defaultData: MarketplaceListing[] = [ + { + id: 1, + name: 'Some guy', + number: '111-1134', + username: 'Taso', + title: 'eeeeeeeeeeeeeeeeeeeeeeeee', + description: + 'skldfsdEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE', + url: 'https://beta.iodine.gg/706Y3.jpeg', + }, + { + id: 2, + name: 'Some other dude', + number: '666-6666', + username: 'Taso', + title: 'Material', + description: 'Selling my wife', + url: '', + }, +]; + +const listingState = atom({ + key: 'listings', + default: selector({ + key: 'defaultListings', + get: async () => { + try { + return await fetchNui(MarketplaceEvents.FETCH_LISTING); + } catch (e) { + if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) { + return defaultData; + } + } + }, }), -}; +}); + +export const useListingValue = () => useRecoilValue(listingState); +export const useSetListings = () => useSetRecoilState(listingState); diff --git a/phone/src/apps/marketplace/hooks/useListing.ts b/phone/src/apps/marketplace/hooks/useListing.ts deleted file mode 100644 index 0e0f1d2..0000000 --- a/phone/src/apps/marketplace/hooks/useListing.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { useRecoilValue } from 'recoil'; -import { MarketplaceListing } from '../../../../../typings/marketplace'; -import { selloutState } from './state'; - -export const useListing = () => { - return useRecoilValue(selloutState.listing); -}; diff --git a/phone/src/apps/marketplace/hooks/useMarketplaceService.ts b/phone/src/apps/marketplace/hooks/useMarketplaceService.ts index b644f25..ba59fa0 100644 --- a/phone/src/apps/marketplace/hooks/useMarketplaceService.ts +++ b/phone/src/apps/marketplace/hooks/useMarketplaceService.ts @@ -1,24 +1,32 @@ import { useNuiEvent } from 'fivem-nui-react-lib'; -import { selloutState } from './state'; -import { useListing } from './useListing'; -import { useSetRecoilState } from 'recoil'; -import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar'; -import { useTranslation } from 'react-i18next'; -import { MarketplaceEvents } from '../../../../../typings/marketplace'; +import { + MarketPlaceBroadcastData, + MarketplaceDeleteDTO, + MarketplaceEvents, + MarketplaceListing, +} from '../../../../../typings/marketplace'; +import { useSetListings } from './state'; export const useMarketplaceService = () => { - const setSellout = useSetRecoilState(selloutState.listing); - const { addAlert } = useSnackbar(); - const { t } = useTranslation(); + const setListings = useSetListings(); - const handleAddAlert = ({ message, type }: IAlert) => { - addAlert({ - message: t(`APPS_${message}`), - type, - }); - }; + useNuiEvent( + 'SELLOUT', + MarketplaceEvents.BROADCAST_EVENT, + ({ type, listing }) => { + if (type === 'ADD') { + const typeCastListing = listing as MarketplaceListing; + return setListings((curState) => [...curState, typeCastListing]); + } - useNuiEvent('SELLOUT', MarketplaceEvents.SEND_ALERT, handleAddAlert); - useNuiEvent('SELLOUT', MarketplaceEvents.SEND_LISTING, setSellout); - return useListing(); + if (type === 'DELETE') { + const deleteDTO = listing as MarketplaceDeleteDTO; + return setListings((currVal) => { + const arrayPos = currVal.map((item) => item.id).indexOf(deleteDTO.id); + + return [...currVal].splice(arrayPos); + }); + } + }, + ); }; diff --git a/resources/client/cl_marketplace.ts b/resources/client/cl_marketplace.ts index 964485d..72fe64a 100644 --- a/resources/client/cl_marketplace.ts +++ b/resources/client/cl_marketplace.ts @@ -1,37 +1,47 @@ -import { MarketplaceEvents, MarketplaceListing } from '../../typings/marketplace'; -import { IAlertProps } from '../../typings/alerts'; +import { MarketplaceEvents, MarketplaceListingBroadcast } from '../../typings/marketplace'; +import { RegisterNuiProxy } from './cl_utils'; import { sendMarketplaceEvent } from '../utils/messages'; -onNet(MarketplaceEvents.SEND_LISTING, (listings: MarketplaceListing[]) => { - sendMarketplaceEvent(MarketplaceEvents.SEND_LISTING, listings); +// onNet(MarketplaceEvents.SEND_LISTING, (listings: MarketplaceListing[]) => { +// sendMarketplaceEvent(MarketplaceEvents.SEND_LISTING, listings); +// }); + +RegisterNuiProxy(MarketplaceEvents.FETCH_LISTING); +RegisterNuiProxy(MarketplaceEvents.ADD_LISTING); + +// RegisterNuiCallbackType(MarketplaceEvents.ADD_LISTING); +// on(`__cfx_nui:${MarketplaceEvents.ADD_LISTING}`, (data: MarketplaceListing, cb: Function) => { +// emitNet(MarketplaceEvents.ADD_LISTING, data); +// cb(); +// }); + +RegisterNuiProxy(MarketplaceEvents.DELETE_LISTING); +RegisterNuiProxy(MarketplaceEvents.REPORT_LISTING); + +onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketplaceListingBroadcast) => { + sendMarketplaceEvent(MarketplaceEvents.BROADCAST_EVENT, broadcastEvent); }); -RegisterNuiCallbackType(MarketplaceEvents.ADD_LISTING); -on(`__cfx_nui:${MarketplaceEvents.ADD_LISTING}`, (data: MarketplaceListing, cb: Function) => { - emitNet(MarketplaceEvents.ADD_LISTING, data); - cb(); -}); +// RegisterNuiCallbackType(MarketplaceEvents.DELETE_LISTING); +// on(`__cfx_nui:${MarketplaceEvents.DELETE_LISTING}`, (data: MarketplaceListing, cb: Function) => { +// emitNet(MarketplaceEvents.DELETE_LISTING, data.id); +// cb(); +// }); -RegisterNuiCallbackType(MarketplaceEvents.DELETE_LISTING); -on(`__cfx_nui:${MarketplaceEvents.DELETE_LISTING}`, (data: MarketplaceListing, cb: Function) => { - emitNet(MarketplaceEvents.DELETE_LISTING, data.id); - cb(); -}); +// RegisterNuiCallbackType(MarketplaceEvents.REPORT_LISTING); +// on(`__cfx_nui:${MarketplaceEvents.REPORT_LISTING}`, (data: MarketplaceListing, cb: Function) => { +// emitNet(MarketplaceEvents.REPORT_LISTING, data); +// cb(); +// }); -RegisterNuiCallbackType(MarketplaceEvents.REPORT_LISTING); -on(`__cfx_nui:${MarketplaceEvents.REPORT_LISTING}`, (data: MarketplaceListing, cb: Function) => { - emitNet(MarketplaceEvents.REPORT_LISTING, data); - cb(); -}); +// onNet(MarketplaceEvents.ADD_LISTING_SUCCESS, () => { +// emitNet(MarketplaceEvents.FETCH_LISTING); +// }); -onNet(MarketplaceEvents.ADD_LISTING_SUCCESS, () => { - emitNet(MarketplaceEvents.FETCH_LISTING); -}); +// onNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, () => { +// emitNet(MarketplaceEvents.FETCH_LISTING); +// }); -onNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, () => { - emitNet(MarketplaceEvents.FETCH_LISTING); -}); - -onNet(MarketplaceEvents.ACTION_RESULT, (alert: IAlertProps) => { - sendMarketplaceEvent(MarketplaceEvents.SEND_ALERT, alert); -}); +// onNet(MarketplaceEvents.ACTION_RESULT, (alert: IAlertProps) => { +// sendMarketplaceEvent(MarketplaceEvents.SEND_ALERT, alert); +// }); diff --git a/typings/marketplace.ts b/typings/marketplace.ts index 94099a4..ea6805a 100644 --- a/typings/marketplace.ts +++ b/typings/marketplace.ts @@ -1,14 +1,22 @@ -export interface MarketplaceListing { +export interface MarketplaceListing extends MarketplaceListingBase { id: number; identifier?: string; username: string; name: string; number: string; +} + +export interface MarketplaceListingBase { title: string; url: string; description: string; } +export interface MarketplaceActionResp { + err: boolean; + errMsg?: string; +} + export enum MarketplaceEvents { ADD_LISTING = 'npwd:addListing', ADD_LISTING_SUCCESS = 'npwd:addListingSuccess', @@ -21,4 +29,19 @@ export enum MarketplaceEvents { REPORT_LISTING_SUCCESS = 'npwd:reportListingSuccess', REPORT_LISTING_SUCESS = 'npwd:reportListingFailed', SEND_ALERT = 'nwpd:sendListingAlert', + BROADCAST_EVENT = 'npwd:sendMarketplaceBroadcast', } + +export interface MarketplaceDeleteDTO { + id: number; +} + +export type MarketPlaceBroadcastData = + | { + type: 'ADD'; + listing: MarketplaceListing; + } + | { + type: 'DELETE'; + listing: MarketplaceDeleteDTO; + }; From 3df2f887590c02ebf6d135b608cb0aaee4ebfe5a Mon Sep 17 00:00:00 2001 From: Taso Date: Fri, 4 Jun 2021 13:08:20 -0400 Subject: [PATCH 6/8] refactor(server/marketplace): Refactor to use promise events --- .../MarketplaceList/ListingActions.tsx | 28 ++--- .../components/form/ListingForm.tsx | 2 +- phone/src/apps/marketplace/hooks/state.ts | 8 +- .../hooks/useMarketplaceService.ts | 1 - resources/client/cl_marketplace.ts | 38 +----- .../marketplace/marketplace.controller.ts | 77 +++++++----- .../server/marketplace/marketplace.db.ts | 13 +- .../server/marketplace/marketplace.service.ts | 119 +++++++++++------- typings/marketplace.ts | 8 ++ 9 files changed, 160 insertions(+), 134 deletions(-) diff --git a/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx index baccfb4..b37bb05 100644 --- a/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx @@ -51,21 +51,21 @@ export const ListingActions: React.FC = ({ children, ...list }; const handleReportListing = () => { - fetchNui(MarketplaceEvents.DELETE_LISTING, listing).then( - ({ err, errMsg }) => { - if (err) { - return addAlert({ - message: t(errMsg), - type: 'error', - }); - } - - addAlert({ - message: t('APPS_MARKETPLACE_REPORT_LISTING_SUCCESS'), - type: 'success', + fetchNui(MarketplaceEvents.REPORT_LISTING, { + listingId: listing.id, + }).then(({ err, errMsg }) => { + if (err) { + return addAlert({ + message: t(errMsg), + type: 'error', }); - }, - ); + } + + addAlert({ + message: t('APPS_MARKETPLACE_REPORT_LISTING_SUCCESS'), + type: 'success', + }); + }); }; const handleCall = () => { diff --git a/phone/src/apps/marketplace/components/form/ListingForm.tsx b/phone/src/apps/marketplace/components/form/ListingForm.tsx index 5997802..293b153 100644 --- a/phone/src/apps/marketplace/components/form/ListingForm.tsx +++ b/phone/src/apps/marketplace/components/form/ListingForm.tsx @@ -56,7 +56,7 @@ export const ListingForm = () => { }).then(({ err, errMsg }) => { if (err) { return addAlert({ - message: t(errMsg), + message: t('errMsg'), type: 'error', }); } diff --git a/phone/src/apps/marketplace/hooks/state.ts b/phone/src/apps/marketplace/hooks/state.ts index 2e336ab..c5b2148 100644 --- a/phone/src/apps/marketplace/hooks/state.ts +++ b/phone/src/apps/marketplace/hooks/state.ts @@ -1,5 +1,9 @@ import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil'; -import { MarketplaceEvents, MarketplaceListing } from '../../../../../typings/marketplace'; +import { + MarketplaceEvents, + MarketplaceFetchResp, + MarketplaceListing, +} from '../../../../../typings/marketplace'; import { fetchNui } from '../../../utils/fetchNui'; const defaultData: MarketplaceListing[] = [ @@ -30,7 +34,7 @@ const listingState = atom({ key: 'defaultListings', get: async () => { try { - return await fetchNui(MarketplaceEvents.FETCH_LISTING); + return (await fetchNui(MarketplaceEvents.FETCH_LISTING)).data; } catch (e) { if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) { return defaultData; diff --git a/phone/src/apps/marketplace/hooks/useMarketplaceService.ts b/phone/src/apps/marketplace/hooks/useMarketplaceService.ts index ba59fa0..5c1f987 100644 --- a/phone/src/apps/marketplace/hooks/useMarketplaceService.ts +++ b/phone/src/apps/marketplace/hooks/useMarketplaceService.ts @@ -23,7 +23,6 @@ export const useMarketplaceService = () => { const deleteDTO = listing as MarketplaceDeleteDTO; return setListings((currVal) => { const arrayPos = currVal.map((item) => item.id).indexOf(deleteDTO.id); - return [...currVal].splice(arrayPos); }); } diff --git a/resources/client/cl_marketplace.ts b/resources/client/cl_marketplace.ts index 72fe64a..3faabcb 100644 --- a/resources/client/cl_marketplace.ts +++ b/resources/client/cl_marketplace.ts @@ -1,47 +1,13 @@ -import { MarketplaceEvents, MarketplaceListingBroadcast } from '../../typings/marketplace'; +import { MarketplaceEvents, MarketPlaceBroadcastData } from '../../typings/marketplace'; import { RegisterNuiProxy } from './cl_utils'; import { sendMarketplaceEvent } from '../utils/messages'; -// onNet(MarketplaceEvents.SEND_LISTING, (listings: MarketplaceListing[]) => { -// sendMarketplaceEvent(MarketplaceEvents.SEND_LISTING, listings); -// }); - RegisterNuiProxy(MarketplaceEvents.FETCH_LISTING); RegisterNuiProxy(MarketplaceEvents.ADD_LISTING); -// RegisterNuiCallbackType(MarketplaceEvents.ADD_LISTING); -// on(`__cfx_nui:${MarketplaceEvents.ADD_LISTING}`, (data: MarketplaceListing, cb: Function) => { -// emitNet(MarketplaceEvents.ADD_LISTING, data); -// cb(); -// }); - RegisterNuiProxy(MarketplaceEvents.DELETE_LISTING); RegisterNuiProxy(MarketplaceEvents.REPORT_LISTING); -onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketplaceListingBroadcast) => { +onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketPlaceBroadcastData) => { sendMarketplaceEvent(MarketplaceEvents.BROADCAST_EVENT, broadcastEvent); }); - -// RegisterNuiCallbackType(MarketplaceEvents.DELETE_LISTING); -// on(`__cfx_nui:${MarketplaceEvents.DELETE_LISTING}`, (data: MarketplaceListing, cb: Function) => { -// emitNet(MarketplaceEvents.DELETE_LISTING, data.id); -// cb(); -// }); - -// RegisterNuiCallbackType(MarketplaceEvents.REPORT_LISTING); -// on(`__cfx_nui:${MarketplaceEvents.REPORT_LISTING}`, (data: MarketplaceListing, cb: Function) => { -// emitNet(MarketplaceEvents.REPORT_LISTING, data); -// cb(); -// }); - -// onNet(MarketplaceEvents.ADD_LISTING_SUCCESS, () => { -// emitNet(MarketplaceEvents.FETCH_LISTING); -// }); - -// onNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, () => { -// emitNet(MarketplaceEvents.FETCH_LISTING); -// }); - -// onNet(MarketplaceEvents.ACTION_RESULT, (alert: IAlertProps) => { -// sendMarketplaceEvent(MarketplaceEvents.SEND_ALERT, alert); -// }); diff --git a/resources/server/marketplace/marketplace.controller.ts b/resources/server/marketplace/marketplace.controller.ts index c6dce16..c3ac565 100644 --- a/resources/server/marketplace/marketplace.controller.ts +++ b/resources/server/marketplace/marketplace.controller.ts @@ -1,42 +1,59 @@ -import { MarketplaceEvents, MarketplaceListing } from '../../../typings/marketplace'; -import { getSource } from '../utils/miscUtils'; +import { + MarketplaceEvents, + MarketplaceListingBase, + MarketplaceReportDTO, +} from '../../../typings/marketplace'; import PlayerService from '../players/player.service'; import { selloutLogger } from './marketplace.utils'; import MarketplaceService from './marketplace.service'; +import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise'; +import { MarketplaceDeleteDTO } from '../../../typings/marketplace'; -onNet(MarketplaceEvents.FETCH_LISTING, async () => { - const src = getSource(); - MarketplaceService.handleFetchListings(src).catch((e) => - selloutLogger.error(`Error occurred in fetch listing event (${src}), Error: ${e.message}`), - ); +onNetPromise(MarketplaceEvents.FETCH_LISTING, async (reqObj, resp) => { + MarketplaceService.handleFetchListings(resp, reqObj.source).catch((e) => { + selloutLogger.error( + `Error occurred in fetch listing event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ error: true, errorMsg: '`Error occurred in fetch listing event' }); + }); }); -onNet(MarketplaceEvents.ADD_LISTING, async (listing: MarketplaceListing) => { - const src = getSource(); - const Player = PlayerService.getPlayer(src); - +onNetPromise(MarketplaceEvents.ADD_LISTING, async (reqObj, resp) => { + const player = PlayerService.getPlayer(reqObj.source); MarketplaceService.handleAddListing( - src, - Player.getFirstName(), - Player.username, - Player.getName(), - Player.getPhoneNumber(), - listing, - ).catch((e) => - selloutLogger.error(`Error occurred in add listing event (${src}), Error: ${e.message}`), - ); + { + src: reqObj.source, + name: player.getName(), + username: player.username, + number: player.getPhoneNumber(), + listing: reqObj.data, + identifier: player.getIdentifier(), + }, + resp, + ).catch((e) => { + selloutLogger.error( + `Error occurred in add listing event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ error: true, errorMsg: 'Error occurred in add listing event' }); + }); }); -onNet(MarketplaceEvents.DELETE_LISTING, async (listingId: number) => { - const src = getSource(); - MarketplaceService.handleDeleteListing(src, listingId).catch((e) => - selloutLogger.error(`Error occurred in delete listing event (${src}), Error: ${e.message}`), - ); +onNetPromise(MarketplaceEvents.DELETE_LISTING, async (reqObj, resp) => { + // TODO: Needs a permission check of some sort here eventually + MarketplaceService.handleDeleteListing(reqObj, resp).catch((e) => { + selloutLogger.error( + `Error occurred in delete listing event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ error: true, errorMsg: 'Error occurred in delete listing event' }); + }); }); -onNet(MarketplaceEvents.REPORT_LISTING, async (listing: MarketplaceListing) => { - const src = getSource(); - MarketplaceService.handleReportListing(src, listing).catch((e) => - selloutLogger.error(`Error occurred in report listing event (${src}), Error: ${e.message}`), - ); +onNetPromise(MarketplaceEvents.REPORT_LISTING, async (reqObj, resp) => { + // TODO: Needs a permission check of some sort here eventually + MarketplaceService.handleReportListing(reqObj, resp).catch((e) => { + selloutLogger.error( + `Error occurred in report listing event (${reqObj.source}), Error: ${e.message}`, + ); + resp({ error: true, errorMsg: 'Error occured in report listing event' }); + }); }); diff --git a/resources/server/marketplace/marketplace.db.ts b/resources/server/marketplace/marketplace.db.ts index f449fbe..8888b12 100644 --- a/resources/server/marketplace/marketplace.db.ts +++ b/resources/server/marketplace/marketplace.db.ts @@ -1,5 +1,6 @@ import { pool } from '../db'; -import { MarketplaceListing } from '../../../typings/marketplace'; +import { MarketplaceListing, MarketplaceListingBase } from '../../../typings/marketplace'; +import { ResultSetHeader } from 'mysql2'; export class _MarketplaceDB { async addListing( @@ -7,12 +8,12 @@ export class _MarketplaceDB { username: string, name: string, number: any, - listing: MarketplaceListing, - ): Promise { + listing: MarketplaceListingBase, + ): Promise { const query = 'INSERT INTO npwd_marketplace_listings (identifier, username, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?, ?)'; - await pool.query(query, [ + const [result] = await pool.query(query, [ identifier, username, name, @@ -21,6 +22,10 @@ export class _MarketplaceDB { listing.url, listing.description, ]); + + const resultCast = result as ResultSetHeader; + + return resultCast.insertId; } async fetchListings(): Promise { diff --git a/resources/server/marketplace/marketplace.service.ts b/resources/server/marketplace/marketplace.service.ts index d9d5a7b..b1907c4 100644 --- a/resources/server/marketplace/marketplace.service.ts +++ b/resources/server/marketplace/marketplace.service.ts @@ -1,9 +1,25 @@ import PlayerService from '../players/player.service'; import { selloutLogger } from './marketplace.utils'; import MarketplaceDB, { _MarketplaceDB } from './marketplace.db'; -import { MarketplaceEvents, MarketplaceListing } from '../../../typings/marketplace'; +import { + MarketplaceDeleteDTO, + MarketplaceEvents, + MarketplaceListing, + MarketplaceListingBase, + MarketplaceReportDTO, +} from '../../../typings/marketplace'; import { notesLogger } from '../notes/notes.utils'; import { reportListingToDiscord } from '../discord'; +import { PromiseEventReturnFunc, PromiseRequest } from '../utils/PromiseNetEvents/promise.types'; + +interface HandleAddListingObj { + src: number; + identifier: string; + username: string; + name: string; + number: any; + listing: MarketplaceListingBase; +} class _MarketplaceService { private readonly marketplaceDB: _MarketplaceDB; @@ -14,93 +30,104 @@ class _MarketplaceService { } async handleAddListing( - src: number, - identifier: string, - username: string, - name: string, - number: any, - listing: MarketplaceListing, + { listing, src, identifier, number, name, username }: HandleAddListingObj, + resp: PromiseEventReturnFunc, ): Promise { selloutLogger.debug('Handling add listing, listing:'); - selloutLogger.debug; + selloutLogger.debug(listing); try { - await this.marketplaceDB.addListing(identifier, username, name, number, listing); + const listingId = await this.marketplaceDB.addListing( + identifier, + username, + name, + number, + listing, + ); + // Respond with success to original source + resp({ status: 'ok' }); - emitNet(MarketplaceEvents.ADD_LISTING_SUCCESS, src); - emitNet(MarketplaceEvents.ACTION_RESULT, src, { - message: 'MARKETPLACE_CREATE_LISTING_SUCCESS', - type: 'success', - }); + const returnObj: MarketplaceListing = { + id: listingId, + identifier, + name, + number, + url: listing.url, + username, + description: listing.description, + title: listing.title, + }; + // Broadcast to everyone we are adding a listing + emitNet(MarketplaceEvents.BROADCAST_EVENT, -1, { type: 'ADD', listing: returnObj }); } catch (e) { selloutLogger.error(`Failed to add listing ${e.message}`, { source: src, }); - emitNet(MarketplaceEvents.ACTION_RESULT, src, { - message: 'MARKETPLACE_CREATE_LISTING_FAILED', - type: 'error', - }); + resp({ err: true, errMsg: 'Failed to create listing' }); } } - async handleFetchListings(src: number) { + async handleFetchListings(resp: PromiseEventReturnFunc, src: number) { try { const listings = await this.marketplaceDB.fetchListings(); - emitNet(MarketplaceEvents.SEND_LISTING, src, listings); + resp({ data: listings, status: 'ok' }); } catch (e) { selloutLogger.error(`Failed to fetch listings, ${e.message}`, { source: src, }); + resp({ err: true, errMsg: 'Failed to fetch listings' }); } } - async handleDeleteListing(src: number, listingId: number): Promise { - const identifier = PlayerService.getIdentifier(src); + async handleDeleteListing( + reqObj: PromiseRequest, + resp: PromiseEventReturnFunc, + ): Promise { + const identifier = PlayerService.getIdentifier(reqObj.source); try { - await this.marketplaceDB.deleteListing(listingId, identifier); + await this.marketplaceDB.deleteListing(reqObj.data.id, identifier); - emitNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, src); - emitNet(MarketplaceEvents.ACTION_RESULT, src, { - message: 'MARKETPLACE_DELETE_LISTING_SUCCESS', - type: 'success', - }); + resp({ status: 'ok' }); + + const returnObj: MarketplaceDeleteDTO = { + id: reqObj.data.id, + }; + + emitNet(MarketplaceEvents.BROADCAST_EVENT, -1, { type: 'DELETE', listing: returnObj }); } catch (e) { notesLogger.error(`Error in handleDeleteListing, ${e.message}`); - emitNet(MarketplaceEvents.ACTION_RESULT, src, { - message: 'MARKETPLACE_DELETE_LISTING_FAILED', - type: 'error', - }); + resp({ error: true, errMsg: 'Error in deleting listing' }); } } - async handleReportListing(src: number, listing: MarketplaceListing): Promise { + async handleReportListing( + reqObj: PromiseRequest, + resp: PromiseEventReturnFunc, + ): Promise { try { - const rListing = await this.marketplaceDB.getListing(listing.id); - const reportExists = await this.marketplaceDB.doesReportExist(listing.id, listing.name); + const rListing = await this.marketplaceDB.getListing(reqObj.data.id); + const reportExists = await this.marketplaceDB.doesReportExist( + reqObj.data.id, + rListing.number, + ); + + const reportingPlayer = GetPlayerName(reqObj.source.toString()); - const reportingPlayer = GetPlayerName(src.toString()); if (reportExists) { selloutLogger.error(`This listing has already been reported`); - return emitNet(MarketplaceEvents.ACTION_RESULT, src, { - message: 'MARKETPLACE_REPORT_LISTING_FAILED', - type: 'info', - }); + resp({ error: true, errorMsg: 'Listing already exists' }); } await this.marketplaceDB.reportListing(rListing.id, rListing.name); await reportListingToDiscord(rListing, reportingPlayer); - - emitNet(MarketplaceEvents.ACTION_RESULT, src, { - message: 'MARKETPLACE_REPORT_LISTING_SUCCESS', - type: 'success', - }); } catch (e) { selloutLogger.error(`Failed to report listing ${e.message}`, { - source: src, + source: reqObj.source, }); + resp({ error: true, errorMsg: 'Failed to report listing' }); } } } diff --git a/typings/marketplace.ts b/typings/marketplace.ts index ea6805a..4b41197 100644 --- a/typings/marketplace.ts +++ b/typings/marketplace.ts @@ -12,6 +12,10 @@ export interface MarketplaceListingBase { description: string; } +export interface MarketplaceFetchResp extends MarketplaceActionResp { + data: MarketplaceListing[]; +} + export interface MarketplaceActionResp { err: boolean; errMsg?: string; @@ -36,6 +40,10 @@ export interface MarketplaceDeleteDTO { id: number; } +export interface MarketplaceReportDTO { + id: number; +} + export type MarketPlaceBroadcastData = | { type: 'ADD'; From 10639260e02e59614f0fca10c0ac67e5b295735d Mon Sep 17 00:00:00 2001 From: Christopher Date: Tue, 8 Jun 2021 20:45:12 +0200 Subject: [PATCH 7/8] fix(phone): move FABs outside of AppContent --- .../apps/contacts/components/ContactsApp.tsx | 17 ++++++++++ .../components/views/ContactsPage.tsx | 31 ++----------------- phone/src/apps/notes/NotesApp.tsx | 6 ++-- phone/src/apps/notes/notes.styles.ts | 2 +- 4 files changed, 23 insertions(+), 33 deletions(-) diff --git a/phone/src/apps/contacts/components/ContactsApp.tsx b/phone/src/apps/contacts/components/ContactsApp.tsx index 74e72fc..9d76932 100644 --- a/phone/src/apps/contacts/components/ContactsApp.tsx +++ b/phone/src/apps/contacts/components/ContactsApp.tsx @@ -11,8 +11,18 @@ import { ContactsThemeProvider } from '../providers/ContactsThemeProvider'; import { ContactEvents } from '../../../../../typings/contact'; import { LoadingSpinner } from '../../../ui/components/LoadingSpinner'; +const useStyles = makeStyles((theme: Theme) => ({ + absolute: { + position: 'absolute', + right: theme.spacing(3), + bottom: theme.spacing(2), + }, +})); + export const ContactsApp = () => { const contacts = useApp('CONTACTS'); + const history = useHistory(); + const classes = useStyles(); return ( @@ -24,6 +34,13 @@ export const ContactsApp = () => { + history.push('/contacts/-1')} + className={classes.absolute} + > + + ); diff --git a/phone/src/apps/contacts/components/views/ContactsPage.tsx b/phone/src/apps/contacts/components/views/ContactsPage.tsx index d072f30..204a803 100644 --- a/phone/src/apps/contacts/components/views/ContactsPage.tsx +++ b/phone/src/apps/contacts/components/views/ContactsPage.tsx @@ -1,37 +1,10 @@ import React from 'react'; -import Fab from '@material-ui/core/Fab'; -import PersonAddIcon from '@material-ui/icons/PersonAdd'; -import { useHistory } from 'react-router-dom'; -import { makeStyles, Theme } from '@material-ui/core/styles'; import { ContactList } from '../List/ContactList'; -const useStyles = makeStyles((theme: Theme) => ({ - absolute: { - position: 'absolute', - bottom: theme.spacing(2), - right: theme.spacing(2), - }, - icon: { - color: '#fff', - fontSize: 30, - }, -})); - export const ContactPage = () => { - const history = useHistory(); - - const classes = useStyles(); - return ( - <> +
- history.push('/contacts/-1')} - className={classes.absolute} - > - - - +
); }; diff --git a/phone/src/apps/notes/NotesApp.tsx b/phone/src/apps/notes/NotesApp.tsx index 85d7c50..ddf5b1c 100644 --- a/phone/src/apps/notes/NotesApp.tsx +++ b/phone/src/apps/notes/NotesApp.tsx @@ -30,10 +30,10 @@ export const NotesApp = () => { - - - + + + ); diff --git a/phone/src/apps/notes/notes.styles.ts b/phone/src/apps/notes/notes.styles.ts index 71b03e3..ed1fd52 100644 --- a/phone/src/apps/notes/notes.styles.ts +++ b/phone/src/apps/notes/notes.styles.ts @@ -13,8 +13,8 @@ const useStyles = makeStyles((theme) => ({ }, absolute: { position: 'absolute', - bottom: theme.spacing(2), right: theme.spacing(3), + bottom: theme.spacing(5), }, })); From 5e225ca7360bc2913a36eb83410c6851f3516e84 Mon Sep 17 00:00:00 2001 From: Taso Date: Tue, 8 Jun 2021 16:33:36 -0400 Subject: [PATCH 8/8] tweak(marketplace): Tweak marketplace to match current fetching std --- .../apps/contacts/components/ContactsApp.tsx | 6 +- .../MarketplaceList/ListingActions.tsx | 23 +++--- .../MarketplaceListContainer.tsx | 10 +-- phone/src/apps/marketplace/hooks/state.ts | 8 ++- .../hooks/useMarketplaceActions.ts | 28 ++++++++ .../hooks/useMarketplaceService.ts | 40 +++++------ phone/src/locale/ba.json | 2 +- phone/src/locale/en.json | 2 +- phone/src/locale/es.json | 2 +- phone/src/locale/fr.json | 2 +- phone/src/locale/hu.json | 2 +- phone/src/locale/no.json | 2 +- phone/src/locale/pt.json | 2 +- phone/src/locale/ptbr.json | 2 +- phone/src/locale/sv.json | 2 +- phone/src/locale/tr.json | 2 +- phone/src/os/apps/config/apps.tsx | 11 ++- resources/client/cl_main.ts | 6 -- resources/client/cl_marketplace.ts | 14 +++- .../marketplace/marketplace.controller.ts | 29 +++----- .../server/marketplace/marketplace.service.ts | 70 +++++++++---------- resources/utils/apps.ts | 2 +- typings/marketplace.ts | 17 ++--- 23 files changed, 148 insertions(+), 136 deletions(-) create mode 100644 phone/src/apps/marketplace/hooks/useMarketplaceActions.ts diff --git a/phone/src/apps/contacts/components/ContactsApp.tsx b/phone/src/apps/contacts/components/ContactsApp.tsx index 9d76932..a48d7b4 100644 --- a/phone/src/apps/contacts/components/ContactsApp.tsx +++ b/phone/src/apps/contacts/components/ContactsApp.tsx @@ -3,13 +3,15 @@ import { AppWrapper } from '../../../ui/components'; import { AppTitle } from '../../../ui/components/AppTitle'; import { AppContent } from '../../../ui/components/AppContent'; import { useApp } from '../../../os/apps/hooks/useApps'; -import InjectDebugData from '../../../os/debug/InjectDebugData'; import { Route } from 'react-router-dom'; import ContactsInfoPage from './views/ContactInfo'; import { ContactPage } from './views/ContactsPage'; import { ContactsThemeProvider } from '../providers/ContactsThemeProvider'; -import { ContactEvents } from '../../../../../typings/contact'; import { LoadingSpinner } from '../../../ui/components/LoadingSpinner'; +import { makeStyles } from '@material-ui/core/styles'; +import { useHistory } from 'react-router'; +import { Fab, Theme } from '@material-ui/core'; +import PersonAddIcon from '@material-ui/icons/PersonAdd'; const useStyles = makeStyles((theme: Theme) => ({ absolute: { diff --git a/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx index b37bb05..ef2058e 100644 --- a/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/ListingActions.tsx @@ -1,11 +1,7 @@ import { Box, Tooltip, Button } from '@material-ui/core'; import { makeStyles, Theme } from '@material-ui/core/styles'; import React from 'react'; -import { - MarketplaceActionResp, - MarketplaceEvents, - MarketplaceListing, -} from '../../../../../../typings/marketplace'; +import { MarketplaceEvents, MarketplaceListing } from '../../../../../../typings/marketplace'; import { useSimcard } from '../../../../os/simcard/hooks/useSimcard'; import DeleteIcon from '@material-ui/icons/Delete'; import ReportIcon from '@material-ui/icons/Report'; @@ -17,6 +13,7 @@ import { useHistory } from 'react-router'; import { CallEvents } from '../../../../../../typings/call'; import { fetchNui } from '../../../../utils/fetchNui'; import { useSnackbar } from '../../../../ui/hooks/useSnackbar'; +import { ServerPromiseResp } from '../../../../../../typings/common'; const useStyles = makeStyles((theme: Theme) => ({ icon: { @@ -33,12 +30,12 @@ export const ListingActions: React.FC = ({ children, ...list const { addAlert } = useSnackbar(); const handleDeleteListing = () => { - fetchNui(MarketplaceEvents.DELETE_LISTING, { + fetchNui(MarketplaceEvents.DELETE_LISTING, { id: listing.id, - }).then(({ err, errMsg }) => { - if (err) { + }).then((resp) => { + if (resp.status !== 'ok') { return addAlert({ - message: t(errMsg), + message: t('APPS_MARKETPLACE_DELETE_LISTING_FAILED'), type: 'error', }); } @@ -51,12 +48,12 @@ export const ListingActions: React.FC = ({ children, ...list }; const handleReportListing = () => { - fetchNui(MarketplaceEvents.REPORT_LISTING, { + fetchNui(MarketplaceEvents.REPORT_LISTING, { listingId: listing.id, - }).then(({ err, errMsg }) => { - if (err) { + }).then((resp) => { + if (resp.status !== 'ok') { return addAlert({ - message: t(errMsg), + message: t('APPS_MARKETPLACE_REPORT_LISTING_FAILED'), type: 'error', }); } diff --git a/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx index a64af09..3f3d681 100644 --- a/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx +++ b/phone/src/apps/marketplace/components/MarketplaceList/MarketplaceListContainer.tsx @@ -1,16 +1,10 @@ import React from 'react'; import { MarketplaceList } from './MarketplaceList'; -import { Box, CircularProgress } from '@material-ui/core'; - -const LoadingListings: React.FC = () => ( - - - -); +import { LoadingSpinner } from '../../../../ui/components/LoadingSpinner'; export const MarketplaceListContainer: React.FC = () => { return ( - }> + }> ); diff --git a/phone/src/apps/marketplace/hooks/state.ts b/phone/src/apps/marketplace/hooks/state.ts index c5b2148..82ba787 100644 --- a/phone/src/apps/marketplace/hooks/state.ts +++ b/phone/src/apps/marketplace/hooks/state.ts @@ -1,10 +1,11 @@ -import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil'; +import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil'; import { MarketplaceEvents, MarketplaceFetchResp, MarketplaceListing, } from '../../../../../typings/marketplace'; import { fetchNui } from '../../../utils/fetchNui'; +import { isEnvBrowser } from '../../../utils/misc'; const defaultData: MarketplaceListing[] = [ { @@ -36,9 +37,11 @@ const listingState = atom({ try { return (await fetchNui(MarketplaceEvents.FETCH_LISTING)).data; } catch (e) { - if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) { + if (isEnvBrowser()) { return defaultData; } + console.error(e); + return []; } }, }), @@ -46,3 +49,4 @@ const listingState = atom({ export const useListingValue = () => useRecoilValue(listingState); export const useSetListings = () => useSetRecoilState(listingState); +export const useListings = () => useRecoilState(listingState); diff --git a/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts b/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts new file mode 100644 index 0000000..762c100 --- /dev/null +++ b/phone/src/apps/marketplace/hooks/useMarketplaceActions.ts @@ -0,0 +1,28 @@ +import { useCallback } from 'react'; +import { useSetListings } from './state'; +import { MarketplaceListing } from '../../../../../typings/marketplace'; + +interface MarketplaceActionValues { + deleteListing: (id: number) => void; + addListing: (listing: MarketplaceListing) => void; +} + +export const useMarketplaceActions = (): MarketplaceActionValues => { + const setListings = useSetListings(); + + const deleteListing = useCallback( + (id: number) => { + setListings((curListings) => [...curListings].filter((listing) => listing.id !== id)); + }, + [setListings], + ); + + const addListing = useCallback( + (listing: MarketplaceListing) => { + setListings((curListings) => [...curListings, listing]); + }, + [setListings], + ); + + return { deleteListing, addListing }; +}; diff --git a/phone/src/apps/marketplace/hooks/useMarketplaceService.ts b/phone/src/apps/marketplace/hooks/useMarketplaceService.ts index 5c1f987..83d16f6 100644 --- a/phone/src/apps/marketplace/hooks/useMarketplaceService.ts +++ b/phone/src/apps/marketplace/hooks/useMarketplaceService.ts @@ -1,31 +1,31 @@ import { useNuiEvent } from 'fivem-nui-react-lib'; import { - MarketPlaceBroadcastData, + MarketplaceBroadcastAddDTO, MarketplaceDeleteDTO, MarketplaceEvents, - MarketplaceListing, } from '../../../../../typings/marketplace'; -import { useSetListings } from './state'; +import { useMarketplaceActions } from './useMarketplaceActions'; export const useMarketplaceService = () => { - const setListings = useSetListings(); + const { addListing, deleteListing } = useMarketplaceActions(); - useNuiEvent( - 'SELLOUT', - MarketplaceEvents.BROADCAST_EVENT, - ({ type, listing }) => { - if (type === 'ADD') { - const typeCastListing = listing as MarketplaceListing; - return setListings((curState) => [...curState, typeCastListing]); - } + const addListingHandler = (resp: MarketplaceBroadcastAddDTO) => { + addListing(resp.listing); + }; - if (type === 'DELETE') { - const deleteDTO = listing as MarketplaceDeleteDTO; - return setListings((currVal) => { - const arrayPos = currVal.map((item) => item.id).indexOf(deleteDTO.id); - return [...currVal].splice(arrayPos); - }); - } - }, + const deleteListingHandler = (listing: MarketplaceDeleteDTO) => { + deleteListing(listing.id); + }; + + useNuiEvent( + 'MARKETPLACE', + MarketplaceEvents.BROADCAST_ADD, + addListingHandler, + ); + + useNuiEvent( + 'MARKETPLACE', + MarketplaceEvents.BROADCAST_DELETE, + deleteListingHandler, ); }; diff --git a/phone/src/locale/ba.json b/phone/src/locale/ba.json index 03b83e8..8c9a2de 100644 --- a/phone/src/locale/ba.json +++ b/phone/src/locale/ba.json @@ -14,7 +14,7 @@ "APPS_NOTES": "Bilješke", "APPS_EXAMPLE": "Primjerna Aplikacija", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Market", + "APPS_MARKETPLACE": "Market", "APPS_CAMERA": "Camera", "APPS_DIALER_INCOMING_CALL_TITLE": "Dolazi telefonski poziv", diff --git a/phone/src/locale/en.json b/phone/src/locale/en.json index a59abbf..9b28455 100644 --- a/phone/src/locale/en.json +++ b/phone/src/locale/en.json @@ -59,7 +59,7 @@ "APPS_NOTES": "Notes", "APPS_EXAMPLE": "Example app", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Marketplace", + "APPS_MARKETPLACE": "Marketplace", "APPS_CAMERA": "Camera", "APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "Photo could not be saved :(", diff --git a/phone/src/locale/es.json b/phone/src/locale/es.json index e584923..088e1a4 100644 --- a/phone/src/locale/es.json +++ b/phone/src/locale/es.json @@ -58,7 +58,7 @@ "APPS_NOTES": "Notas", "APPS_EXAMPLE": "App de Ejemplo", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Mercado", + "APPS_MARKETPLACE": "Mercado", "APPS_CAMERA": "Camara", "APPS_DIALER_INCOMING_CALL_TITLE": "Llamada entrante", diff --git a/phone/src/locale/fr.json b/phone/src/locale/fr.json index 9926a80..66d11e2 100644 --- a/phone/src/locale/fr.json +++ b/phone/src/locale/fr.json @@ -59,7 +59,7 @@ "APPS_NOTES": "Notes", "APPS_EXAMPLE": "App test", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Marché", + "APPS_MARKETPLACE": "Marché", "APPS_CAMERA": "Caméra", "APPS_DIALER_INCOMING_CALL_TITLE": "Appel entrant", diff --git a/phone/src/locale/hu.json b/phone/src/locale/hu.json index 7a8b26d..b49092f 100644 --- a/phone/src/locale/hu.json +++ b/phone/src/locale/hu.json @@ -59,7 +59,7 @@ "APPS_NOTES": "Jegyzetek", "APPS_EXAMPLE": "Péla app", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Pia", + "APPS_MARKETPLACE": "Pia", "APPS_CAMERA": "Kamera", "APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "Nem lehet elmenteni a képet :(", diff --git a/phone/src/locale/no.json b/phone/src/locale/no.json index c4ca458..66bdc35 100644 --- a/phone/src/locale/no.json +++ b/phone/src/locale/no.json @@ -52,7 +52,7 @@ "APPS_NOTES": "Notater", "APPS_EXAMPLE": "Example app", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Marked", + "APPS_MARKETPLACE": "Marked", "APPS_CAMERA": "Kamera", "APPS_DIALER_INCOMING_CALL_TITLE": "Innkommende Anrop", diff --git a/phone/src/locale/pt.json b/phone/src/locale/pt.json index 923ce7a..9dfa94f 100644 --- a/phone/src/locale/pt.json +++ b/phone/src/locale/pt.json @@ -14,7 +14,7 @@ "APPS_NOTES": "Notas", "APPS_EXAMPLE": "Aplicativo exemplo", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Market", + "APPS_MARKETPLACE": "Market", "APPS_CAMERA": "Camera", "APPS_DIALER_INCOMING_CALL_TITLE": "Incoming Phone Call", diff --git a/phone/src/locale/ptbr.json b/phone/src/locale/ptbr.json index fb5cd2a..c62a49f 100644 --- a/phone/src/locale/ptbr.json +++ b/phone/src/locale/ptbr.json @@ -59,7 +59,7 @@ "APPS_NOTES": "Notas", "APPS_EXAMPLE": "Aplicativo de exemplo", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Mercado", + "APPS_MARKETPLACE": "Mercado", "APPS_CAMERA": "Camera", "APPS_CAMERA_FAILED_TO_TAKE_PHOTO": "Não foi possível salvar a foto :(", diff --git a/phone/src/locale/sv.json b/phone/src/locale/sv.json index ed8947d..84bf501 100644 --- a/phone/src/locale/sv.json +++ b/phone/src/locale/sv.json @@ -14,7 +14,7 @@ "APPS_NOTES": "Anteckningar", "APPS_EXAMPLE": "Exempel app", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Market", + "APPS_MARKETPLACE": "Market", "APPS_CAMERA": "Camera", "APPS_DIALER_INCOMING_CALL_TITLE": "Incoming Phone Call", diff --git a/phone/src/locale/tr.json b/phone/src/locale/tr.json index 239ff34..9e91a81 100644 --- a/phone/src/locale/tr.json +++ b/phone/src/locale/tr.json @@ -14,7 +14,7 @@ "APPS_NOTES": "Notlar", "APPS_EXAMPLE": "Örnek uygulama", "APPS_TWITTER": "Twitter", - "APPS_SELLOUT": "Market", + "APPS_MARKETPLACE": "Market", "APPS_CAMERA": "Camera", "APPS_DIALER_INCOMING_CALL_TITLE": "Incoming Phone Call", diff --git a/phone/src/os/apps/config/apps.tsx b/phone/src/os/apps/config/apps.tsx index bda8970..e83121f 100644 --- a/phone/src/os/apps/config/apps.tsx +++ b/phone/src/os/apps/config/apps.tsx @@ -127,13 +127,18 @@ export const APPS: IAppConfig[] = [ Route: () => , }, { - id: 'SELLOUT', - nameLocale: 'APPS_SELLOUT', + id: 'MARKETPLACE', + nameLocale: 'APPS_MARKETPLACE', backgroundColor: SELLOUT_APP_PRIMARY_COLOR, color: SELLOUT_APP_ICON_COLOR, path: '/marketplace', Route: () => ( - + ), }, { diff --git a/resources/client/cl_main.ts b/resources/client/cl_main.ts index c88ed79..c850aec 100644 --- a/resources/client/cl_main.ts +++ b/resources/client/cl_main.ts @@ -143,12 +143,6 @@ on(`__cfx_nui:${PhoneEvents.UI_IS_READY}`, (_data: any, cb: Function) => { * NUI Service Callback Registration * * * * * * * * * * * * * */ -RegisterNuiCallbackType(PhoneEvents.OPEN_APP_LISTINGS); -on(`__cfx_nui:${PhoneEvents.OPEN_APP_LISTINGS}`, (data: any, cb: Function) => { - emitNet(MarketplaceEvents.FETCH_LISTING); - cb(); -}); - RegisterNuiCallbackType(PhoneEvents.OPEN_APP_NOTES); on(`__cfx_nui:${PhoneEvents.OPEN_APP_NOTES}`, (data: any, cb: Function) => { emitNet(NotesEvents.FETCH_ALL_NOTES); diff --git a/resources/client/cl_marketplace.ts b/resources/client/cl_marketplace.ts index 3faabcb..048b1c7 100644 --- a/resources/client/cl_marketplace.ts +++ b/resources/client/cl_marketplace.ts @@ -1,4 +1,8 @@ -import { MarketplaceEvents, MarketPlaceBroadcastData } from '../../typings/marketplace'; +import { + MarketplaceBroadcastAddDTO, + MarketplaceDeleteDTO, + MarketplaceEvents, +} from '../../typings/marketplace'; import { RegisterNuiProxy } from './cl_utils'; import { sendMarketplaceEvent } from '../utils/messages'; @@ -8,6 +12,10 @@ RegisterNuiProxy(MarketplaceEvents.ADD_LISTING); RegisterNuiProxy(MarketplaceEvents.DELETE_LISTING); RegisterNuiProxy(MarketplaceEvents.REPORT_LISTING); -onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketPlaceBroadcastData) => { - sendMarketplaceEvent(MarketplaceEvents.BROADCAST_EVENT, broadcastEvent); +onNet(MarketplaceEvents.BROADCAST_ADD, (broadcastEvent: MarketplaceBroadcastAddDTO) => { + sendMarketplaceEvent(MarketplaceEvents.BROADCAST_ADD, broadcastEvent); +}); + +onNet(MarketplaceEvents.BROADCAST_DELETE, (broadcastEvent: MarketplaceDeleteDTO) => { + sendMarketplaceEvent(MarketplaceEvents.BROADCAST_DELETE, broadcastEvent); }); diff --git a/resources/server/marketplace/marketplace.controller.ts b/resources/server/marketplace/marketplace.controller.ts index c3ac565..7dd7059 100644 --- a/resources/server/marketplace/marketplace.controller.ts +++ b/resources/server/marketplace/marketplace.controller.ts @@ -1,40 +1,29 @@ import { MarketplaceEvents, + MarketplaceListing, MarketplaceListingBase, MarketplaceReportDTO, } from '../../../typings/marketplace'; -import PlayerService from '../players/player.service'; import { selloutLogger } from './marketplace.utils'; import MarketplaceService from './marketplace.service'; import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise'; import { MarketplaceDeleteDTO } from '../../../typings/marketplace'; -onNetPromise(MarketplaceEvents.FETCH_LISTING, async (reqObj, resp) => { - MarketplaceService.handleFetchListings(resp, reqObj.source).catch((e) => { +onNetPromise(MarketplaceEvents.FETCH_LISTING, async (reqObj, resp) => { + MarketplaceService.handleFetchListings(reqObj, resp).catch((e) => { selloutLogger.error( `Error occurred in fetch listing event (${reqObj.source}), Error: ${e.message}`, ); - resp({ error: true, errorMsg: '`Error occurred in fetch listing event' }); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); }); }); -onNetPromise(MarketplaceEvents.ADD_LISTING, async (reqObj, resp) => { - const player = PlayerService.getPlayer(reqObj.source); - MarketplaceService.handleAddListing( - { - src: reqObj.source, - name: player.getName(), - username: player.username, - number: player.getPhoneNumber(), - listing: reqObj.data, - identifier: player.getIdentifier(), - }, - resp, - ).catch((e) => { +onNetPromise(MarketplaceEvents.ADD_LISTING, async (reqObj, resp) => { + MarketplaceService.handleAddListing(reqObj, resp).catch((e) => { selloutLogger.error( `Error occurred in add listing event (${reqObj.source}), Error: ${e.message}`, ); - resp({ error: true, errorMsg: 'Error occurred in add listing event' }); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); }); }); @@ -44,7 +33,7 @@ onNetPromise(MarketplaceEvents.DELETE_LISTING, async (reqO selloutLogger.error( `Error occurred in delete listing event (${reqObj.source}), Error: ${e.message}`, ); - resp({ error: true, errorMsg: 'Error occurred in delete listing event' }); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); }); }); @@ -54,6 +43,6 @@ onNetPromise(MarketplaceEvents.REPORT_LISTING, async (reqO selloutLogger.error( `Error occurred in report listing event (${reqObj.source}), Error: ${e.message}`, ); - resp({ error: true, errorMsg: 'Error occured in report listing event' }); + resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' }); }); }); diff --git a/resources/server/marketplace/marketplace.service.ts b/resources/server/marketplace/marketplace.service.ts index b1907c4..0e03149 100644 --- a/resources/server/marketplace/marketplace.service.ts +++ b/resources/server/marketplace/marketplace.service.ts @@ -10,16 +10,7 @@ import { } from '../../../typings/marketplace'; import { notesLogger } from '../notes/notes.utils'; import { reportListingToDiscord } from '../discord'; -import { PromiseEventReturnFunc, PromiseRequest } from '../utils/PromiseNetEvents/promise.types'; - -interface HandleAddListingObj { - src: number; - identifier: string; - username: string; - name: string; - number: any; - listing: MarketplaceListingBase; -} +import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types'; class _MarketplaceService { private readonly marketplaceDB: _MarketplaceDB; @@ -30,60 +21,65 @@ class _MarketplaceService { } async handleAddListing( - { listing, src, identifier, number, name, username }: HandleAddListingObj, - resp: PromiseEventReturnFunc, + reqObj: PromiseRequest, + resp: PromiseEventResp, ): Promise { selloutLogger.debug('Handling add listing, listing:'); - selloutLogger.debug(listing); + selloutLogger.debug(reqObj.data); + + const player = PlayerService.getPlayer(reqObj.source); try { const listingId = await this.marketplaceDB.addListing( - identifier, - username, - name, - number, - listing, + player.getIdentifier(), + player.username, + player.getName(), + player.getPhoneNumber(), + reqObj.data, ); // Respond with success to original source resp({ status: 'ok' }); const returnObj: MarketplaceListing = { id: listingId, - identifier, - name, - number, - url: listing.url, - username, - description: listing.description, - title: listing.title, + identifier: player.getIdentifier(), + name: player.getName(), + number: player.getPhoneNumber(), + url: reqObj.data.url, + username: player.username, + description: reqObj.data.description, + title: reqObj.data.title, }; // Broadcast to everyone we are adding a listing - emitNet(MarketplaceEvents.BROADCAST_EVENT, -1, { type: 'ADD', listing: returnObj }); + emitNet(MarketplaceEvents.BROADCAST_ADD, -1, { type: 'ADD', listing: returnObj }); } catch (e) { selloutLogger.error(`Failed to add listing ${e.message}`, { - source: src, + source: reqObj.source, }); - resp({ err: true, errMsg: 'Failed to create listing' }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); } } - async handleFetchListings(resp: PromiseEventReturnFunc, src: number) { + async handleFetchListings( + req: PromiseRequest, + resp: PromiseEventResp, + ) { try { const listings = await this.marketplaceDB.fetchListings(); resp({ data: listings, status: 'ok' }); } catch (e) { selloutLogger.error(`Failed to fetch listings, ${e.message}`, { - source: src, + source: req.source, }); - resp({ err: true, errMsg: 'Failed to fetch listings' }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); } } async handleDeleteListing( reqObj: PromiseRequest, - resp: PromiseEventReturnFunc, + resp: PromiseEventResp, ): Promise { const identifier = PlayerService.getIdentifier(reqObj.source); try { @@ -95,17 +91,17 @@ class _MarketplaceService { id: reqObj.data.id, }; - emitNet(MarketplaceEvents.BROADCAST_EVENT, -1, { type: 'DELETE', listing: returnObj }); + emitNet(MarketplaceEvents.BROADCAST_DELETE, -1, returnObj); } catch (e) { notesLogger.error(`Error in handleDeleteListing, ${e.message}`); - resp({ error: true, errMsg: 'Error in deleting listing' }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); } } async handleReportListing( reqObj: PromiseRequest, - resp: PromiseEventReturnFunc, + resp: PromiseEventResp, ): Promise { try { const rListing = await this.marketplaceDB.getListing(reqObj.data.id); @@ -118,7 +114,7 @@ class _MarketplaceService { if (reportExists) { selloutLogger.error(`This listing has already been reported`); - resp({ error: true, errorMsg: 'Listing already exists' }); + resp({ status: 'error', errorMsg: 'REPORT_EXISTS' }); } await this.marketplaceDB.reportListing(rListing.id, rListing.name); @@ -127,7 +123,7 @@ class _MarketplaceService { selloutLogger.error(`Failed to report listing ${e.message}`, { source: reqObj.source, }); - resp({ error: true, errorMsg: 'Failed to report listing' }); + resp({ status: 'error', errorMsg: 'DB_ERROR' }); } } } diff --git a/resources/utils/apps.ts b/resources/utils/apps.ts index dbc326d..2f5295e 100644 --- a/resources/utils/apps.ts +++ b/resources/utils/apps.ts @@ -3,7 +3,7 @@ export default { MATCH: 'MATCH', MESSAGES: 'MESSAGES', NOTES: 'NOTES', - MARKETPLACE: 'SELLOUT', + MARKETPLACE: 'MARKETPLACE', CONTACTS: 'CONTACTS', CAMERA: 'CAMERA', }; diff --git a/typings/marketplace.ts b/typings/marketplace.ts index 4b41197..f70064b 100644 --- a/typings/marketplace.ts +++ b/typings/marketplace.ts @@ -33,7 +33,12 @@ export enum MarketplaceEvents { REPORT_LISTING_SUCCESS = 'npwd:reportListingSuccess', REPORT_LISTING_SUCESS = 'npwd:reportListingFailed', SEND_ALERT = 'nwpd:sendListingAlert', - BROADCAST_EVENT = 'npwd:sendMarketplaceBroadcast', + BROADCAST_ADD = 'npwd:sendMarketplaceBroadcastAdd', + BROADCAST_DELETE = 'npwd:sendMarketplaceBroadcastDelete', +} + +export interface MarketplaceBroadcastAddDTO { + listing: MarketplaceListing; } export interface MarketplaceDeleteDTO { @@ -43,13 +48,3 @@ export interface MarketplaceDeleteDTO { export interface MarketplaceReportDTO { id: number; } - -export type MarketPlaceBroadcastData = - | { - type: 'ADD'; - listing: MarketplaceListing; - } - | { - type: 'DELETE'; - listing: MarketplaceDeleteDTO; - };