Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Save detour creation snapshot to db #2729

Merged
merged 25 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
15d9028
Posts to db but author is null
hannahpurcell Jul 30, 2024
f9adc45
Save snapshot to db
hannahpurcell Aug 5, 2024
3f6038a
Formatting
hannahpurcell Aug 5, 2024
ab2556e
Use db id for detour as uuid instead of frontend-created one
hannahpurcell Aug 8, 2024
6b08b9a
formatting
hannahpurcell Aug 8, 2024
2fe30e6
Send not really needed in dependency array, but lint complained
hannahpurcell Aug 8, 2024
1daeac7
Fix event name to prioritize uuid
hannahpurcell Aug 12, 2024
a79b43a
Update putDetourUpdate to apiCallResult + useDetour snapshot subscrip…
hannahpurcell Aug 14, 2024
a398d08
Improve typing in new api call
hannahpurcell Aug 20, 2024
ca9f3fb
fix: Tweaked syntax in detours_controller
hannahpurcell Aug 20, 2024
6462a00
Include transitional state for saving-in-progress
hannahpurcell Aug 20, 2024
7142fa6
Formatting
hannahpurcell Aug 20, 2024
71ed919
fix: typo
hannahpurcell Aug 22, 2024
80d66f1
tweak: typing
hannahpurcell Aug 22, 2024
87e37ee
fix: typing correction
hannahpurcell Aug 22, 2024
fc7cb6c
tests!
hannahpurcell Aug 22, 2024
db14199
fix: typo!
hannahpurcell Aug 22, 2024
bf5483a
Merge branch 'main' into hp/test-branch-saving-to-db
hannahpurcell Aug 22, 2024
f1c3ea4
fix: formatting
hannahpurcell Aug 22, 2024
ffbccb8
fix: Split out tests
hannahpurcell Aug 22, 2024
8480c77
fix: redacted change
hannahpurcell Aug 22, 2024
de0f904
Missed some words in a comment!
hannahpurcell Aug 23, 2024
e2b84f1
Missed some words in second comment!
hannahpurcell Aug 23, 2024
b109fb8
fix: test adjustment
hannahpurcell Aug 23, 2024
8603420
Merge branch 'hp/test-branch-saving-to-db' of https://github.com/mbta…
hannahpurcell Aug 23, 2024
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
16 changes: 16 additions & 0 deletions assets/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,22 @@ export const putRouteTabs = (routeTabs: RouteTab[]): Promise<Response> =>
body: JSON.stringify({ route_tabs: routeTabs }),
})

export const putDetourUpdate = (snapshot: any): Promise<string | null> =>
checkedApiCall({
url: `/api/detours/update_snapshot`,
parser: nullableParser((id: string) => id),
dataStruct: any(),
defaultResult: null,
fetchArgs: {
method: "PUT",
headers: {
"Content-Type": "application/json",
"x-csrf-token": getCsrfToken(),
},
body: JSON.stringify({ snapshot: snapshot }),
},
})
firestack marked this conversation as resolved.
Show resolved Hide resolved

const getCsrfToken = (): string => appData()?.csrfToken || ""

export const nullableParser =
Expand Down
14 changes: 10 additions & 4 deletions assets/src/hooks/useDetour.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useCallback } from "react"
import { ShapePoint } from "../schedule"
import { fetchUnfinishedDetour } from "../api"
import { fetchUnfinishedDetour, putDetourUpdate } from "../api"
import { useApiCall } from "./useApiCall"
import { isErr, isOk } from "../util/result"
import { useNearestIntersection } from "./useNearestIntersection"
Expand All @@ -27,15 +27,21 @@ export const useDetour = (input: UseDetourInput) => {

// Record snapshots when changed
useEffect(() => {
const snapshotSubscription = actorRef.subscribe(() => {
const serializedSnapshot = JSON.stringify(actorRef.getPersistedSnapshot())
const snapshotSubscription = actorRef.subscribe((snap) => {
const persistedSnapshot = actorRef.getPersistedSnapshot()
const serializedSnapshot = JSON.stringify(persistedSnapshot)
localStorage.setItem("snapshot", serializedSnapshot)
putDetourUpdate(persistedSnapshot).then((uuid: string | null) => {
if (uuid && snap.matches({ UUID: "Unset" })) {
send({ type: "detour.set.uuid", uuid })
}
hannahpurcell marked this conversation as resolved.
Show resolved Hide resolved
})
})

return () => {
snapshotSubscription.unsubscribe()
}
}, [actorRef])
}, [actorRef, send])

const {
routePattern,
Expand Down
21 changes: 20 additions & 1 deletion assets/src/models/createDetourMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { DetourShape, FinishedDetour } from "./detour"
export const createDetourMachine = setup({
types: {
context: {} as {
uuid: string | undefined
route?: Route
routePattern?: RoutePattern

Expand Down Expand Up @@ -59,6 +60,7 @@ export const createDetourMachine = setup({
| { type: "detour.edit.place-waypoint-on-route"; location: ShapePoint }
| { type: "detour.edit.place-waypoint"; location: ShapePoint }
| { type: "detour.edit.undo" }
| { type: "detour.set.uuid"; uuid: string }
hannahpurcell marked this conversation as resolved.
Show resolved Hide resolved
| { type: "detour.share.copy-detour"; detourText: string },
},
actors: {
Expand Down Expand Up @@ -159,12 +161,13 @@ export const createDetourMachine = setup({
context: ({ input }) => ({
...input,
waypoints: [],
uuid: undefined,
startPoint: undefined,
endPoint: undefined,
finishedDetour: undefined,
detourShape: undefined,
}),

type: "parallel",
initial: "Detour Drawing",
states: {
"Detour Drawing": {
Expand Down Expand Up @@ -415,6 +418,22 @@ export const createDetourMachine = setup({
},
},
},
UUID: {
initial: "Unset",
states: {
Unset: {
on: {
"detour.set.uuid": {
target: "Set",
actions: assign({
uuid: ({ event }) => event.uuid,
}),
},
},
},
Set: {},
},
},
},
})

Expand Down
34 changes: 34 additions & 0 deletions lib/skate/detours/detours.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ defmodule Skate.Detours.Detours do
alias Skate.Repo

alias Skate.Detours.Db.Detour
alias Skate.Settings.User

@doc """
Returns the list of detours.
Expand Down Expand Up @@ -55,6 +56,39 @@ defmodule Skate.Detours.Detours do
|> Repo.insert()
end

@doc """
Creates a detour given a user id & detour id.
"""
def create_detour_for_user(user_id, attrs \\ %{}) do
user = User.get_by_id!(user_id)

%Detour{
author: user
}
|> Detour.changeset(attrs)
|> Repo.insert()
end

@doc """
Update or create a detour given a user id & detour id.
"""
def update_or_create_detour_for_user(user_id, uuid, attrs \\ %{}) do
user = User.get_by_id!(user_id)

case uuid do
nil ->
create_detour_for_user(user_id, attrs)

_ ->
Repo.insert(
Detour.changeset(%Detour{author: user, id: uuid}, attrs),
returning: true,
conflict_target: [:id],
on_conflict: {:replace, [:state, :updated_at]}
)
firestack marked this conversation as resolved.
Show resolved Hide resolved
end
end

@doc """
Updates a detour.

Expand Down
18 changes: 18 additions & 0 deletions lib/skate_web/controllers/detours_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,28 @@ defmodule SkateWeb.DetoursController do
alias Skate.OpenRouteServiceAPI
use SkateWeb, :controller

alias Skate.Detours.Detours
alias Skate.Detours.MissedStops
alias Skate.Detours.RouteSegments
alias SkateWeb.AuthManager
alias Util.Location

@spec update_snapshot(Plug.Conn.t(), map()) :: Plug.Conn.t()
def update_snapshot(conn, %{"snapshot" => %{"context" => context} = snapshot}) do
uuid = Map.get(context, "uuid")

%{id: user_id} = AuthManager.Plug.current_resource(conn)

{:ok, returned_detour} =
Detours.update_or_create_detour_for_user(user_id, uuid, %{
state: snapshot
})

returned_uuid = Map.get(returned_detour, :id)
hannahpurcell marked this conversation as resolved.
Show resolved Hide resolved

json(conn, %{data: returned_uuid})
end

@spec unfinished_detour(Plug.Conn.t(), map()) :: Plug.Conn.t()
def unfinished_detour(conn, %{
"route_pattern_id" => route_pattern_id,
Expand Down
1 change: 1 addition & 0 deletions lib/skate_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ defmodule SkateWeb.Router do
get "/location_search/search", LocationSearchController, :search
get "/location_search/suggest", LocationSearchController, :suggest
post "/detours/directions/", DetourRouteController, :directions
put "/detours/update_snapshot", DetoursController, :update_snapshot
post "/detours/unfinished_detour", DetoursController, :unfinished_detour
post "/detours/finished_detour", DetoursController, :finished_detour
end
Expand Down
Loading