Skip to content

Commit

Permalink
add city for volunteer
Browse files Browse the repository at this point in the history
  • Loading branch information
ariel-bentu committed Nov 1, 2024
1 parent c3fd6a5 commit 0537a63
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 51 deletions.
31 changes: 20 additions & 11 deletions functions/src/demands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,19 @@ import { HttpsError } from "firebase-functions/v2/https";
import { logger } from "firebase-functions/v2";
import { holidays } from "./holidays";

function mealAirtable2FamilyDemand(demand: AirTableRecord, cityName: string, active: boolean): FamilyDemand {
function mealAirtable2FamilyDemand(demand: AirTableRecord, familyCityName: string, volunteerCityName: string, active: boolean): FamilyDemand {
return {
id: demand.id,
date: demand.fields["DATE"],
city: cityName, // id and needs to be name
familyCityName,
city: familyCityName,
familyLastName: demand.fields.Name,
district: getSafeFirstArrayElement(demand.fields["מחוז"], ""),
status: Status.Occupied,
mainBaseFamilyId: getSafeFirstArrayElement(demand.fields["משפחה"], ""),
districtBaseFamilyId: "N/A",
volunteerId: getSafeFirstArrayElement(demand.fields["מתנדב"], undefined),
volunteerCityName,
isFamilyActive: active,
transpotingVolunteerId: getSafeFirstArrayElement(demand.fields["מתנדב משנע"], undefined),
};
Expand All @@ -44,7 +46,10 @@ export async function getDemands2(

const mealsQuery = new AirTableQuery<FamilyDemand>("ארוחות", (m) => {
const family = families.find(f => f.id == getSafeFirstArrayElement(m.fields["משפחה"], ""));
return mealAirtable2FamilyDemand(m, getCityName(getSafeFirstArrayElement(m.fields["עיר"], "")), family ? family.active : false);
return mealAirtable2FamilyDemand(m,
getCityName(getSafeFirstArrayElement(m.fields["עיר"], "")),
getCityName(getSafeFirstArrayElement(m.fields["עיר מתנדב"], "")),
family ? family.active : false);
});

const filters: string[] = [];
Expand Down Expand Up @@ -101,13 +106,14 @@ export async function getDemands2(
addedOpenDemands.push({
id: getCalcDemandID(family.id, actualDate, family.cityId),
date: actualDate,
city: getCityName(family.cityId),
familyCityName: getCityName(family.cityId),
district: family.district,
status: Status.Available,
familyLastName: family.name,
mainBaseFamilyId: family.id,
districtBaseFamilyId: "N/A",
volunteerId: "",
volunteerCityName: "",
isFamilyActive: family.active,
});
}
Expand All @@ -125,13 +131,14 @@ export async function getDemands2(
addedOpenDemands.push({
id: family.id + holidayDate,
date: holidayDate,
city: getCityName(family.cityId),
familyCityName: getCityName(family.cityId),
district: family.district,
status: Status.Available,
familyLastName: family.name,
mainBaseFamilyId: family.id,
districtBaseFamilyId: "N/A",
volunteerId: "",
volunteerCityName: "",
isFamilyActive: family.active,
});
}
Expand Down Expand Up @@ -183,13 +190,15 @@ export async function updateFamilityDemand(demandId: string, demandDistrict: str
const possibleDemands = await getDemands2(demandDistrict, Status.Occupied, date, date);
demand = possibleDemands.find(d => d.mainBaseFamilyId == familyId && d.date == date);
} else {
const cities = await getCities();
const _cities = await getCities();
const getCityName = (id: string) => _cities.find(c => c.id == id)?.name || "";

// eslint-disable-next-line new-cap
demand = await AirTableGet<FamilyDemand>("ארוחות", demandId, (rec) => {
const city = cities.find(c => c.id == getSafeFirstArrayElement(rec.fields["עיר"], ""));
return mealAirtable2FamilyDemand(rec, city?.name || "N/A", true);
});
demand = await AirTableGet<FamilyDemand>("ארוחות", demandId, (m) => mealAirtable2FamilyDemand(m,
getCityName(getSafeFirstArrayElement(m.fields["עיר"], "")),
getCityName(getSafeFirstArrayElement(m.fields["עיר מתנדב"], "")),
true)
);
}

if ((!demand && !isRegistering) || demand && isRegistering) {
Expand Down Expand Up @@ -250,7 +259,7 @@ export async function updateFamilityDemand(demandId: string, demandDistrict: str
await addNotificationToQueue("שיבוץ בוטל!", `תאריך: ${demand.date}
משפחה: ${demand.familyLastName}
בוטל ע״י: ${performingUser}
עיר: ${demand.city}
עיר: ${demand.familyCityName}
`, NotificationChannels.Registrations, [], adminsIds);
}
} else {
Expand Down
2 changes: 1 addition & 1 deletion functions/src/scheduled-functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export async function SendLinkOrInstall() {
const query = new AirTableQuery<{ id: string, familyCount: number }>("מחוז", (rec) => ({
id: rec.id,
familyCount: rec.fields["כמות משפחות פעילות במחוז"],
}))
}));
const districtsIdsWithFamilies = (await query.execute()).filter(d => d.familyCount > 0).map(d => d.id);

const users = await db.collection(Collections.Users).where("active", "==", true).get();
Expand Down
55 changes: 27 additions & 28 deletions src/charts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React, { useEffect, useRef, useState } from 'react';
import { Chart } from 'primereact/chart';
import { MultiSelect } from 'primereact/multiselect';
import dayjs from 'dayjs';
import {AppServices, FamilyCompact, FamilyDemand, UserInfo, VolunteerInfo} from './types';
import {getDemands, getVolunteerInfo, handleSearchUsers, updateDemandTransportation, updateFamilityDemand} from './api';
import { AppServices, FamilyCompact, FamilyDemand, UserInfo, VolunteerInfo } from './types';
import { getDemands, getVolunteerInfo, handleSearchUsers, updateDemandTransportation, updateFamilityDemand } from './api';

import { InProgress, PhoneNumber, WeekSelectorSlider } from './common-ui';
import { SelectButton } from 'primereact/selectbutton';
Expand All @@ -17,7 +17,7 @@ import { ProgressSpinner } from 'primereact/progressspinner';
import { ProgressBar } from 'primereact/progressbar';
import { confirmPopup } from 'primereact/confirmpopup';
import { Recipient } from './types';
import {Dialog} from "primereact/dialog";
import { Dialog } from "primereact/dialog";

interface DemandChartProps {
data: FamilyDemand[];
Expand All @@ -27,7 +27,7 @@ interface DemandChartProps {
showFilterByVolunteer?: boolean;
onCancellationPerformed?: () => void;
onSelectFamily?: (family: GroupedFamily | undefined) => void,
setLoading:(isLoading:boolean)=>void;
setLoading: (isLoading: boolean) => void;
setReload: (reload: number | ((prev: number) => number)) => void;
}

Expand Down Expand Up @@ -76,7 +76,7 @@ const filterOnlyFulfilled = (f: FamilyDemand) => f.status === "תפוס";
export function Stats({ userInfo, appServices }: StatsProps) {
const [loading, setLoading] = useState<boolean>(false);
const [data, setData] = useState<FamilyDemand[]>([]);
const [selectedWeeks, setSelectedWeeks] = useState<[number,number]>([0, 4]);
const [selectedWeeks, setSelectedWeeks] = useState<[number, number]>([0, 4]);
const [selectedDistricts, setSelectedDistricts] = useState<string[]>([]);
//const calendar = useRef<Calendar>(null);
const [mode, setMode] = useState(Modes.Open);
Expand Down Expand Up @@ -120,7 +120,7 @@ export function Stats({ userInfo, appServices }: StatsProps) {
מי יכול.ה לסייע בבישול בחודש הקרוב 🙏
`;
for (const city of sortedCities){
for (const city of sortedCities) {
// Sort families alphabetically within each city
const sortedFamilies = sortFamilies(groupedData[city]);

Expand Down Expand Up @@ -209,21 +209,21 @@ export function Stats({ userInfo, appServices }: StatsProps) {
{/* {error && <small style={{ color: 'red' }}>{error}</small>} */}

{mode === Modes.Open || mode === Modes.Fulfilled ?
<DemandList setReload={setReload} setLoading={setLoading} data={data} isShowOpen={mode === Modes.Open} appServices={appServices} userInfo={userInfo}
<DemandList setReload={setReload} setLoading={setLoading} data={data} isShowOpen={mode === Modes.Open} appServices={appServices} userInfo={userInfo}
onSelectFamily={family => setSelectedFamily(family)}
showFilterByVolunteer={showFilterByVolunteer}
onCancellationPerformed={() => {
appServices.showMessage("success", "בוטל בהצלחה", "")
setReload(prev => prev + 1)
}
} /> :
<DemandChart setReload={setReload} setLoading={setLoading} data={data} appServices={appServices} userInfo={userInfo} />
<DemandChart setReload={setReload} setLoading={setLoading} data={data} appServices={appServices} userInfo={userInfo} />
}
</div>
);
}

export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appServices, userInfo, showFilterByVolunteer,
export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appServices, userInfo, showFilterByVolunteer,
onCancellationPerformed, onSelectFamily, setLoading, setReload }) => {
let demands = data.filter(isShowOpen ? filterOnlyOpen : filterOnlyFulfilled);
const [showFamilyDetails, setShowFamilyDetails] = useState<GroupedFamily | undefined>();
Expand All @@ -238,7 +238,7 @@ export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appSe
const [showRecipientModal, setShowRecipientModal] = useState(false);
const [recipients, setRecipients] = useState<Recipient[]>([]);
const [filteredUsers, setFilteredUsers] = useState<any[]>([]); // Adjust the type as needed
const [transportingVolunteer, setTransportingVolunteer] = useState<VolunteerInfo|undefined>(undefined);
const [transportingVolunteer, setTransportingVolunteer] = useState<VolunteerInfo | undefined>(undefined);

const openRecipientModal = () => {
setShowRecipientModal(true);
Expand Down Expand Up @@ -270,7 +270,7 @@ export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appSe
appServices.showMessage("error", "שמירה נכשלה", error.message);
console.error("Error updating transportation:", error);
})
.finally(()=>setLoading(false));
.finally(() => setLoading(false));
}
closeRecipientModal(); // Close the modal after success
} catch (error) {
Expand All @@ -283,17 +283,16 @@ export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appSe
selectedDateInfo: DateInfo | undefined,
volunteerInfo: VolunteerInfo | undefined
) => {
const message = `
דרוש שינוע🚙
const message = `דרוש שינוע🚙
מי יכול.ה לעזור בשינוע?
מי יכול.ה לעזור בשינוע?
בתאריך ${selectedDateInfo ? selectedDateInfo.date : ""}
בתאריך ${selectedDateInfo ? selectedDateInfo.date : ""}
מ${volunteerInfo ? volunteerInfo.city : ""}
ל${selectedDateInfo && selectedDateInfo.parentFamily ? `${selectedDateInfo.parentFamily.city}` : ""}
למשפחת${selectedDateInfo && selectedDateInfo.parentFamily ? ` ${selectedDateInfo.parentFamily.familyLastName}` : ""}
`;
מ${volunteerInfo ? volunteerInfo.city : ""}
ל${selectedDateInfo && selectedDateInfo.parentFamily ? `${selectedDateInfo.parentFamily.city}` : ""}
למשפחת${selectedDateInfo && selectedDateInfo.parentFamily ? ` ${selectedDateInfo.parentFamily.familyLastName}` : ""}`;

// Handle the message, e.g., displaying it in a modal or copying to clipboard
console.log(message); // Or whatever logic you need to use the message
navigator.clipboard.writeText(message);
Expand Down Expand Up @@ -337,7 +336,7 @@ export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appSe
if (onSelectFamily) onSelectFamily(undefined);

// todo push nav state
}} reloadOpenDemands={() => { }} detailsOnly={true} actualUserId={""}/>;
}} reloadOpenDemands={() => { }} detailsOnly={true} actualUserId={""} />;
}

const handleDateClick = (e: any, dateInfo: DateInfo) => {
Expand Down Expand Up @@ -410,10 +409,10 @@ export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appSe
{selectedDateInfo && (volunteerInfo ?
<>
<div><strong>שם מבשל</strong>: {volunteerInfo.firstName + " " + volunteerInfo.lastName}</div>
<PhoneNumber phone={volunteerInfo.phone} label="טלפון מבשל"/>
<PhoneNumber phone={volunteerInfo.phone} label="טלפון מבשל" />
{transportingVolunteer &&
<div><strong>שם משנע</strong>: {transportingVolunteer ? transportingVolunteer.firstName + " " + transportingVolunteer.lastName : undefined}</div>}
{transportingVolunteer && <PhoneNumber phone={transportingVolunteer.phone} label="טלפון משנע"/>}
<div><strong>שם משנע</strong>: {transportingVolunteer ? transportingVolunteer.firstName + " " + transportingVolunteer.lastName : undefined}</div>}
{transportingVolunteer && <PhoneNumber phone={transportingVolunteer.phone} label="טלפון משנע" />}
<Button label="מחק התנדבות" onClick={() => {
confirmPopup({
message: 'האם למחוק התנדבות זו?',
Expand Down Expand Up @@ -452,9 +451,9 @@ export const DemandList: React.FC<DemandChartProps> = ({ data, isShowOpen, appSe
/>

{/* Modal for selecting recipients */}
<Dialog header={<div style={{ textAlign: 'right', width: '100%' }}>בחר משנע</div>} visible={showRecipientModal}
onHide={closeRecipientModal}
style={{ width: '300px', position: 'absolute', right: '10%', top: '20%' }}
<Dialog header={<div style={{ textAlign: 'right', width: '100%' }}>בחר משנע</div>} visible={showRecipientModal}
onHide={closeRecipientModal}
style={{ width: '300px', position: 'absolute', right: '10%', top: '20%' }}

>
<div className="flex justify-content-end">
Expand Down Expand Up @@ -564,7 +563,7 @@ const groupByCityAndFamily = (familyDemands: FamilyDemand[]): GroupedData => {
const groupedByCityAndFamily: GroupedData = {};

familyDemands.forEach((family) => {
const city = family.city.replaceAll("\"", "");
const city = family.familyCityName.replaceAll("\"", "");
const familyName = simplifyFamilyName(family.familyLastName);

// Initialize city if not exists
Expand All @@ -579,7 +578,7 @@ const groupByCityAndFamily = (familyDemands: FamilyDemand[]): GroupedData => {
familyLastName: familyName,
districtBaseFamilyId: family.districtBaseFamilyId,
mainBaseFamilyId: family.mainBaseFamilyId,
city: family.city,
city,
district: family.district,
active: family.isFamilyActive,
};
Expand Down
12 changes: 4 additions & 8 deletions src/existing-registration-component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ export function ExistingRegistrationsComponent({ appServices, navigationRequest,

if (currentRegistration) {
const currentFamily = {
city: currentRegistration.city,
city: currentRegistration.familyCityName,
districtBaseFamilyId: currentRegistration.districtBaseFamilyId,
mainBaseFamilyId: currentRegistration.mainBaseFamilyId,
familyLastName: currentRegistration.familyLastName,
Expand Down Expand Up @@ -192,7 +192,7 @@ export function ExistingRegistrationsComponent({ appServices, navigationRequest,
</div>
}
title={reg.familyLastName}
body={`עיר: ${reg.city}\nמתי: ${getReferenceDays(reg.date)}`}
body={`עיר: ${reg.familyCityName}\nמתי: ${getReferenceDays(reg.date)}`}
footer={dayjs(reg.date).format(NICE_DATE)}
unread={isInFuture(reg.date)}
className="cooking-color" // Apply specific color for cooking
Expand All @@ -213,7 +213,7 @@ export function ExistingRegistrationsComponent({ appServices, navigationRequest,
);
}
const cookingVolunteerCity = volunteerInfo ? volunteerInfo.city : ""; // Assuming volunteerInfo has the city of the cooking volunteer
const transportingDestinationCity = reg.city; // Assuming reg.city is the target city for transportation
const transportingDestinationCity = reg.familyCityName; // Assuming reg.city is the target city for transportation

// Transporting line (if transpotingVolunteerId is present and current user is the transporting volunteer)
if (reg.transpotingVolunteerId === actualUserId) {
Expand All @@ -239,7 +239,7 @@ export function ExistingRegistrationsComponent({ appServices, navigationRequest,
</div>
}
title={reg.familyLastName}
body={`מעיר: ${transportingDestinationCity}\n לעיר: ${transportingDestinationCity}\nמתי: ${getReferenceDays(reg.date)}`}
body={`מעיר: ${cookingVolunteerCity}\n לעיר: ${transportingDestinationCity}\nמתי: ${getReferenceDays(reg.date)}`}
footer={dayjs(reg.date).format(NICE_DATE)}
unread={isInFuture(reg.date)}
className="transporting-color"
Expand All @@ -251,11 +251,7 @@ export function ExistingRegistrationsComponent({ appServices, navigationRequest,
}}
/>
);



}

return lines;
})
) : (
Expand Down
2 changes: 1 addition & 1 deletion src/registration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ function RegistrationComponent({ openDemands, appServices, actualUserId, openDem
// calculate the cities' availability
// const cities = getUniqueCities(demands.demands).map(city => ({ ...city, available: true }));
// console.log("cities", demands.allDistrictCities)
const cities = demands.allDistrictCities.map(city => ({ ...city, available: (demands.demands.some(d => compareCities(d.city, city.name))) } as CityAvailability));
const cities = demands.allDistrictCities.map(city => ({ ...city, available: (demands.demands.some(d => compareCities(d.familyCityName, city.name))) } as CityAvailability));
setCities(cities);
if (cities.length == 1) {
console.log("cities", cities)
Expand Down
Loading

0 comments on commit 0537a63

Please sign in to comment.