Skip to content

Commit

Permalink
Merge branch 'main' into avoid-solicitudes-requests
Browse files Browse the repository at this point in the history
  • Loading branch information
j8seangel committed Nov 15, 2024
2 parents ad7a827 + 0bcc252 commit 94e596f
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 53 deletions.
32 changes: 0 additions & 32 deletions src/app/casos-activos/mapa/actions.tsx

This file was deleted.

10 changes: 8 additions & 2 deletions src/app/casos-activos/solicitudes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ function getDataFiltered(data: HelpRequestDataWAssignmentCount[], filters: DataF
return data;
}

return filters.reduceRight((results, { value, keys }) => matchSorter(results, value, { keys }), data);
return filters.reduceRight(
(results, { value, keys }) =>
matchSorter(results, value, { keys, threshold: matchSorter.rankings.WORD_STARTS_WITH }),
data,
);
}

type SolicitudesProps = {
Expand Down Expand Up @@ -47,7 +51,9 @@ export function Solicitudes({ data, count }: SolicitudesProps) {
(filter: FilterType, value: string | number) => {
const params = new URLSearchParams(searchParams.toString());
params.set(filter, value.toString());
router.push(`?${params.toString()}`);
if (filter === 'soloSinAsignar') {
router.push(`?${params.toString()}`);
}
},
[searchParams, router],
);
Expand Down
45 changes: 32 additions & 13 deletions src/app/casos-activos/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { createClient } from '@/lib/supabase/server';
import { Database } from '@/types/database';
import { Solicitudes } from '.';
import { FiltersData } from './types';
import { HelpRequestData, HelpRequestDataWAssignmentCount } from '@/types/Requests';
import { getAllAssignments } from '@/lib/actions';
import { HelpRequestData, HelpRequestDataWAssignmentCount } from '../../../types/Requests';

export const dynamic = 'force-dynamic';

Expand Down Expand Up @@ -33,30 +34,47 @@ function parseData(data: HelpRequestData[], assignments: Assignment[]): HelpRequ
});
}

const getData = async (supabase: SupabaseClient<Database>) => {
const { error, data } = await supabase
.from('help_requests')
.select('*')
const getData = async (supabase: SupabaseClient<Database>, filters: FiltersData) => {
const query = supabase
.from('help_requests_with_assignment_count')
.select('*', { count: 'exact' })
.eq('type', 'necesita')
.order('created_at', { ascending: false });
const { data: assignments, error: assignmentError } = await getAllAssignments();
.order('created_at', { ascending: false })
.neq('status', 'finished');

// Solo agregar filtro si es true
if (filters.soloSinAsignar !== undefined && filters.soloSinAsignar === 'true') {
query.eq('assignments_count', 0);
}

const { data, error } = await query.order('created_at', { ascending: false });

if (error) {
throw new Error('Error fetching solicita:', error);
}

const { data: assignments, error: assignmentError } = await getAllAssignments();

if (assignmentError) {
throw new Error('Error fetching assignments:', assignmentError);
}

return parseData(data as HelpRequestData[], assignments);
};

const getCount = async (supabase: SupabaseClient<Database>) => {
const { count: solicitaCount, error: solicitaError } = await supabase
.from('help_requests')
const getCount = async (supabase: SupabaseClient<Database>, filters: FiltersData) => {
const query = supabase
.from('help_requests_with_assignment_count')
.select('id', { count: 'exact' })
.eq('type', 'necesita');

// Solo agregar filtro si es true
if (filters.soloSinAsignar !== undefined && filters.soloSinAsignar === 'true') {
query.eq('assignments_count', 0);
}

const { count: solicitaCount, error: solicitaError } = await query;

const { count: ofreceCount, error: ofreceError } = await supabase
.from('help_requests')
.select('id', { count: 'exact' })
Expand All @@ -75,10 +93,11 @@ const getCount = async (supabase: SupabaseClient<Database>) => {
};
};

export default async function SolicitudesPage() {
export default async function SolicitudesPage(props: { searchParams: Promise<Record<string, string | undefined>> }) {
const searchParams = (await props.searchParams) as FiltersData;
const supabase = await createClient();
const data = await getData(supabase);
const count = await getCount(supabase);
const data = await getData(supabase, searchParams);
const count = await getCount(supabase, searchParams);

return (
<Suspense
Expand Down
1 change: 0 additions & 1 deletion src/components/map/map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ const Map: FC<MapProps> = ({ solicitudes, setSelectedMarker }) => {

const onClickHandler = (e: MapLayerMouseEvent) => {
if (e.features?.[0]) {
console.log('e.features?.[0]:', e.features?.[0].properties);
toggleModal(MAP_MODAL_NAME, true);
setSelectedMarker(e.features?.[0].properties as HelpRequestDataWAssignmentCount);
}
Expand Down
27 changes: 25 additions & 2 deletions src/components/solicitudes/SolicitudCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,26 +15,47 @@ import DeleteHelpRequest from '../DeleteHelpRequest';
import { textWithEllipsis } from '@/helpers/utils';
import { useTowns } from '@/context/TownProvider';
import { useRole } from '@/context/RoleProvider';
import { useState } from 'react';
import { Fragment, useState } from 'react';
import ChangeUrgencyHelpRequest from '../ChangeUrgencyHelpRequest';
import ChangeStatusButton from '../ChangeStatusButton';
import ChangeCRMStatus from '../ChangeCRMStatus';
import { UserRoles } from '@/helpers/constants';
import CRMNotes from '@/components/CRMNotes';
import CRMLog from '@/components/CRMLog';

export const getHighlightedText = (text: string, highlight: string) => {
if (highlight === '') return text;
const regEscape = (v: string) => v.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
const textChunks = text.split(new RegExp(regEscape(highlight), 'ig'));
let sliceIdx = 0;
return textChunks.map((chunk, index) => {
const currentSliceIdx = sliceIdx + chunk.length;
sliceIdx += chunk.length + highlight.length;
return (
<Fragment key={index}>
{chunk}
{currentSliceIdx < text.length && (
<span className="inline-block bg-blue-100">{text.slice(currentSliceIdx, sliceIdx)}</span>
)}
</Fragment>
);
});
};

type SolicitudCardProps = {
caso: SelectedHelpData | HelpRequestData | HelpRequestDataWAssignmentCount;
showLink?: boolean;
showEdit?: boolean;
format?: 'small' | 'large';
highlightedText?: string;
};

export default function SolicitudCard({
caso,
showLink = true,
showEdit = false,
format = 'large',
highlightedText = '',
}: SolicitudCardProps) {
const session = useSession();
const role = useRole();
Expand All @@ -47,6 +68,8 @@ export default function SolicitudCard({
const isMyRequest = session.user?.id && session.user.id === caso.user_id;
const [updateUrgency, setUpdateUrgency] = useState(caso.urgency);
const [updateStatus, setUpdateStatus] = useState(caso.status);

const description = format === 'small' ? textWithEllipsis(caso.description, 250) : caso.description;
return (
!deleted && (
<div key={caso.id} className="rounded-2xl bg-white shadow-lg ring-1 ring-gray-900/5">
Expand Down Expand Up @@ -100,7 +123,7 @@ export default function SolicitudCard({
</div>
<div className="px-6 py-4">
<p className="text-gray-700 first-letter:capitalize" style={{ wordBreak: 'break-word' }}>
{format === 'small' ? textWithEllipsis(caso.description, 250) : caso.description}
{description && getHighlightedText(description, highlightedText)}
</p>
</div>
<div className="flex flex-col sm:flex-row justify-between items-start md:items-end gap-4 px-6 pb-4">
Expand Down
8 changes: 7 additions & 1 deletion src/components/solicitudes/SolicitudList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,13 @@ export default function SolicitudList({ data, count, filtersData, onDataFilterCh
data={data}
itemContent={(_, caso) => (
<div key={caso.id} className="py-2">
<SolicitudCard format="small" showLink={true} showEdit={true} caso={caso} />
<SolicitudCard
format="small"
showLink={true}
showEdit={true}
caso={caso as HelpRequestData}
highlightedText={filtersData.search}
/>
</div>
)}
/>
Expand Down
7 changes: 5 additions & 2 deletions src/components/solicitudes/SolicitudMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import Map from '@/components/map/map';
import { HelpRequestData, HelpRequestDataWAssignmentCount } from '@/types/Requests';
import { Dispatch, SetStateAction, useMemo } from 'react';

function transformHelpRequestToPointFeature(request: any): GeoJSON.Feature<GeoJSON.Point> {
function transformHelpRequestToPointFeature(request: any): GeoJSON.Feature<GeoJSON.Point> | [] {
if (!request.latitude || !request.longitude) {
return [];
}
return {
type: 'Feature',
geometry: {
Expand All @@ -25,7 +28,7 @@ export default function SolicitudList({ data, setSelectedMarker }: SolicitudList
() =>
({
type: 'FeatureCollection',
features: data.map(transformHelpRequestToPointFeature),
features: data.flatMap(transformHelpRequestToPointFeature),
}) as GeoJSON.FeatureCollection<GeoJSON.Point>,
[data],
);
Expand Down

0 comments on commit 94e596f

Please sign in to comment.