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
2 changes: 0 additions & 2 deletions backend/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import profile from "routes/profile.js";
import auth from "routes/auth.js";
import support from "routes/support.js";
import taxonomy from "routes/taxonomy.js";
import piper from "routes/piper.js";
import region from "routes/region.js";
import ebirdProxy from "routes/ebird-proxy.js";
import invites from "routes/invites.js";
Expand All @@ -27,7 +26,6 @@ app.route("/v1/trips", trips);
app.route("/v1/auth", auth);
app.route("/v1/support", support);
app.route("/v1/taxonomy", taxonomy);
app.route("/v1/piper", piper);
app.route("/v1/region", region);
app.route("/v1/ebird-proxy", ebirdProxy);
app.route("/v1/invites", invites);
Expand Down
1 change: 1 addition & 0 deletions backend/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export const RESET_TOKEN_EXPIRATION = 12; // hours
export const OPENBIRDING_API_URL = process.env.OPENBIRDING_API_URL;
4 changes: 1 addition & 3 deletions backend/lib/db.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import Trip from "models/Trip.js";
import Profile from "models/Profile.js";
import TargetList from "models/TargetList.js";
import Invite from "models/Invite.js";
import Vault from "models/Vault.js";
import mongoose from "mongoose";

let isConnected = false;
Expand Down Expand Up @@ -44,4 +42,4 @@ export async function connect() {
}
}

export { Trip, Profile, TargetList, Invite, Vault };
export { Trip, Profile, Invite };
39 changes: 30 additions & 9 deletions backend/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { HTTPException } from "hono/http-exception";
import type { Context } from "hono";
import { auth } from "lib/firebaseAdmin.js";
import { customAlphabet } from "nanoid";
import type { Trip, TargetList, Hotspot } from "@birdplan/shared";
import type { Trip, Hotspot } from "@birdplan/shared";

export const nanoId = (length: number = 16) => {
return customAlphabet("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length)();
Expand Down Expand Up @@ -63,18 +63,18 @@ export function sanitizeFileName(fileName: string): string {
return sanitized.trim();
}

const targetsToHtml = (targets: TargetList[], id?: string) => {
const items = targets.find((it) => it._id === id)?.items;
const targetsToHtml = (items?: { name: string; frequency: number; code?: string }[]) => {
if (!items?.length) {
return "";
}
let html = "<b>Targets</b><br/>";
items.forEach((it) => {
html += `<b>${it.name}</b> (${it.percentYr}%)<br/>`;
const percent = it.percentYr;
const numBlocks = Math.round(percent / 10) * 1;
const freq = it.frequency > 1 ? Math.round(it.frequency) : it.frequency;
html += `<b>${it.name}</b> (${freq}%)<br/>`;
const numBlocks = Math.round(freq / 10);
const blocks = "🟩".repeat(numBlocks) + "⬜".repeat(10 - numBlocks);
html += `<a href='merlinbirdid://species/${it.code}' style="text-decoration:none">${blocks} ℹ️</a><br/><br/>`;
const code = it.code ? `<a href='merlinbirdid://species/${it.code}' style="text-decoration:none">${blocks} ℹ️</a>` : blocks;
html += `${code}<br/><br/>`;
});
return html;
};
Expand All @@ -95,7 +95,10 @@ const favsToHtml = (favs: Hotspot["favs"]) => {
return html + "<br/><br/>";
};

export const tripToGeoJson = (trip: Trip, targets: TargetList[]) => {
export const tripToGeoJson = (
trip: Trip,
hotspotTargets: Record<string, { name: string; frequency: number; code?: string }[]>
) => {
const hotspots = trip?.hotspots || [];
const markers = trip?.markers || [];

Expand All @@ -113,7 +116,7 @@ export const tripToGeoJson = (trip: Trip, targets: TargetList[]) => {
it.id
}&bmo=1&emo=12&r2=world&t2=life'>Targets</a><br/><br/><b>Notes</b><br/>${
it.notes || "None"
}<br/><br/>${favsToHtml(it.favs)}${targetsToHtml(targets, it.targetsId)}<br/><br/>`,
}<br/><br/>${favsToHtml(it.favs)}${targetsToHtml(hotspotTargets[it.id])}<br/><br/>`,
},
geometry: {
type: "Point",
Expand All @@ -139,6 +142,24 @@ export const tripToGeoJson = (trip: Trip, targets: TargetList[]) => {
return geojson;
};

export function getMonthRange(startMonth: number, endMonth: number): number[] {
const months: number[] = [];
let m = startMonth;
while (true) {
months.push(m);
if (m === endMonth) break;
m = m === 12 ? 1 : m + 1;
}
return months;
}

export function computeFrequency(obs: number[], samples: number[], months: number[]): number {
const totalObs = months.reduce((sum, m) => sum + (obs[m - 1] || 0), 0);
const totalSamples = months.reduce((sum, m) => sum + (samples[m - 1] || 0), 0);
if (totalSamples === 0) return 0;
return Number(((totalObs / totalSamples) * 100).toFixed(1));
}

export const mostFrequentValue = (arr: any[]) => {
const filteredArr = arr.filter(Boolean);
if (!filteredArr.length) return null;
Expand Down
33 changes: 0 additions & 33 deletions backend/models/TargetList.ts

This file was deleted.

1 change: 0 additions & 1 deletion backend/models/Trip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ const fields: Record<keyof Omit<Trip, "createdAt" | "updatedAt">, any> = {
lng: { type: Number, required: true },
notes: String,
species: Number,
targetsId: String,
favs: [
{
_id: false,
Expand Down
17 changes: 0 additions & 17 deletions backend/models/Vault.ts

This file was deleted.

3 changes: 1 addition & 2 deletions backend/routes/account.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Hono } from "hono";
import { authenticate } from "lib/utils.js";
import { connect, Profile, Trip, TargetList, Invite } from "lib/db.js";
import { connect, Profile, Trip, Invite } from "lib/db.js";
import { auth as firebaseAuth } from "lib/firebaseAdmin.js";
import { HTTPException } from "hono/http-exception";

Expand All @@ -18,7 +18,6 @@ account.delete("/", async (c) => {

await Promise.all([
Profile.deleteOne({ uid }),
TargetList.deleteMany({ tripId: { $in: tripIds } }),
Invite.deleteMany({ tripId: { $in: tripIds } }),
Invite.deleteMany({ uid }),
Trip.deleteMany({ ownerId: uid }),
Expand Down
40 changes: 0 additions & 40 deletions backend/routes/piper.ts

This file was deleted.

94 changes: 3 additions & 91 deletions backend/routes/trips/[tripId]/hotspots.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,8 @@
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { authenticate } from "lib/utils.js";
import { connect, Trip, TargetList } from "lib/db.js";
import type {
HotspotInput,
HotspotNotesInput,
TargetListInput,
HotspotFav,
SpeciesFavInput,
TranslateNameResponse,
} from "@birdplan/shared";
import { TargetListType } from "@birdplan/shared";
import { connect, Trip } from "lib/db.js";
import type { HotspotInput, HotspotNotesInput, HotspotFav, SpeciesFavInput, TranslateNameResponse } from "@birdplan/shared";
import * as deepl from "deepl-node";
import axios from "axios";
import dayjs from "dayjs";
Expand Down Expand Up @@ -48,90 +40,10 @@ hotspots.delete("/:hotspotId", async (c) => {
if (!trip) throw new HTTPException(404, { message: "Trip not found" });
if (!trip.userIds.includes(session.uid)) throw new HTTPException(403, { message: "Forbidden" });

await Promise.all([
Trip.updateOne({ _id: tripId }, { $pull: { hotspots: { id: hotspotId } } }),
TargetList.deleteMany({ tripId, hotspotId }),
]);
await Trip.updateOne({ _id: tripId }, { $pull: { hotspots: { id: hotspotId } } });
return c.json({});
});

hotspots.patch("/:hotspotId/reset-targets", async (c) => {
const session = await authenticate(c);

const tripId = c.req.param("tripId");
const hotspotId = c.req.param("hotspotId");
if (!tripId) throw new HTTPException(400, { message: "Trip ID is required" });
if (!hotspotId) throw new HTTPException(400, { message: "Hotspot ID is required" });

await connect();
const trip = await Trip.findById(tripId).lean();
if (!trip) throw new HTTPException(404, { message: "Trip not found" });
if (!trip.userIds.includes(session.uid)) throw new HTTPException(403, { message: "Forbidden" });

const hotspot = trip.hotspots.find((it) => it.id === hotspotId);
if (!hotspot) throw new HTTPException(404, { message: "Hotspot not found" });

await Promise.all([
Trip.updateOne({ _id: tripId, "hotspots.id": hotspotId }, { $unset: { "hotspots.$.targetsId": "" } }),
TargetList.deleteMany({ tripId, hotspotId }),
]);

return c.json({});
});

hotspots.get("/:hotspotId/targets", async (c) => {
const session = await authenticate(c);

const tripId = c.req.param("tripId");
const hotspotId = c.req.param("hotspotId");
if (!tripId) throw new HTTPException(400, { message: "Trip ID is required" });
if (!hotspotId) throw new HTTPException(400, { message: "Hotspot ID is required" });

await connect();
const [trip, targetList] = await Promise.all([
Trip.findById(tripId),
TargetList.findOne({ type: TargetListType.hotspot, tripId, hotspotId }).sort({ createdAt: -1 }),
]);
if (!trip) throw new HTTPException(404, { message: "Trip not found" });
if (!trip.isPublic && (!session?.uid || !trip.userIds.includes(session.uid)))
throw new HTTPException(403, { message: "Forbidden" });

return c.json(targetList || null);
});

hotspots.patch("/:hotspotId/targets", async (c) => {
const session = await authenticate(c);

const tripId = c.req.param("tripId");
if (!tripId) throw new HTTPException(400, { message: "Trip ID is required" });

const data = await c.req.json<TargetListInput>();

await connect();
const trip = await Trip.findById(tripId).lean();
if (!trip) throw new HTTPException(404, { message: "Trip not found" });
if (!trip.userIds.includes(session.uid)) throw new HTTPException(403, { message: "Forbidden" });

if (!data.hotspotId) throw new HTTPException(400, { message: "Hotspot ID is required" });
const targetList = await TargetList.findOneAndUpdate(
{ type: TargetListType.hotspot, tripId, hotspotId: data.hotspotId },
{
...data,
type: TargetListType.hotspot,
tripId,
hotspotId: data.hotspotId,
},
{ upsert: true, new: true }
);
if (targetList._id) {
await Trip.updateOne(
{ _id: tripId, "hotspots.id": data.hotspotId },
{ $set: { "hotspots.$.targetsId": targetList._id } }
);
}
return c.json({ id: targetList._id });
});

hotspots.patch("/:hotspotId/translate-name", async (c) => {
const session = await authenticate(c);

Expand Down
Loading
Loading