Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions app/md/proposal/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { renderProposalMarkdown } from '@/lib/agent-markdown';
import { PostService } from '@/services/post.service';

interface Params {
params: Promise<{ id: string }>;
}

/** Markdown for a proposal. Reached by the Accept: text/markdown rewrite in next.config.js. */
export async function GET(_request: Request, { params }: Params) {
const { id } = await params;
if (!/^\d+$/.test(id)) return new Response('Not found', { status: 404 });

try {
const work = await PostService.getPublic(id);
if (work.contentType !== 'preregistration' || work.isPublic === false) {
return new Response('Not found', { status: 404 });
}
return new Response(renderProposalMarkdown(work, `/proposal/${id}/${work.slug}`), {
headers: {
'Content-Type': 'text/markdown; charset=utf-8',
'X-Robots-Tag': 'noindex',
},
});
} catch {
return new Response('Not found', { status: 404 });
}
}
27 changes: 27 additions & 0 deletions app/md/rfp/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { renderRfpMarkdown } from '@/lib/agent-markdown';
import { PostService } from '@/services/post.service';

interface Params {
params: Promise<{ id: string }>;
}

/** Markdown for an RFP. Reached by the Accept: text/markdown rewrite in next.config.js. */
export async function GET(_request: Request, { params }: Params) {
const { id } = await params;
if (!/^\d+$/.test(id)) return new Response('Not found', { status: 404 });

try {
const work = await PostService.getPublic(id);
if (work.contentType !== 'funding_request' || work.isPublic === false) {
return new Response('Not found', { status: 404 });
}
return new Response(renderRfpMarkdown(work, `/rfp/${id}/${work.slug}`), {
headers: {
'Content-Type': 'text/markdown; charset=utf-8',
'X-Robots-Tag': 'noindex',
},
});
} catch {
return new Response('Not found', { status: 404 });
}
}
1 change: 1 addition & 0 deletions app/robots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default function robots(): MetadataRoute.Robots {
'/moderators/',
'/expert-finder/',
'/settings',
'/md/',
'/_next/',
'/sw.js',
],
Expand Down
59 changes: 59 additions & 0 deletions lib/agent-markdown.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { SITE_CONFIG } from '@/lib/metadata';
import { proposalGoal, storedGrantAmount } from '@/lib/metadata-helpers';
import type { Work } from '@/types/work';
import { stripHtml } from '@/utils/stringUtils';

function pageUrl(path: string): string {
return `${SITE_CONFIG.url}${path}`;
}

function lines(rows: Array<[string, string | undefined]>): string {
return rows
.filter((row): row is [string, string] => Boolean(row[1]))
.map(([label, value]) => `- ${label}: ${value}`)
.join('\n');
}

function goalLabel(work: Work): string | undefined {
const goal = proposalGoal(work.fundraise, work.linkedGrant?.fundingMechanism);
return goal ? `${goal.value} ${goal.currency}` : undefined;
}

function body(work: Work): string {
const text = stripHtml(work.previewContent || work.abstract || '').trim();
return text ? `\n\n## Details\n\n${text}` : '';
}

/** Public RFP as markdown. Peer review text is never included. */
export function renderRfpMarkdown(work: Work, path: string): string {
const grant = work.note?.post?.grant;
const amount = storedGrantAmount(grant?.amount, grant?.currency);
const amountLabel = amount ? `${amount.value} ${amount.currency}` : undefined;
const facts = lines([
['URL', pageUrl(path)],
['Funder', grant?.organization || undefined],
['Amount', amountLabel],
['Status', grant?.status],
['Application deadline', grant?.endDate || undefined],
['Funding', grant?.fundingMechanism],
]);

return `# ${work.title}\n\n${facts}${body(work)}\n`;
}

/** Public proposal as markdown. Peer review text is never included. */
export function renderProposalMarkdown(work: Work, path: string): string {
const linked = work.linkedGrant;
const rfpUrl = linked?.postId ? pageUrl(`/rfp/${linked.postId}`) : undefined;
const facts = lines([
['URL', pageUrl(path)],
['Funder', linked?.organization || undefined],
['Request for Proposal', rfpUrl],
['Goal', goalLabel(work)],
['Status', work.fundraise?.status],
['Funding deadline', work.fundraise?.endDate],
['Funding', linked?.fundingMechanism],
]);

return `# ${work.title}\n\n${facts}${body(work)}\n`;
}
119 changes: 111 additions & 8 deletions lib/metadata-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@ import {
buildArticleMetadata,
buildDefaultOgImageUrl,
buildOpenGraphMetadata,
SITE_CONFIG,
} from '@/lib/metadata';
import { generateDocumentStructuredData } from '@/lib/structured-data';
import {
generateDocumentStructuredData,
generateGrantStructuredData,
generateProposalStructuredData,
} from '@/lib/structured-data';
import type { Grant } from '@/types/grant';
import { Work } from '@/types/work';
import { stripHtml } from '@/utils/stringUtils';

Expand All @@ -21,6 +27,109 @@ export function getWorkShareImageUrl(work: Work): string {
return getWorkImage(work) || buildDefaultOgImageUrl(work.title, getWorkDescription(work));
}

/**
* A community proposal's funding goal. Award applications publish a budget of 0
* because the funder pays them directly, and a zero amount is not a goal.
*/
export function proposalGoal(
fundraise: Work['fundraise'],
fundingMechanism: string | undefined
): { value: number; currency: string } | undefined {
if (!fundraise || fundingMechanism === 'AWARD') return undefined;
const value =
fundraise.goalCurrency === 'USD' ? fundraise.goalAmount.usd : fundraise.goalAmount.rsc;
if (value <= 0) return undefined;
return { value, currency: fundraise.goalCurrency };
}

/**
* The grant's stored amount. `usd` is float(grant.amount); `rsc` is an exchange
* conversion of that number, so the published value stays `usd`. `currency` is
* the unit of the stored amount.
*/
export function storedGrantAmount(
amount: { usd: number } | undefined,
currency: string | undefined
): { value: number; currency: string } | undefined {
if (!amount || !currency) return undefined;
return { value: amount.usd, currency };
}

/** Proposals this grant has put money toward. Open applications with nothing raised are not funded yet. */
function fundedGrantItems(
applications: Grant['applications']
): Array<{ name: string; url: string }> {
return (applications ?? []).flatMap((application) => {
const raised = application.fundraise?.amountRaised;
const hasMoney = (raised?.usd ?? 0) > 0 || (raised?.rsc ?? 0) > 0;
const postId = application.preregistrationPostId;
const name = application.fundraise?.title;
if (!hasMoney || postId == null || !name) return [];
return [{ name, url: `${SITE_CONFIG.url}/proposal/${postId}` }];
});
}

/** schema.org data for a work page: a grant, a proposal, a paper, or the generic article. */
function buildWorkStructuredData(work: Work, url: string, description: string) {
const absoluteUrl = `${SITE_CONFIG.url}${url}`;

if (work.contentType === 'funding_request') {
const grant = work.note?.post?.grant;
if (grant) {
return generateGrantStructuredData({
title: work.title,
description: stripHtml(grant.description || ''),
url: absoluteUrl,
organization: grant.organization,
amount: storedGrantAmount(grant.amount, grant.currency),
status: grant.status,
endDate: grant.endDate,
fundingMechanism: grant.fundingMechanism,
image: work.image,
alternateName:
grant.shortTitle && grant.shortTitle !== work.title ? grant.shortTitle : undefined,
fundedItems: fundedGrantItems(grant.applications),
});
}
}

if (work.contentType === 'preregistration') {
const fundraise = work.fundraise;
return generateProposalStructuredData({
title: work.title,
description,
url: absoluteUrl,
funder: work.linkedGrant?.organization || undefined,
goal: proposalGoal(fundraise, work.linkedGrant?.fundingMechanism),
status: fundraise?.status,
endDate: fundraise?.endDate,
fundingMechanism: work.linkedGrant?.fundingMechanism,
fundingName: work.linkedGrant?.shortTitle || work.linkedGrant?.title || undefined,
fundingUrl: work.linkedGrant?.postId
? `${SITE_CONFIG.url}/rfp/${work.linkedGrant.postId}`
: undefined,
image: work.image,
members: work.authors
.filter((author) => author.authorProfile?.fullName)
.map((author) => ({
name: author.authorProfile.fullName,
url: author.authorProfile.profileUrl
? `${SITE_CONFIG.url}${author.authorProfile.profileUrl}`
: undefined,
})),
});
}

return generateDocumentStructuredData({
...work,
schemaType: work.contentType === 'paper' ? 'ScholarlyArticle' : undefined,
authors: work.authors?.map((a) => ({
name: a.authorProfile?.fullName || '',
url: a.authorProfile?.profileUrl,
})),
});
}

export function getWorkMetadata({
work,
url,
Expand All @@ -34,13 +143,7 @@ export function getWorkMetadata({
const description = getWorkDescription(work);
const topics = work.contentType === 'paper' ? work.topics : undefined;

const structuredData = generateDocumentStructuredData({
...work,
authors: work.authors?.map((a) => ({
name: a.authorProfile?.fullName || '',
url: a.authorProfile?.profileUrl,
})),
});
const structuredData = buildWorkStructuredData(work, url, description);

const articleMetadata = buildArticleMetadata({
title,
Expand Down
Loading