Skip to content

Instantly share code, notes, and snippets.

@jonshipman
Created June 19, 2024 13:30
Show Gist options
  • Save jonshipman/91d013322239fef69ef62e4008c750a9 to your computer and use it in GitHub Desktop.
Save jonshipman/91d013322239fef69ef62e4008c750a9 to your computer and use it in GitHub Desktop.
import mongoose from 'mongoose';
import { revalidatePath } from 'next/cache';
import { Field, Form, FormButton } from '@/components/form';
import { SCHEMAS, capability, mongoDb } from '@/lib/server';
import type { Lead } from '@/lib/server/schemas';
import { isString } from '@/lib/validators';
async function deadReasonAction(_: any, formData: FormData): Promise<{ error: string | null }> {
'use server';
const can = await capability.currentUserCan('edit_Lead');
if (!can) return { error: 'Forbidden' };
const _id = formData.get('_id') + '';
if (!_id) return { error: '_id problem' };
try {
await mongoDb.model<Lead>(SCHEMAS.LEAD, async (m) => {
const lead = await m.findOne({ _id: new mongoose.mongo.ObjectId(_id) });
if (!lead) throw new Error('No Lead');
const reason = formData.get('leadDeadReason');
if (!isString(reason)) throw new Error('No reason given');
let reasonString = reason.trim();
if (!reasonString) throw new Error('No reason given');
lead.leadDeadReason = reasonString;
await lead.save();
});
} catch (e) {
if (e instanceof Error) {
return { error: e.message };
}
return { error: 'Unknown error' };
}
revalidatePath(`/lead/${_id}`);
return { error: null };
}
export function ReasonEdit({
children,
canEdit,
id,
}: Readonly<{ children?: string | undefined | null; canEdit: boolean; id: string }>) {
if (!canEdit && children) {
return <div className="text-sm">Reason: {children}</div>;
} else if (!canEdit && !children) {
return '';
}
return (
<Form action={deadReasonAction}>
<div className="flex items-end gap-4">
<Field name="leadDeadReason" type="text" label="Reason" value={children || ''} />
<input type="hidden" name="_id" value={id} readOnly />
<FormButton>
<svg xmlns="http://www.w3.org/2000/svg" className="w-4 h-4" viewBox="0 0 24 24">
<path
fill="currentColor"
d="M18 19h1V6.828L17.172 5H16v4H7V5H5v14h1v-7h12zM4 3h14l2.707 2.707a1 1 0 0 1 .293.707V20a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1m4 11v5h8v-5z"
/>
</svg>
</FormButton>
</div>
</Form>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment