diff --git a/src/api/stakeholders.js b/src/api/stakeholders.js index cdfafb3b9..a0bfe2ee4 100644 --- a/src/api/stakeholders.js +++ b/src/api/stakeholders.js @@ -1,7 +1,7 @@ import { handleResponse, handleError, - getOrganization, + // getOrganization, getOrganizationId, } from './apiUtils'; import { session } from '../models/auth'; @@ -9,40 +9,12 @@ import { session } from '../models/auth'; const STAKEHOLDER_API = process.env.REACT_APP_STAKEHOLDER_API_ROOT; export default { - getStakeholderById(id) { + getStakeholders(id, { offset, rowsPerPage, orderBy, order, filter }) { const orgId = getOrganizationId(); - let stakeholderQuery = ''; - if (Number(orgId)) { - stakeholderQuery = `${STAKEHOLDER_API}/${orgId}`; - } else if (id) { - stakeholderQuery = `${STAKEHOLDER_API}?id=${id}`; - } else { - stakeholderQuery = `${STAKEHOLDER_API}`; - } - - console.log('getStakeholderById ---->', stakeholderQuery); - - return fetch(stakeholderQuery, { - method: 'GET', - headers: { - 'content-type': 'application/json', - Authorization: session.token, - }, - }) - .then(handleResponse) - .catch(handleError); - }, - - getStakeholders({ - offset, - rowsPerPage, - orderBy = 'id', - order = 'desc', - filter, - }) { - const where = filter.getWhereObj ? filter.getWhereObj() : {}; - const stakeholderFilter = { - where: { ...where, active: true }, + const where = filter.getWhereObj(); + console.log('where', where); + const lbFilter = { + where, order: [`${orderBy} ${order}`], limit: rowsPerPage, offset, @@ -52,28 +24,27 @@ export default { orgName: true, firstName: true, lastName: true, - imageUrl: true, email: true, phone: true, website: true, logoUrl: true, - mapName: true, + imageUrl: true, + map: true, stakeholder_uuid: true, - organizationId: true, }, }; - const query = `${STAKEHOLDER_API}/stakeholder?filter=${JSON.stringify( - stakeholderFilter, - )}`; - console.log( - 'getStakeholders ---> ', - query, - 'org ---> ', - getOrganizationId(), - ); + let query = ''; + if (!id && orgId && Number(orgId)) { + query = `${STAKEHOLDER_API}/${orgId}?filter=${JSON.stringify(lbFilter)}`; + // } else if (id) { + // query = `${STAKEHOLDER_API}/${id}?filter=${JSON.stringify(lbFilter)}`; + } else { + query = `${STAKEHOLDER_API}?filter=${JSON.stringify(lbFilter)}`; + } return fetch(query, { + method: 'GET', headers: { 'content-type': 'application/json', Authorization: session.token, @@ -83,14 +54,67 @@ export default { .catch(handleError); }, - updateStakeholder(stakeholderUpdate) { - if (stakeholderUpdate.organizationId === 'null') { - stakeholderUpdate = { ...stakeholderUpdate, organizationId: null }; + getUnlinkedStakeholders(id, abortController) { + const orgId = getOrganizationId(); + + console.log('id orgId', id, orgId); + + let query = ''; + if (!id && orgId && Number(orgId)) { + query = `${STAKEHOLDER_API}/links/${orgId}`; + } else if (id) { + query = `${STAKEHOLDER_API}/links/${id}`; + } else { + query = `${STAKEHOLDER_API}/links`; + } + + console.log('getUnlinkedStakeholders ---->', query); + + return fetch(query, { + method: 'GET', + headers: { + 'content-type': 'application/json', + Authorization: session.token, + }, + signal: abortController?.signal, + }) + .then(handleResponse) + .catch(handleError); + }, + + updateLinks(id, stakeholdersData) { + const orgId = getOrganizationId(); + + console.log('id orgId', id, orgId); + + let query = ''; + if (orgId && Number(orgId)) { + query = `${STAKEHOLDER_API}/links/${orgId}`; + } else if (id) { + query = `${STAKEHOLDER_API}/links/${id}`; + } else { + query = `${STAKEHOLDER_API}/links`; } - const { id } = stakeholderUpdate; - const stakeholderQuery = `${STAKEHOLDER_API}/${getOrganization()}stakeholder/${id}`; - return fetch(stakeholderQuery, { + console.log('updateLinks ---->', query); + + return fetch(query, { + method: 'PATCH', + headers: { + 'content-type': 'application/json', + Authorization: session.token, + }, + body: JSON.stringify(stakeholdersData), + }) + .then(handleResponse) + .catch(handleError); + }, + + updateStakeholder(stakeholderUpdate) { + console.log('org ---> ', getOrganizationId()); + const query = `${STAKEHOLDER_API}/${getOrganizationId()}`; + + return fetch(query, { method: 'PATCH', headers: { 'content-type': 'application/json', @@ -101,4 +125,25 @@ export default { .then(handleResponse) .catch(handleError); }, + + createStakeholder(stakeholderData) { + console.log('org ---> ', getOrganizationId()); + let query = `${STAKEHOLDER_API}`; + const orgId = getOrganizationId(); + + if (orgId) { + query = `${STAKEHOLDER_API}/${orgId}`; + } + + return fetch(query, { + method: 'POST', + headers: { + 'content-type': 'application/json', + Authorization: session.token, + }, + body: JSON.stringify(stakeholderData), + }) + .then(handleResponse) + .catch(handleError); + }, }; diff --git a/src/components/FilterTop.js b/src/components/FilterTop.js index 667014d5a..6de30d575 100644 --- a/src/components/FilterTop.js +++ b/src/components/FilterTop.js @@ -1,9 +1,6 @@ import React, { useState, useContext } from 'react'; import { withStyles } from '@material-ui/core/styles'; -import Grid from '@material-ui/core/Grid'; -import Button from '@material-ui/core/Button'; -import TextField from '@material-ui/core/TextField'; -import MenuItem from '@material-ui/core/MenuItem'; +import { Grid, Button, TextField, MenuItem } from '@material-ui/core'; import Autocomplete from '@material-ui/lab/Autocomplete'; import SelectOrg from './common/SelectOrg'; import FilterModel, { diff --git a/src/components/Stakeholders/Add.js b/src/components/Stakeholders/Add.js index 7b40acd06..b623531c9 100644 --- a/src/components/Stakeholders/Add.js +++ b/src/components/Stakeholders/Add.js @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useContext } from 'react'; import { Button, Dialog, @@ -7,11 +7,29 @@ import { DialogActions, TextField, FormControl, + MenuItem, } from '@material-ui/core'; +import { StakeholdersContext } from 'context/StakeholdersContext'; -function AddStakeholder({ dispatch }) { +function AddStakeholder() { + const { createStakeholder } = useContext(StakeholdersContext); const [open, setOpen] = useState(false); - const [data, setData] = useState(); + const [data, setData] = useState({}); + + const defaultTypeList = [ + { + name: 'Not set', + value: undefined, + }, + { + name: 'Organization', + value: 'Organization', + }, + { + name: 'Person', + value: 'Person', + }, + ]; const openModal = () => { setOpen(true); @@ -22,12 +40,12 @@ function AddStakeholder({ dispatch }) { setOpen(false); }; - const handleDataChange = (e) => { + const handleChange = (e) => { setData({ ...data, [e.target.name]: e.target.value }); }; const submit = () => { - dispatch.createStakeholder(data); + createStakeholder(data); }; return ( @@ -40,45 +58,87 @@ function AddStakeholder({ dispatch }) { handleChange(e)} + > + {defaultTypeList.map((type) => ( + + {type.name} + + ))} + + + + + diff --git a/src/components/Stakeholders/Filter.js b/src/components/Stakeholders/Filter.js index f571c9f08..c8f91958f 100644 --- a/src/components/Stakeholders/Filter.js +++ b/src/components/Stakeholders/Filter.js @@ -8,8 +8,15 @@ import { DialogActions, TextField, FormControl, + MenuItem, } from '@material-ui/core'; import FilterIcon from '@material-ui/icons/FilterList'; +// import FilterModel from '../../models/FilterStakeholder'; +import FilterModel, { + ALL_ORGANIZATIONS, + ORGANIZATION_NOT_SET, +} from '../../models/FilterStakeholder'; +import { AppContext } from '../../context/AppContext'; import { StakeholdersContext } from '../../context/StakeholdersContext'; const useStyles = makeStyles({ @@ -21,6 +28,7 @@ const useStyles = makeStyles({ }, flex: { display: 'flex', + flex: 'wrap', }, ml: { marginLeft: '24px', @@ -28,35 +36,86 @@ const useStyles = makeStyles({ }); function Filter() { - const { filter, updateFilter } = useContext(StakeholdersContext); - const classes = useStyles(); + const { orgList, userHasOrg } = useContext(AppContext); + + const { filter, updateFilter, initialFilterState } = useContext( + StakeholdersContext, + ); + const [organizationId, setOrganizationId] = useState( + filter.id || ALL_ORGANIZATIONS, + ); + const [search, setSearch] = useState(''); + const [formData, setFormData] = useState(initialFilterState); const [open, setOpen] = useState(false); - const [options, setOptions] = useState({}); const close = () => { - setOptions(filter); + setFormData(filter); setOpen(false); }; - const updateOptions = (e) => { - setOptions({ ...options, [e.target.name]: e.target.value }); + const handleChanges = (e) => { + // console.log('handleChanges', e.target); + setFormData({ ...formData, [e.target.name]: e.target.value }); }; const resetFilters = () => { - setOptions({}); - updateFilter({}); + setFormData({}); + const resetFilter = new FilterModel(initialFilterState); + updateFilter(resetFilter); }; const applyFilters = () => { - updateFilter({ ...filter, ...options }); + const resetFilter = new FilterModel({ + ...filter, + ...formData, + }); + updateFilter(resetFilter); setOpen(false); }; const applySearch = (e) => { - updateFilter({ ...filter, search: e.target.value }); + setSearch(e.target.value); + const resetFilter = new FilterModel({ ...filter, search: e.target.value }); + updateFilter(resetFilter); }; + const defaultOrgList = userHasOrg + ? [ + { + id: ALL_ORGANIZATIONS, + name: 'All', + value: 'All', + }, + ] + : [ + { + id: ALL_ORGANIZATIONS, + name: 'All', + value: 'All', + }, + { + id: ORGANIZATION_NOT_SET, + name: 'Not set', + value: null, + }, + ]; + + const defaultTypeList = [ + { + name: 'Not set', + value: undefined, + }, + { + name: 'Organization', + value: 'Organization', + }, + { + name: 'Person', + value: 'Person', + }, + ]; + return ( <> @@ -89,43 +148,92 @@ function Filter() { label="ID" variant="outlined" name="id" - onChange={updateOptions} - value={options?.id || ''} + onChange={handleChanges} + value={formData?.id || ''} /> handleChanges(e)} + > + {defaultTypeList.map((type) => ( + + {type.name} + + ))} + + setOrganizationId(e.target.value)} + > + {[...defaultOrgList, ...orgList].map((org) => ( + + {org.name} + + ))} + + {/* + + */} diff --git a/src/components/Stakeholders/StakeholderDetail/Groups.js b/src/components/Stakeholders/StakeholderDetail/Groups.js index b09790706..7e2dac43f 100644 --- a/src/components/Stakeholders/StakeholderDetail/Groups.js +++ b/src/components/Stakeholders/StakeholderDetail/Groups.js @@ -1,10 +1,11 @@ -import React, { useContext } from 'react'; +import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; -import { Button, Grid, List, Typography } from '@material-ui/core'; -import { StakeholdersContext } from '../../../context/StakeholdersContext'; +import { Grid, List, Typography } from '@material-ui/core'; +// import { StakeholdersContext } from '../../../context/StakeholdersContext'; import AdminIcon from '@material-ui/icons/SupervisorAccount'; import GrowerIcon from '@material-ui/icons/NaturePeople'; import StakeholderList from './List'; +import LinkStakeholder from './LinkStakeholder'; const useStyles = makeStyles({ flex: { @@ -32,9 +33,9 @@ const useStyles = makeStyles({ }); function StakeholderGroups({ data, render, tall }) { - console.log('StakeholderGroups data, render tall', data, render, tall); + // console.log('StakeholderGroups data, render tall', data, render, tall); const classes = useStyles(); - const linkStakeholder = useContext(StakeholdersContext); + // const { linkStakeholder } = useContext(StakeholdersContext); const stakeholders = { children: { label: 'Children', icon: '' }, @@ -43,9 +44,9 @@ function StakeholderGroups({ data, render, tall }) { growers: { label: 'Growers', icon: }, }; - const handleLink = (type, id) => { - linkStakeholder({ type, id }); - }; + // const handleLink = (type, id) => { + // linkStakeholder({ type, id }); + // }; return ( <> @@ -58,14 +59,11 @@ function StakeholderGroups({ data, render, tall }) { {stakeholders[type]?.label} ({data[type]?.length || 0}) - + {type === 'growers' || type === 'users' ? ( + 'Linking coming soon' + ) : ( + + )} ( ))} diff --git a/src/components/Stakeholders/StakeholderDetail/Header.js b/src/components/Stakeholders/StakeholderDetail/Header.js index 1ff01476f..f23b6c945 100644 --- a/src/components/Stakeholders/StakeholderDetail/Header.js +++ b/src/components/Stakeholders/StakeholderDetail/Header.js @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useState, useContext } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Button, TextField, Grid, Link, Typography } from '@material-ui/core'; import PersonIcon from '@material-ui/icons/Person'; @@ -8,6 +8,7 @@ import MapIcon from '@material-ui/icons/Map'; import WebsiteIcon from '@material-ui/icons/Language'; import IdIcon from '@material-ui/icons/Money'; import TypeIcon from '@material-ui/icons/Category'; +import { StakeholdersContext } from '../../../context/StakeholdersContext'; const useStyles = makeStyles({ logoLg: { @@ -43,6 +44,7 @@ const useStyles = makeStyles({ }); export default function DialogHeader({ data }) { + const { updateStakeholder } = useContext(StakeholdersContext); const [isEditing, setIsEditing] = useState(false); const [details, setDetails] = useState({ ...data }); @@ -50,7 +52,6 @@ export default function DialogHeader({ data }) { const handleEdit = (e) => { setDetails({ ...details, [e.target.name]: e.target.value }); - console.log(details); }; const handleCancel = () => { @@ -60,7 +61,7 @@ export default function DialogHeader({ data }) { const handleSave = () => { setIsEditing(false); - console.log(details); + updateStakeholder(details); }; return ( @@ -94,7 +95,13 @@ export default function DialogHeader({ data }) { )} ) : ( - + {isEditing ? ( { + const abortController = new AbortController(); + if (unlinkedStakeholders.length === 0) { + getUnlinkedStakeholders(id, { signal: abortController.signal }); + } + return () => abortController.abort(); + }, []); + + useEffect(() => { + // console.log('unlinkedStakeholders', id, type, unlinkedStakeholders.length); + // const filtered = unlinkedStakeholders.filter((s) => { + // return s.type === type; + // }); + setFilteredStakeholders(unlinkedStakeholders); + }, [unlinkedStakeholders]); + + const openModal = () => { + setOpen(true); + }; + + const closeModal = () => { + // setFilteredStakeholders([]); + setOpen(false); + }; + + // const submit = () => { + // updateLinks(id, relation, data.id, linked); + // }; + + return ( + <> + + + Link Stakeholder + + + {filteredStakeholders && + filteredStakeholders.map((stakeholder) => { + return ( + + {/* handleChange(stakeholder.id, e)} + value={data.linked} + /> */} + + ); + })} + + + + {/* */} + + + + + ); +} + +export default LinkStakeholder; diff --git a/src/components/Stakeholders/StakeholderDetail/List.js b/src/components/Stakeholders/StakeholderDetail/List.js index f2c8b8c29..8a9649b11 100644 --- a/src/components/Stakeholders/StakeholderDetail/List.js +++ b/src/components/Stakeholders/StakeholderDetail/List.js @@ -1,7 +1,8 @@ -import React, { useContext } from 'react'; +import React, { useState, useContext } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Paper, IconButton, Grid, ListItem } from '@material-ui/core'; import UnlinkIcon from '@material-ui/icons/LinkOff'; +import LinkIcon from '@material-ui/icons/Link'; import { StakeholdersContext } from '../../../context/StakeholdersContext'; import UserListItem from './UserListItem'; import GrowerListItem from './GrowerListItem'; @@ -15,12 +16,23 @@ const useStyles = makeStyles({ }, }); -function StakeholderList({ data, type }) { +function StakeholderList({ id, data, type, linked }) { const classes = useStyles(); - const unlinkStakeholder = useContext(StakeholdersContext); + const [isLinked, setIsLinked] = useState(linked); + const { updateLinks } = useContext(StakeholdersContext); - const handleUnlink = (type, id) => { - unlinkStakeholder({ type, id }); + // const handleUnlink = (type, id) => { + // unlinkStakeholder({ type, id }); + // }; + + const handleChange = (e, stakeholder) => { + setIsLinked(!isLinked); + updateLinks(id, { + id: stakeholder.id, + type, + linked: !linked, + data: stakeholder, + }); }; return ( @@ -33,18 +45,24 @@ function StakeholderList({ data, type }) { direction="row" > - {type === 'users' ? ( + {type === 'User' ? ( - ) : type === 'growers' ? ( + ) : type === 'Person' ? ( ) : ( )} - handleUnlink(type, data.id)}> - - + {isLinked ? ( + handleChange(e, data)}> + + + ) : ( + handleChange(e, data)}> + + + )} diff --git a/src/components/Stakeholders/StakeholderDetail/ParentChildListItem.js b/src/components/Stakeholders/StakeholderDetail/ParentChildListItem.js index 75104d0a8..2a9bf2912 100644 --- a/src/components/Stakeholders/StakeholderDetail/ParentChildListItem.js +++ b/src/components/Stakeholders/StakeholderDetail/ParentChildListItem.js @@ -1,6 +1,7 @@ import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import { Grid, Typography } from '@material-ui/core'; +import PersonIcon from '@material-ui/icons/Person'; import IdIcon from '@material-ui/icons/Money'; const useStyles = makeStyles({ @@ -23,10 +24,21 @@ export default function ParentChildListItem({ data }) { return ( <> - + {data.type === 'Organization' ? ( + + ) : ( + + )} - {data.org_name} + + {data.org_name + ? data.org_name + : `${data.first_name} ${data.last_name}`} + diff --git a/src/components/Stakeholders/StakeholderDetail/index.js b/src/components/Stakeholders/StakeholderDetail/index.js index d76ebbc6e..ce1ffec00 100644 --- a/src/components/Stakeholders/StakeholderDetail/index.js +++ b/src/components/Stakeholders/StakeholderDetail/index.js @@ -66,7 +66,7 @@ export default function StakeholderDetail({ row, columns, child }) { {col.value === 'name' && row.type === 'Organization' && ( <> {row.org_name} diff --git a/src/components/Stakeholders/Table.js b/src/components/Stakeholders/Table.js index 254b7bb37..9e6cebd99 100644 --- a/src/components/Stakeholders/Table.js +++ b/src/components/Stakeholders/Table.js @@ -16,7 +16,7 @@ import { StakeholdersContext } from '../../context/StakeholdersContext'; function StakeholderTable() { const { stakeholders, - stakeholder, + // stakeholder, columns, page, rowsPerPage, @@ -29,11 +29,6 @@ function StakeholderTable() { // getStakeholders, } = useContext(StakeholdersContext); - // useEffect(() => { - // // getStakeholders(); - // getStakeholder('792a4eee-8e18-4750-a56f-91bdec383aa6'); - // }, []); - const handleRowsPerPageChange = (e) => { setRowsPerPage(e.target.value); }; @@ -42,8 +37,9 @@ function StakeholderTable() { setPage(page); }; - const handleSort = (col) => { - sort(col); + const handleSort = (col, order) => { + console.log('sort col', { col, order }); + sort({ col, order }); }; return ( @@ -55,11 +51,11 @@ function StakeholderTable() { {columns.map((col) => ( handleSort(col.value)} + onClick={() => handleSort(col.value, !order)} > {col.label} @@ -68,7 +64,7 @@ function StakeholderTable() { - {stakeholder.map((stakeholder) => ( + {stakeholders.map((stakeholder) => ( {/* Main stakeholder */} diff --git a/src/context/StakeholdersContext.js b/src/context/StakeholdersContext.js index 1c30f2fc2..ee75c56ea 100644 --- a/src/context/StakeholdersContext.js +++ b/src/context/StakeholdersContext.js @@ -2,17 +2,20 @@ import React, { useState, useEffect, createContext } from 'react'; import FilterStakeholder from '../models/FilterStakeholder'; import api from '../api/stakeholders'; import * as loglevel from 'loglevel'; +// import { getOrganizationId } from 'api/apiUtils'; const log = loglevel.getLogger('../context/StakeholderContext'); export const StakeholdersContext = createContext({ stakeholder: {}, stakeholders: [], + unlinkedStakeholders: [], display: [], columns: [], page: 0, rowsPerPage: 1, - filters: {}, + filter: new FilterStakeholder(), + initialFilterState: {}, orderBy: undefined, order: true, setPage: () => {}, @@ -27,8 +30,9 @@ export const StakeholdersContext = createContext({ getStakeholder: () => {}, getStakeholders: () => {}, createStakeholder: () => {}, - linkStakeholder: () => {}, - unlinkStakeholder: () => {}, + updateStakeholder: () => {}, + getUnlinkedStakeholders: () => {}, + updateLinks: () => {}, }); const initialFilterState = { @@ -42,17 +46,17 @@ const initialFilterState = { phone: null, website: null, logoUrl: null, - mapName: null, + map: null, stakeholder_uuid: null, }; export function StakeholdersProvider(props) { const [stakeholders, setStakeholders] = useState([]); - const [stakeholder, setStakeholder] = useState([]); + const [unlinkedStakeholders, setUnlinkedStakeholders] = useState([]); const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(1); - const [order, setOrder] = useState(true); - const [orderBy, setOrderBy] = useState('asc'); + const [order, setOrder] = useState('asc'); + const [orderBy, setOrderBy] = useState(undefined); const [filter, setFilter] = useState( new FilterStakeholder(initialFilterState), ); @@ -67,8 +71,7 @@ export function StakeholdersProvider(props) { // const [totalGrowerCount, setTotalGrowerCount] = useState(null); useEffect(() => { - // getStakeholders(); // don't want to run this every time, adjust to call it only when trying to link an org - getStakeholder(); + getStakeholders(); }, [filter, page, rowsPerPage]); useEffect(() => { @@ -77,48 +80,9 @@ export function StakeholdersProvider(props) { // EVENT HANDLERS - const getStakeholders = async () => { - log.debug('load stakeholders'); - const data = await api.getStakeholders({ - offset: page * rowsPerPage, - rowsPerPage, - orderBy, - order, - filter, - }); - console.log('getStakeholders DATA', data); - setStakeholders(data.stakeholders); - }; - - const getStakeholder = async (id) => { - log.debug('load stakeholder by uuid', id); - let data; - // compare both id and uuid while transitioning - // can remove id comparison when all stakeholders use uuid - data = stakeholders.find((p) => p.id === id || p.id === id); - if (!data) { - data = await api.getStakeholderById(id); - console.log('getStakeholder api DATA', data); - } - setStakeholder(data.stakeholders); - }; - - const updateStakeholder = async (payload) => { - await api.updateStakeholder(payload); - const updatedStakeholder = await api.getStakeholder(payload.id); - const index = stakeholders.findIndex((p) => p.id === updatedStakeholder.id); - if (index >= 0) { - const stakeholdersData = Object.assign([], stakeholders, { - [index]: updatedStakeholder, - }); - setStakeholders(stakeholdersData); - } - }; - const setDisplay = () => { let display; - - // sorting + // orderBy => field & order => true = asc/ false = desc if (orderBy) { if (order) { display = stakeholders @@ -133,57 +97,73 @@ export function StakeholdersProvider(props) { display = stakeholders; } - // pagination - display = display.slice(page * rowsPerPage, (page + 1) * rowsPerPage); - setStakeholders(display); }; const sort = (payload) => { - this.setSortBy(payload); - this.setSortAsc(); - this.setDisplay(); + console.log('sort', payload); + setOrderBy(payload.col); + setOrder(payload.order); + setDisplay(); }; - const updateFilter = async () => { + + // call w/ or w/o an id, it will default to the organization id or null + const getStakeholders = async (id = null) => { + log.debug('load stakeholders', id); + let data; + // compare both id and uuid while transitioning + // can remove id comparison when all stakeholders use uuid + data = stakeholders.find((p) => p.id === id || p.id === id); + if (!data) { + data = await api.getStakeholders(id, { + offset: page * rowsPerPage, + rowsPerPage, + orderBy, + order, + filter, + }); + } + setStakeholders(data.stakeholders); + }; + + const updateFilter = async (filter) => { setPage(0); setFilter(filter); - // fetch api - // set data - // set display + }; + + const updateStakeholder = async (payload) => { + await api.updateStakeholder(payload); + getStakeholders(); }; const createStakeholder = async (payload) => { - console.log(payload); - // send api request + console.log('create', payload); + await api.createStakeholder(payload); + getStakeholders(); }; - const linkStakeholder = async (payload) => { - console.log('link'); - console.log({ - type: payload.type, - id: payload.id, - }); - updateStakeholder(payload); - //determine which request to make (growers, users, etc) - //get stakeholders - //when one's selected - //add id to the array of that type on the current stakeholder & update the stakeholder + const getUnlinkedStakeholders = async (id) => { + const unlinked = await api.getUnlinkedStakeholders(id); + setUnlinkedStakeholders(unlinked.stakeholders); }; - const unlinkStakeholder = async (payload) => { - console.log('unlink'); - console.log({ type: payload.type, id: payload.id }); - updateStakeholder(payload); - //remove the id from the type array in the current stakeholder + const updateLinks = async (stakeholder_id, payload) => { + const { id, type, linked, data } = payload; + console.log('update links', stakeholder_id, id, type, linked, data); + // update parent_id or child_id fields + await api.updateLinks(stakeholder_id, payload); + // get updated list of unlinked + getUnlinkedStakeholders(); }; const value = { - stakeholder, stakeholders, + unlinkedStakeholders, columns, page, rowsPerPage, filter, + initialFilterState, orderBy, order, setPage, @@ -195,11 +175,12 @@ export function StakeholdersProvider(props) { setDisplay, sort, updateFilter, - getStakeholder, + // getStakeholder, getStakeholders, createStakeholder, - linkStakeholder, - unlinkStakeholder, + updateStakeholder, + getUnlinkedStakeholders, + updateLinks, }; return ( diff --git a/src/models/FilterStakeholder.js b/src/models/FilterStakeholder.js index 232e41dd1..8eaf35aaa 100644 --- a/src/models/FilterStakeholder.js +++ b/src/models/FilterStakeholder.js @@ -1,4 +1,4 @@ -import { stringToSearchRegExp } from '../utilities'; +// import { stringToSearchRegExp } from '../utilities'; /* * A simple model for grower filter @@ -11,29 +11,32 @@ export default class Filter { constructor(options) { Object.assign(this, options); } + getWhereObj() { + console.log('this', this); let where = {}; if (this.type) { where.type = this.type; } - if (this.orgName) { - where.orgName = { - regexp: stringToSearchRegExp(this.orgName), - }; - } - - if (this.firstName) { - where.firstName = { - regexp: stringToSearchRegExp(this.firstName), - }; - } + if (this.name) { + const [firstName, ...lastName] = this.name.split(' '); + if (this.type === 'Person') { + if (this.firstName) { + where.firstName = firstName; + } - if (this.lastName) { - where.lastName = { - regexp: stringToSearchRegExp(this.lastName), - }; + if (this.lastName) { + where.lastName = lastName[0]; + } + where.orgName = ''; + } else { + // give all name fields the value for filter + where.orgName = this.name; + where.firstName = firstName || this.name; + where.lastName = lastName[0] || this.name; + } } if (this.id === ORGANIZATION_NOT_SET) { @@ -42,12 +45,6 @@ export default class Filter { where.id = this.id; } - if (this.organizationId === ORGANIZATION_NOT_SET) { - where.organizationId = null; - } else if (this.organizationId !== ALL_ORGANIZATIONS) { - where.organizationId = this.organizationId; - } - if (!this.stakeholder_uuid) { where.stakeholder_uuid = null; } else { @@ -61,15 +58,11 @@ export default class Filter { } if (this.email) { - where.email = { - regexp: stringToSearchRegExp(this.email), - }; + where.email = this.email; } if (this.phone) { - where.phone = { - regexp: stringToSearchRegExp(this.phone), - }; + where.phone = this.phone; } if (this.website) { @@ -84,10 +77,10 @@ export default class Filter { where.logoUrl = null; } - if (this.mapName) { - where.mapName = this.mapName; + if (this.map) { + where.map = this.map; } else { - where.mapName = null; + where.map = null; } return where; @@ -139,7 +132,7 @@ export default class Filter { numFilters += 1; } - if (this.mapName) { + if (this.map) { numFilters += 1; } @@ -147,10 +140,6 @@ export default class Filter { numFilters += 1; } - if (this.organizationId && this.organizationId !== ALL_ORGANIZATIONS) { - numFilters += 1; - } - if (this.stakeholder_uuid) { numFilters += 1; }