Skip to content

Commit

Permalink
Merge branch 'solicitudes-asigness-count' into avoid-solicitudes-requ…
Browse files Browse the repository at this point in the history
…ests
  • Loading branch information
j8seangel committed Nov 15, 2024
2 parents a88783b + d1f377b commit ad7a827
Show file tree
Hide file tree
Showing 12 changed files with 319 additions and 21 deletions.
6 changes: 5 additions & 1 deletion src/app/casos-activos/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ function parseData(data: HelpRequestData[], assignments: Assignment[]): HelpRequ
}

const getData = async (supabase: SupabaseClient<Database>) => {
const { error, data } = await supabase.from('help_requests').select('*').eq('type', 'necesita');
const { error, data } = await supabase
.from('help_requests')
.select('*')
.eq('type', 'necesita')
.order('created_at', { ascending: false });
const { data: assignments, error: assignmentError } = await getAllAssignments();

if (error) {
Expand Down
1 change: 0 additions & 1 deletion src/app/casos-activos/solicitudes/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,3 @@ import { HelpRequestData } from '@/types/Requests';
export type FilterType = 'search' | 'urgencia' | 'tipoAyuda' | 'pueblo' | 'soloSinAsignar';

export type FiltersData = Record<FilterType, string>;

2 changes: 1 addition & 1 deletion src/app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ body {

/* .maplibregl-ctrl-attrib {
display: none;
} */
} */
115 changes: 115 additions & 0 deletions src/components/CRMLog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
'use client';

import { MouseEvent, useCallback, useEffect, useState } from 'react';
import Modal from '@/components/Modal';
import { useModal } from '@/context/ModalProvider';
import { ScrollText } from 'lucide-react';
import { getCRMLogEntries } from '@/lib/actions';

type CRMLogButtonProps = {
helpRequestId: number;
};

type LogEntry = {
date: Date | null;
email: string;
diff: string | null;
};

export default function CRMLog({ helpRequestId }: CRMLogButtonProps) {
const { toggleModal } = useModal();
const [opened, setOpened] = useState(false);
const [logEntries, setLogEntries] = useState<LogEntry[]>([]);
useEffect(() => {
if (opened) {
const fetchLogEntries = async () => {
const data = await getCRMLogEntries(helpRequestId);
setLogEntries(
data?.map((entry) => ({
date: entry.created_at ? new Date(entry.created_at) : null,
email: entry.email,
diff: entry.diff,
})),
);
};
fetchLogEntries();
}
}, [opened]);
const MODAL_NAME = `Ver-LogBook-${helpRequestId}`;

const handleCloseModal = useCallback(
async (e: MouseEvent) => {
e.preventDefault();
toggleModal(MODAL_NAME, false);
setOpened(false);
},
[toggleModal, setOpened],
);

const handleOpenModal = useCallback(
async (e: MouseEvent) => {
e.preventDefault();
toggleModal(MODAL_NAME, true);
setOpened(true);
},
[toggleModal, setOpened],
);

return (
<>
<button
onClick={handleOpenModal}
className="w-full inline-flex text-center rounded-xl px-4 py-2 font-semibold text-white sm:w-auto transition-all bg-pink-500 hover:bg-pink-600"
>
<ScrollText />
&nbsp;Logs
</button>
<Modal id={MODAL_NAME} allowClose={false}>
<div className="fixed inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 z-50">
<div className="bg-white w-full max-w-lg rounded-lg shadow-lg overflow-hidden">
<div className="flex justify-between items-center p-4 border-b border-gray-200">
<h2 className="text-xl font-semibold text-gray-800">Log de Cambios</h2>
<button onClick={handleCloseModal} className="text-gray-500 hover:text-gray-700">
</button>
</div>
<div className="p-4 h-96 overflow-y-auto">
{logEntries.length > 0 ? (
logEntries.map((entry, index) => (
<div key={index} className="mb-4 p-3 bg-gray-50 rounded-lg shadow-sm border border-gray-200">
<div className="flex justify-between text-gray-600 text-sm mb-1">
<span>
{entry.date
? entry.date.toLocaleDateString('es-ES', {
day: 'numeric',
month: 'long',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
})
: ''}
</span>
<span>{entry.email}</span>
</div>
<pre className="text-gray-700 text-sm">{entry.diff}</pre>
</div>
))
) : (
<p className="text-gray-500 text-center">No hay cambios registrados.</p>
)}
</div>
<div className="p-4 border-t border-gray-200 flex justify-end">
<button
onClick={handleCloseModal}
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
>
Cerrar
</button>
</div>
</div>
</div>
</Modal>
</>
);
}
14 changes: 12 additions & 2 deletions src/components/CRMNotes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import { ChangeEvent, MouseEvent, useCallback, useState } from 'react';
import Modal from '@/components/Modal';
import { useModal } from '@/context/ModalProvider';
import { LimitedTextarea } from '@/components/input/LimitedTextarea';
import { updateNotesRequest } from '@/lib/actions';
import { updateNotesRequest, addCRMLog } from '@/lib/actions';
import { useSession } from '@/context/SessionProvider';

type CRMNotesButtonProps = {
helpRequestId: number;
currentNotes: string | null;
};

export default function CRMNotes({ helpRequestId, currentNotes }: CRMNotesButtonProps) {
const { user } = useSession();
const { toggleModal } = useModal();
const [notes, setNotes] = useState<string>(currentNotes || '');
const [newNotes, setNewNotes] = useState<string>(currentNotes || '');
Expand All @@ -27,10 +29,18 @@ export default function CRMNotes({ helpRequestId, currentNotes }: CRMNotesButton
setError(error);
return;
}
if (user) {
await addCRMLog(
'---ANTES---\n' + notes + '\n---DESPUES---\n' + newNotes,
helpRequestId,
user.id,
(user.user_metadata.full_name || user.user_metadata.nombre) + ' ' + user.email,
);
}
toggleModal(MODAL_NAME, false);
setNotes(newNotes);
},
[newNotes, setNotes, toggleModal],
[newNotes, setNotes, toggleModal, user],
);

async function handleOpenModal(e: MouseEvent) {
Expand Down
40 changes: 26 additions & 14 deletions src/components/ChangeCRMStatus.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
'use client';

import { useState } from 'react';
import { useCallback, useState } from 'react';
import { CRMStatus, CrmStatusActive, CrmStatusFinished } from '@/helpers/constants';
import { updateHelpRequestCRMStatus } from '@/lib/actions';
import { addCRMLog, updateHelpRequestCRMStatus } from '@/lib/actions';
import { useSession } from '@/context/SessionProvider';

type ChangeCRMStatusRequestButtonProps = {
helpRequestId: number;
Expand All @@ -17,22 +18,33 @@ export default function ChangeCRMStatus({
currentStatus,
currentCrmStatus,
}: ChangeCRMStatusRequestButtonProps) {
const { user } = useSession();
const [crmStatus, setCrmStatus] = useState<string>(currentCrmStatus || CrmStatusActive);
const [error, setError] = useState({});

const updateStatusRequest = async (newCrmStatus: string) => {
var status = currentStatus || 'active';
if (newCrmStatus === CrmStatusFinished) {
status = 'finished';
} else if (newCrmStatus !== CrmStatusFinished && status == 'finished') {
status = 'active';
}
const { data, error } = await updateHelpRequestCRMStatus(String(helpRequestId), status, newCrmStatus);

onStatusUpdate(status);
const updateStatusRequest = useCallback(
async (newCrmStatus: string) => {
var status = currentStatus || 'active';
if (newCrmStatus === CrmStatusFinished) {
status = 'finished';
} else if (newCrmStatus !== CrmStatusFinished && status == 'finished') {
status = 'active';
}
const { data, error } = await updateHelpRequestCRMStatus(String(helpRequestId), status, newCrmStatus);
if (user !== null) {
await addCRMLog(
'Estado cambiado de ' + crmStatus + ' a ' + newCrmStatus,
helpRequestId,
user.id,
(user.user_metadata.full_name || user.user_metadata.nombre) + ' ' + user.email,
);
}
onStatusUpdate(status);

return { data, error };
};
return { data, error };
},
[crmStatus, helpRequestId, user],
);

async function handleUpdateSubmit(newStatus: string) {
const { data, error } = await updateStatusRequest(newStatus);
Expand Down
4 changes: 2 additions & 2 deletions src/components/layout/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { SelectedHelpData } from '@/types/Requests';
import { getOffersByUser, getRequestsByUser } from '@/lib/actions';
import { useSession } from '../../context/SessionProvider';

export const SOLICITUDES_PATH = '/casos-activos/solicitudes'
export const SOLICITUDES_PATH = '/casos-activos/solicitudes';

type SidebarProps = {
isOpen: boolean;
Expand Down Expand Up @@ -61,7 +61,7 @@ export default function Sidebar({ isOpen, toggleAction }: SidebarProps) {
path: SOLICITUDES_PATH,
color: 'text-orange-600',
highlight: true,
closeOnClick: true
closeOnClick: true,
},
{
icon: Inbox,
Expand Down
2 changes: 2 additions & 0 deletions src/components/solicitudes/SolicitudCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import ChangeStatusButton from '../ChangeStatusButton';
import ChangeCRMStatus from '../ChangeCRMStatus';
import { UserRoles } from '@/helpers/constants';
import CRMNotes from '@/components/CRMNotes';
import CRMLog from '@/components/CRMLog';

type SolicitudCardProps = {
caso: SelectedHelpData | HelpRequestData | HelpRequestDataWAssignmentCount;
Expand Down Expand Up @@ -217,6 +218,7 @@ export default function SolicitudCard({
/>
)}
{(isCrmUser || isAdmin) && <CRMNotes helpRequestId={caso.id} currentNotes={caso.notes} />}
{(isCrmUser || isAdmin) && <CRMLog helpRequestId={caso.id} />}
{isAdmin && <DeleteHelpRequest helpRequestId={caso.id} onDelete={() => setDeleted(true)} />}
</div>
</div>
Expand Down
21 changes: 21 additions & 0 deletions src/lib/actions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use server';

import {
CRMUsersLogRow,
helpDataSelectFields,
HelpRequestAssignmentInsert,
HelpRequestData,
Expand Down Expand Up @@ -79,6 +80,26 @@ export async function updateNotesRequest(newNotes: string, helpRequestId: string
return { data, error };
}

export async function addCRMLog(diff: string, helpRequestId: number, userId: string, email: string) {
const supabase = await createClient();
const { data, error } = await supabase
.from('crm_users_log')
.insert([{ help_request_id: helpRequestId, user_id: userId, email, diff }]);
return { data, error };
}

export async function getCRMLogEntries(helpRequestId: number): Promise<CRMUsersLogRow[]> {
const supabase = await createClient();
const { data, error } = await supabase
.from('crm_users_log')
.select('*')
.eq('help_request_id', helpRequestId)
.order('created_at', { ascending: false });

if (error) throw error;
return data;
}

export async function deleteHelpRequest(helpRequestId: string) {
const supabase = await createClient();
const { data, error } = await supabase.from('help_requests').delete().eq('id', helpRequestId).select();
Expand Down
1 change: 1 addition & 0 deletions src/types/Requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export type HelpRequestAssignmentData = Database['public']['Tables']['help_reque
export type HelpRequestAssignmentInsert = Database['public']['Tables']['help_request_assignments']['Insert'];

export type HelpRequestComment = Database['public']['Tables']['comments']['Row'];
export type CRMUsersLogRow = Database['public']['Tables']['crm_users_log']['Row'];

export type HelpRequestAdditionalInfo = {
special_situations?: string;
Expand Down
27 changes: 27 additions & 0 deletions src/types/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,33 @@ export type Database = {
};
Relationships: [];
};
crm_users_log: {
Row: {
id: number;
help_request_id: number;
created_at: string | null;
email: string;
user_id: string;
diff: string | null;
};
Insert: {
id: number | null;
help_request_id: number;
created_at?: string | null;
email: string;
user_id: string;
diff: string;
};
Relationships: [
{
foreignKeyName: 'crm_users_log_help_request_id_fkey';
columns: ['help_request_id'];
isOneToOne: false;
referencedRelation: 'help_requests';
referencedColumns: ['id'];
},
];
};
};
Views: {
distinct_collection_cities: {
Expand Down
Loading

0 comments on commit ad7a827

Please sign in to comment.