diff --git a/backend/app.py b/backend/app.py index eb4d4ac..2b34ea2 100644 --- a/backend/app.py +++ b/backend/app.py @@ -85,9 +85,9 @@ def api_dashboard(): None Returns: - JSON: user information provided by CAS, all the rides, and - a mapping of available and upcoming rideshares, sorted by - upcoming date + JSON: user information provided by CAS, all upcoming rideshares + (including full ones), sorted by upcoming date, and a mapping + of the user's ride request statuses """ user_info = _cas.authenticate() @@ -112,12 +112,12 @@ def api_dashboard(): "updated_at": ride[9], "current_riders": ride[10], "note": ride[11], + "departure_start": ride[12], + "departure_end": ride[13], } - if ( - updated_ride["arrival_time"] > current_time - and len(updated_ride["current_riders"]) < updated_ride["max_capacity"] - ): + # full rides are included too; Home shows them with a "Full" button + if updated_ride["arrival_time"] > current_time: updated_rides.append(updated_ride) updated_rides.sort(key=lambda ride: ride["arrival_time"]) @@ -170,6 +170,8 @@ def get_my_rides(): "current_riders": ride[11], "requested_riders": ride[12], "phone_number": ride[13], + "departure_start": ride[14], + "departure_end": ride[15], } if updated_ride["arrival_time"] > current_time: @@ -197,6 +199,8 @@ def get_my_rides(): "request_status": ride[12], # only accepted riders get the poster's phone number "phone_number": ride[13] if ride[12] == "accepted" else None, + "departure_start": ride[14], + "departure_end": ride[15], } if updated_ride["arrival_time"] > current_time: @@ -236,9 +240,11 @@ def addride(): arrival_time: a datetime object with the arrival date & time phone_number: the poster's US phone number, shown to accepted riders note (optional): note with the rideshare + departure_start, departure_end (optional): ISO times for the window + the ride leaves in; both or neither, ending by the arrival time Returns: - JSON: a success message + JSON: a success message and the new ride's ride_id 400: if the phone number or note is invalid, or unable to create rideshare """ user_info = _cas.authenticate() @@ -283,11 +289,21 @@ def addride(): arrival_time = data.get("arrival_time") + departure_start, departure_end, window_error = parse_departure_window( + data.get("departure_start"), data.get("departure_end"), arrival_time + ) + if window_error: + return jsonify({"success": False, "message": window_error}), 400 + origin_json = Json(origin) dest_json = Json(dest) + failed = ( + jsonify({"success": False, "message": "Failed to create rideshare."}), + 400, + ) try: - database.create_ride( + ride_id = database.create_ride( user_info["netid"], user_info["displayname"], user_info["mail"], @@ -297,13 +313,63 @@ def addride(): arrival_time, note, phone_number, + departure_start, + departure_end, ) - return jsonify({"success": True, "message": "Rideshare successfully created!"}) - except: - return ( - jsonify({"success": False, "message": "Failed to create rideshare."}), - 400, - ) + except Exception: + return failed + if ride_id is None: + return failed + return jsonify( + { + "success": True, + "message": "Rideshare successfully created!", + "ride_id": ride_id, + } + ) + + +def parse_iso_time(value): + """ + Parses an ISO 8601 time like "2026-11-20T21:00:00.000Z" into a UTC + datetime, or returns None if it's missing or invalid. + """ + if not isinstance(value, str) or not value: + return None + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + if parsed.tzinfo is None: + parsed = parsed.replace(tzinfo=timezone.utc) + return parsed.astimezone(timezone.utc) + + +def parse_departure_window(start, end, arrival_time): + """ + Checks an optional departure window. Both ends or neither must be set; + the window must start before it ends, end by the arrival time, and not + be over already. + + Returns: + (start, end, error): ISO strings to store (or None, None), and an + error message if the window is invalid + """ + if not start and not end: + return None, None, None + + start_time = parse_iso_time(start) + end_time = parse_iso_time(end) + if not start_time or not end_time: + return None, None, "Please give both a start and end for the departure window." + if start_time >= end_time: + return None, None, "The departure window must start before it ends." + arrival = parse_iso_time(arrival_time) + if arrival and end_time > arrival: + return None, None, "The departure window must end by the arrival time." + if end_time <= datetime.now(timezone.utc): + return None, None, "The departure window can't be in the past." + return start, end, None def normalize_phone_number(phone_number): @@ -494,6 +560,8 @@ def searchrides(): "updated_at": ride[9], "current_riders": ride[10], "note": ride[11], + "departure_start": ride[12], + "departure_end": ride[13], } if ( diff --git a/backend/database.py b/backend/database.py index 540a171..133fc50 100644 --- a/backend/database.py +++ b/backend/database.py @@ -148,17 +148,25 @@ def create_ride( arrival_time, note="", phone_number=None, + departure_start=None, + departure_end=None, ): """ - Adds a ride to the Rides database + Adds a ride to the Rides database. departure_start / departure_end are + an optional window for when the ride leaves. + + Returns: + int: the new ride's id, or None if the ride could not be added """ current_riders = [] sql_command = f""" INSERT INTO Rides (admin_netid, admin_name, admin_email, max_capacity, current_riders, - origin_dict, destination_dict, arrival_time, note, phone_number, updated_at) VALUES (%s, %s, %s, %s, - %s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP); + origin_dict, destination_dict, arrival_time, note, phone_number, departure_start, + departure_end, updated_at) VALUES (%s, %s, %s, %s, + %s, %s, %s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP) + RETURNING id; """ values = ( @@ -172,8 +180,11 @@ def create_ride( arrival_time, note, phone_number, + departure_start, + departure_end, ) + ride_id = None conn = connect() # if it was successful connection, execute SQL commands to database & commit @@ -181,15 +192,19 @@ def create_ride( try: with conn.cursor() as cursor: cursor.execute(sql_command, values) + ride_id = cursor.fetchone()[0] conn.commit() print("Ride addded successfully!") except Exception as e: + ride_id = None print(f"Error adding ride: {e}") finally: conn.close() else: print("Connection not established.") + return ride_id + def delete_ride(netid, ride_id): """ @@ -441,7 +456,9 @@ def get_users_rides(netid): ELSE ARRAY[RideRequests.netid, RideRequests.full_name, RideRequests.mail, RideRequests.note] END ) FILTER (WHERE RideRequests.netid IS NOT NULL), ARRAY[]::text[][]) AS riderequesters, - Rides.phone_number + Rides.phone_number, + Rides.departure_start, + Rides.departure_end FROM Rides LEFT JOIN @@ -461,7 +478,9 @@ def get_users_rides(netid): Rides.updated_at, Rides.note, Rides.current_riders, - Rides.phone_number; + Rides.phone_number, + Rides.departure_start, + Rides.departure_end; """ values = (str(netid),) @@ -488,7 +507,8 @@ def get_all_rides(): sql_command = """ SELECT id, admin_netid, admin_name, admin_email, max_capacity, origin_dict, - destination_dict, arrival_time, creation_time, updated_at, current_riders, note FROM Rides + destination_dict, arrival_time, creation_time, updated_at, current_riders, note, + departure_start, departure_end FROM Rides """ conn = connect() @@ -516,7 +536,8 @@ def search_rides( ): query = """ SELECT id, admin_netid, admin_name, admin_email, max_capacity, origin_dict, - destination_dict, arrival_time, creation_time, updated_at, current_riders, note FROM Rides + destination_dict, arrival_time, creation_time, updated_at, current_riders, note, + departure_start, departure_end FROM Rides WHERE 1=1 """ @@ -572,7 +593,8 @@ def get_users_requested_rides(netid): sql_command = """ SELECT Rides.id, admin_netid, admin_name, admin_email, max_capacity, origin_dict, destination_dict, arrival_time, creation_time, updated_at, Rides.note, - current_riders, RideRequests.status as ride_request_status, Rides.phone_number + current_riders, RideRequests.status as ride_request_status, Rides.phone_number, + Rides.departure_start, Rides.departure_end FROM Rides JOIN RideRequests ON Rides.id = RideRequests.ride_id WHERE RideRequests.netid = %s; diff --git a/backend/migrations/002_ride_departure_window.sql b/backend/migrations/002_ride_departure_window.sql new file mode 100644 index 0000000..26ce83f --- /dev/null +++ b/backend/migrations/002_ride_departure_window.sql @@ -0,0 +1,6 @@ +-- Adds an optional departure window to rides ("leave between 4:00 and +-- 5:30PM"). Both columns are nullable, so existing rides without a window +-- still load. + +ALTER TABLE Rides ADD COLUMN IF NOT EXISTS departure_start TIMESTAMP; +ALTER TABLE Rides ADD COLUMN IF NOT EXISTS departure_end TIMESTAMP; diff --git a/backend/schema.sql b/backend/schema.sql index bb4fd7f..3bf23df 100644 --- a/backend/schema.sql +++ b/backend/schema.sql @@ -11,7 +11,9 @@ CREATE TABLE Rides ( updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, current_riders TEXT[][], note VARCHAR(300), - phone_number VARCHAR(20) + phone_number VARCHAR(20), + departure_start TIMESTAMP, + departure_end TIMESTAMP ); CREATE TABLE IF NOT EXISTS RideRequests ( diff --git a/backend/tests/test_add_ride.py b/backend/tests/test_add_ride.py new file mode 100644 index 0000000..351e5a4 --- /dev/null +++ b/backend/tests/test_add_ride.py @@ -0,0 +1,75 @@ +""" +Tests for posting a ride: /api/addride returns the new ride's id, rejects +invalid input without creating a ride, and both posted and requested rides +show up under the user's /api/myrides. +""" + +from datetime import datetime, timedelta, timezone + + +def place(name): + return { + "formatted_address": "1 Main St, Princeton, NJ 08540, USA", + "name": name, + "place_id": "place-" + name, + } + + +def ride_body(**overrides): + body = { + "capacity": 3, + "origin": place("Frist"), + "destination": place("PHL"), + "arrival_time": (datetime.now(timezone.utc) + timedelta(days=2)).isoformat(), + "note": "Meet at the front steps", + "phone_number": "(609) 555-1234", + } + body.update(overrides) + return body + + +def test_addride_returns_new_ride_id(api): + response = api.as_user("poster").post("/api/addride", json=ride_body()) + + assert response.status_code == 200 + data = response.get_json() + assert data["success"] is True + assert isinstance(data["ride_id"], int) + + my_rides = api.as_user("poster").get("/api/myrides").get_json() + posted_ids = [ride["id"] for ride in my_rides["upcoming_posted_rides"]] + assert data["ride_id"] in posted_ids + + +def test_addride_rejects_invalid_phone(api): + response = api.as_user("poster").post( + "/api/addride", json=ride_body(phone_number="123") + ) + + assert response.status_code == 400 + data = response.get_json() + assert data["success"] is False + assert "ride_id" not in data + + my_rides = api.as_user("poster").get("/api/myrides").get_json() + assert my_rides["upcoming_posted_rides"] == [] + + +def test_requested_ride_shows_under_my_rides(api, ride_id): + api.as_user("rider").post( + "/api/requestride", + json={ + "rideid": ride_id, + "origin_name": "Frist", + "destination_name": "EWR", + "formatted_arrival_time": "soon", + "note": "", + }, + ) + + my_rides = api.as_user("rider").get("/api/myrides").get_json() + requested = [ + ride for ride in my_rides["upcoming_requested_rides"] if ride["id"] == ride_id + ] + assert len(requested) == 1 + assert requested[0]["request_status"] == "pending" diff --git a/backend/tests/test_departure_window.py b/backend/tests/test_departure_window.py new file mode 100644 index 0000000..7a62479 --- /dev/null +++ b/backend/tests/test_departure_window.py @@ -0,0 +1,109 @@ +""" +Tests for a ride's optional departure window ("leave between 4:00 and +5:30PM"), set when creating a ride. +""" + +from datetime import datetime, timedelta, timezone + +import pytest + + +def iso(dt): + return dt.isoformat().replace("+00:00", "Z") + + +def create_ride(api, **extra): + place = lambda name: { + "formatted_address": "1 Main St, Princeton, NJ 08540, USA", + "name": name, + "place_id": "place-" + name, + } + return api.as_user("poster").post( + "/api/addride", + json={ + "capacity": 2, + "origin": place("Frist"), + "destination": place("EWR"), + "note": "", + "phone_number": "6095551234", + **extra, + }, + ) + + +@pytest.fixture +def arrival(): + return (datetime.now(timezone.utc) + timedelta(days=3)).replace( + microsecond=0 + ) + + +def test_ride_with_departure_window_is_returned(api, arrival): + start, end = arrival - timedelta(hours=2), arrival - timedelta(hours=1) + + response = create_ride( + api, + arrival_time=iso(arrival), + departure_start=iso(start), + departure_end=iso(end), + ) + + assert response.get_json()["success"] + for netid, path, key in [ + ("rider", "/api/dashboard", "rides"), + ("poster", "/api/myrides", "upcoming_posted_rides"), + ]: + ride = api.as_user(netid).get(path).get_json()[key][0] + assert parse(ride["departure_start"]) == start + assert parse(ride["departure_end"]) == end + + +def test_ride_without_departure_window_still_works(api, arrival): + response = create_ride(api, arrival_time=iso(arrival)) + + assert response.get_json()["success"] + ride = api.as_user("rider").get("/api/dashboard").get_json()["rides"][0] + assert ride["departure_start"] is None + assert ride["departure_end"] is None + + +@pytest.mark.parametrize( + "start_offset, end_offset, message", + [ + (-2, None, "both a start and end"), # only a start + (-1, -2, "start before it ends"), # backwards + (-2, 1, "end by the arrival time"), # ends after arriving + ], +) +def test_invalid_departure_window_is_rejected( + api, arrival, start_offset, end_offset, message +): + window = {"departure_start": iso(arrival + timedelta(hours=start_offset))} + if end_offset is not None: + window["departure_end"] = iso(arrival + timedelta(hours=end_offset)) + + response = create_ride(api, arrival_time=iso(arrival), **window) + + assert response.status_code == 400 + assert message in response.get_json()["message"] + assert api.as_user("rider").get("/api/dashboard").get_json()["rides"] == [] + + +def test_past_departure_window_is_rejected(api): + now = datetime.now(timezone.utc) + response = create_ride( + api, + arrival_time=iso(now + timedelta(hours=1)), + departure_start=iso(now - timedelta(hours=2)), + departure_end=iso(now - timedelta(hours=1)), + ) + + assert response.status_code == 400 + assert "past" in response.get_json()["message"] + + +def parse(http_date): + """Flask returns datetimes as RFC 1123 strings in UTC.""" + return datetime.strptime(http_date, "%a, %d %b %Y %H:%M:%S %Z").replace( + tzinfo=timezone.utc + ) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 94644e1..4ebbb63 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,8 +1,10 @@ import { useState, useEffect } from "react"; import { Navigate, Routes, Route } from "react-router-dom"; import { ConfigProvider } from "antd"; -import AllRides from "./pages/AllRides"; +import Home from "./pages/Home"; +import RideDetails from "./pages/RideDetails"; import MyRides from "./pages/MyRides"; +import ScheduleRide from "./pages/ScheduleRide"; import NotFound from "./pages/NotFound"; import Navbar from "./components/Navbar"; import tailwindConfig from "../tailwind.config.js"; @@ -61,8 +63,13 @@ function App() {
} /> - } /> + } /> + } /> } /> + } + /> } />
diff --git a/frontend/src/assets/figma/alert-circle.svg b/frontend/src/assets/figma/alert-circle.svg new file mode 100644 index 0000000..38dc8e0 --- /dev/null +++ b/frontend/src/assets/figma/alert-circle.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/frontend/src/assets/figma/arrow-40.svg b/frontend/src/assets/figma/arrow-40.svg new file mode 100644 index 0000000..e354877 --- /dev/null +++ b/frontend/src/assets/figma/arrow-40.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/src/assets/figma/arrow-left.svg b/frontend/src/assets/figma/arrow-left.svg new file mode 100644 index 0000000..6c200cf --- /dev/null +++ b/frontend/src/assets/figma/arrow-left.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/figma/avatar.svg b/frontend/src/assets/figma/avatar.svg new file mode 100644 index 0000000..c2f1019 --- /dev/null +++ b/frontend/src/assets/figma/avatar.svg @@ -0,0 +1,3 @@ + + + diff --git a/frontend/src/assets/figma/car.svg b/frontend/src/assets/figma/car.svg new file mode 100644 index 0000000..a8a23d6 --- /dev/null +++ b/frontend/src/assets/figma/car.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/frontend/src/assets/figma/chevron-down.svg b/frontend/src/assets/figma/chevron-down.svg new file mode 100644 index 0000000..a0e69f4 --- /dev/null +++ b/frontend/src/assets/figma/chevron-down.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/figma/menu.svg b/frontend/src/assets/figma/menu.svg new file mode 100644 index 0000000..76b1c97 --- /dev/null +++ b/frontend/src/assets/figma/menu.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/frontend/src/assets/figma/minus.svg b/frontend/src/assets/figma/minus.svg new file mode 100644 index 0000000..8f437fc --- /dev/null +++ b/frontend/src/assets/figma/minus.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/figma/plus.svg b/frontend/src/assets/figma/plus.svg new file mode 100644 index 0000000..e1c38a7 --- /dev/null +++ b/frontend/src/assets/figma/plus.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/figma/search.svg b/frontend/src/assets/figma/search.svg new file mode 100644 index 0000000..b297c27 --- /dev/null +++ b/frontend/src/assets/figma/search.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/assets/figma/switch.svg b/frontend/src/assets/figma/switch.svg new file mode 100644 index 0000000..c254cc4 --- /dev/null +++ b/frontend/src/assets/figma/switch.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/frontend/src/components/CreateRideModal.jsx b/frontend/src/components/CreateRideModal.jsx new file mode 100644 index 0000000..558b94d --- /dev/null +++ b/frontend/src/components/CreateRideModal.jsx @@ -0,0 +1,356 @@ +import { useRef, useState } from "react"; +import Autocomplete from "react-google-autocomplete"; +import { Input, TimePicker } from "antd"; +import Modal from "./Modal.jsx"; +import Dropdown from "./Dropdown.jsx"; +import IconButton from "./IconButton.jsx"; +import DateTimePicker from "./DateTimePicker.jsx"; +import CustomTextArea from "./TextArea.jsx"; +import WarningModal from "./WarningModal.jsx"; +import LiftButton from "./lift/LiftButton.jsx"; +import { + MAX_CAPACITY, + NOTE_MAX_LENGTH, + autocompleteStyling, + flipFields, + normalizePhoneNumber, + placeToLocation, + renderToAndFrom, +} from "../utils/utils"; + +// autocomplete options for location input +const autocompleteOptions = { + fields: ["formatted_address", "geometry", "name", "place_id"], + types: ["establishment", "geocode"], // This will show both businesses and addresses +}; + +// make capacity dropdown options +const capacityOptions = Array.from({ length: MAX_CAPACITY }, (_, i) => ({ + value: i + 1, + label: i + 1, +})); + +// "Create a Rideshare" form. Opened from the navbar on any page. +// onCreated(responseData) is called after the server responds. +export default function CreateRideModal({ isOpen, onClose, onCreated }) { + const google_api_key = import.meta.env.VITE_GOOGLE_API_KEY; // Google API key from environment variables + + const originRef = useRef(null); + const destinationRef = useRef(null); + + const [origin, setOrigin] = useState(null); + const [capacity, setCapacity] = useState(""); + const [dest, setDest] = useState(null); + const [date, setDate] = useState(""); + const [time, setTime] = useState(""); + // optional departure window, on the arrival date + const [departStart, setDepartStart] = useState(null); + const [departEnd, setDepartEnd] = useState(null); + const [rideNote, setRideNote] = useState(""); + const [phoneNumber, setPhoneNumber] = useState(""); + const [isCreatingRide, setIsCreatingRide] = useState(false); + + // validation warning, e.g. for a missing field + const [validationModal, setValidationModal] = useState(null); // { title, message } + + // Closes the modal and resets the form + const handleClose = () => { + setCapacity(""); + setOrigin(null); + setDest(null); + setDate(""); + setTime(""); + setDepartStart(null); + setDepartEnd(null); + setRideNote(""); + setPhoneNumber(""); + originRef.current = null; + destinationRef.current = null; + onClose(); + }; + + const onChange = (e, setFunction) => { + if (!e.target.value) { + setFunction(null); + } + }; + + // Checks if all necessary fields are filled in before creating the ride + const checkCreateRideParams = () => { + let arrivalTime = null; + if (date && time) { + arrivalTime = new Date( + `${date.format("YYYY-MM-DD")}T${time.format("HH:mm:ss")}` + ); + } + + if (arrivalTime && Date.now() >= arrivalTime.getTime()) { + setValidationModal({ + title: "Invalid Input", + message: "Cannot enter a date in the past.", + }); + return; + } + + if ( + !capacity || + !origin || + !dest || + !date || + !time || + !phoneNumber.trim() || + !date.isValid() || + !time.isValid() + ) { + setValidationModal({ + title: "Missing fields", + message: "You must provide all fields to create a ride.", + }); + return; + } + + if (!normalizePhoneNumber(phoneNumber)) { + setValidationModal({ + title: "Invalid Input", + message: "Please enter a valid 10-digit phone number.", + }); + return; + } + + // optional departure window: both times or neither, on the arrival + // date, starting before it ends and ending by the arrival time + let departureWindow = null; + if (departStart || departEnd) { + const onArrivalDate = (t) => + new Date(`${date.format("YYYY-MM-DD")}T${t.format("HH:mm:00")}`); + const windowError = + !departStart || !departEnd + ? "Please give both a start and end for the departure window, or leave both empty." + : onArrivalDate(departStart) >= onArrivalDate(departEnd) + ? "The departure window must start before it ends." + : onArrivalDate(departEnd) > arrivalTime + ? "The departure window must end by the arrival time." + : onArrivalDate(departEnd) <= new Date() + ? "The departure window can't be in the past." + : null; + if (windowError) { + setValidationModal({ title: "Invalid Input", message: windowError }); + return; + } + departureWindow = { + start: onArrivalDate(departStart), + end: onArrivalDate(departEnd), + }; + } + + createRide(arrivalTime, departureWindow); + }; + + // Creates ride by making API call to /addride + const createRide = async (arrivalTime, departureWindow) => { + setIsCreatingRide(true); + let responseData = { + success: false, + message: "Failed to create rideshare.", + }; + try { + const response = await fetch("/api/addride", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ + capacity: capacity["label"], + origin: origin, + destination: dest, + arrival_time: arrivalTime.toISOString(), + note: rideNote, + phone_number: phoneNumber, + departure_start: departureWindow?.start.toISOString() ?? null, + departure_end: departureWindow?.end.toISOString() ?? null, + }), + }); + responseData = await response.json(); + } catch (error) { + console.error("Error during fetch:", error); + } + setIsCreatingRide(false); + if (responseData.success) { + handleClose(); + } + onCreated(responseData); + }; + + return ( + <> + {/* Modal returns early before its hooks when closed, so only mount it + while open */} + {isOpen && ( + +
+
+
+

Capacity

+

+ Number of people you'd like to rideshare with, not + including yourself +

+ +
+
+

Origin & Destination

+
+ { + setOrigin(place); // Store selected place details in state + }} + onChange={(e) => onChange(e, setOrigin)} + options={autocompleteOptions} + ref={originRef} + /> + + flipFields( + origin, + dest, + originRef, + destinationRef, + setOrigin, + setDest + ) + } + > + { + setDest(place); // Store selected place details in state + }} + onChange={(e) => onChange(e, setDest)} + options={autocompleteOptions} + ref={destinationRef} + /> +
+ {/* preview so riders can confirm e.g. PHL vs EWR before posting */} + {origin?.formatted_address && dest?.formatted_address && ( +
+ {renderToAndFrom({ + origin: placeToLocation(origin), + destination: placeToLocation(dest), + })} +
+ )} +
+
+

Arrival Time (in ET)

+ +
+
+

Departure Window (optional)

+

+ When you're planning to leave, on the arrival date +

+
+ + to + +
+
+
+

Phone Number

+

+ Only shown to riders you accept +

+ setPhoneNumber(e.target.value)} + maxLength={20} + /> +
+
+

Optional Note to Riders

+ +
+
+ + Create rideshare + +
+
+ )} + {validationModal && ( + setValidationModal(null)} + title={validationModal.title} + > +
+

{validationModal.message}

+ setValidationModal(null)} + > + Okay + +
+
+ )} + + ); +} diff --git a/frontend/src/components/DateTimePicker.jsx b/frontend/src/components/DateTimePicker.jsx index 2e201a7..fa80909 100644 --- a/frontend/src/components/DateTimePicker.jsx +++ b/frontend/src/components/DateTimePicker.jsx @@ -9,6 +9,19 @@ export default function MyDateTimePicker({ time, setTime, allowClear = true, + // Optional, for pages that restyle or label the pickers (e.g. the + // "lift-picker" look on Schedule a Ride). Defaults keep the old look. + className = "", + datePlaceholder = "Select date", + timePlaceholder = "Select time", + dateId, + timeId, + status, + suffixIcon, + // extra props for each picker, e.g. aria-label / aria-describedby / + // format / popupClassName + dateProps = {}, + timeProps = {}, }) { // on phones, tapping opens the picker without the on-screen keyboard const isMobile = useIsMobile(); @@ -55,18 +68,25 @@ export default function MyDateTimePicker({ }; return ( -
+
); diff --git a/frontend/src/components/IconButton.jsx b/frontend/src/components/IconButton.jsx index 469531e..fe6c2f3 100644 --- a/frontend/src/components/IconButton.jsx +++ b/frontend/src/components/IconButton.jsx @@ -24,6 +24,24 @@ export default function IconButton({ /> ); + case "arrowLeft": + return ( + + ); case "checkmark": return ( { setOpenPanel(null); - navigate("/allrides", { state: { openCreate: true } }); + navigate("/schedule"); }; const onReadNotif = (notif) => { diff --git a/frontend/src/components/RideDetails.jsx b/frontend/src/components/RideDetails.jsx new file mode 100644 index 0000000..d29ac2a --- /dev/null +++ b/frontend/src/components/RideDetails.jsx @@ -0,0 +1,256 @@ +import Button from "./Button"; +import CopyEmailButton from "./CopyEmailButton"; +import { + formatPhoneNumber, + getGoogleCalendarUrl, + tapTargetInline, +} from "../utils/utils"; + +// The extras under a ride's shared card on Your Rides: riders, incoming +// requests (with Accept / Deny styled like the Figma Request Card 132:1596), +// contact details, the calendar link and the note. + +const LINK = `underline text-content-primary hover:text-content-secondary ${tapTargetInline}`; +const COPY = `inline-flex items-center text-content-secondary hover:text-content-primary ${tapTargetInline}`; + +function Section({ title, children }) { + return ( +
+

+ {title} +

+ {children} +
+ ); +} + +// Figma's "Requests" heading: a lime dot (fill-accent) and a subhead, so +// new requests stand out right where they are answered +function RequestsHeading({ count }) { + return ( +

+

+ ); +} + +function Note({ note }) { + if (!note) return null; + return ( +
+

+ “{note}” +

+
+ ); +} + +function CalendarLink({ ride }) { + return ( + + Add to Google Calendar + + ); +} + +const riderNames = (ride) => + ride.current_riders.map((rider) => rider[1]).join(", "); + +function PostedDetails({ ride, respondingTo, onRespond }) { + const riders = ride.current_riders; + const requests = ride.requested_riders || []; + const isFull = riders.length >= ride.max_capacity; + + return ( + <> +
+ {riders.length > 0 ? ( + + ) : ( +

+ No riders yet. +

+ )} +
+ + {requests.length > 0 && ( +
+ +
    + {requests.map(([netid, fullName, , note]) => { + const key = `${ride.id}:${netid}`; + const busy = respondingTo === key; + return ( +
  • +

    + {fullName} wants to join +

    + {note && ( +

    + “{note}” +

    + )} +
    + + +
    + {isFull && ( +

    + Ride is full. Edit to add seats. +

    + )} +
  • + ); + })} +
+
+ )} + + {ride.phone_number && ( +

+ Your phone {formatPhoneNumber(ride.phone_number)}, shown to riders you + accept +

+ )} + + + + ); +} + +function RequestedDetails({ ride }) { + const accepted = ride.request_status === "accepted"; + return ( + <> + {ride.request_status === "removed" && ( +

+ You were removed from this ride. You can request it again from Home. +

+ )} +
+

+ Posted by {ride.admin_name} +

+ +
+ {/* the card already shows the open seats; list riders only if any */} + {ride.current_riders.length > 0 && ( +
+

+ {riderNames(ride)} +

+
+ )} + {accepted && ride.phone_number && ( +

+ Phone:{" "} + + {formatPhoneNumber(ride.phone_number)} + +

+ )} + + {accepted && } + + ); +} + +function PastDetails({ ride }) { + return ( +

+ {ride.kind === "posted" + ? ride.current_riders.length > 0 + ? `You posted this ride. Rode with: ${riderNames(ride)}` + : "You posted this ride. No riders." + : `Posted by ${ride.admin_name}.`} +

+ ); +} + +/** + * Props: + * ride a /api/myrides ride tagged with kind "posted" | "requested" + * isPast whether it is a past ride + * respondingTo "rideid:netid" of the request being answered, or null + * onRespond (ride, netid, "accept" | "reject") for incoming requests + * className extra classes for the panel + */ +export default function RideDetails({ + ride, + isPast, + respondingTo, + onRespond, + className = "", +}) { + return ( +
+ {isPast ? ( + + ) : ride.kind === "posted" ? ( + + ) : ( + + )} +
+ ); +} diff --git a/frontend/src/components/RideEditor.jsx b/frontend/src/components/RideEditor.jsx index 3884d8d..dc87508 100644 --- a/frontend/src/components/RideEditor.jsx +++ b/frontend/src/components/RideEditor.jsx @@ -1,45 +1,57 @@ -// Inline editor shown on a posted ride's card in place of its details +// Inline editor shown on Your Rides in place of a posted ride's card. Built +// from the design-system pieces: the ride card's surface (56:958), the Text +// Input (205:159), the Seat Stepper, Request Card Accept / Deny (132:1596) +// and the button set (10:574). import { useState } from "react"; import dayjs from "dayjs"; import Autocomplete from "react-google-autocomplete"; import Button from "./Button"; -import Dropdown from "./Dropdown"; import DateTimePicker from "./DateTimePicker"; -import CustomTextArea from "./TextArea"; -import IconButton from "./IconButton"; -import Pill from "./Pill"; import WarningModal from "./WarningModal"; +import RouteHeading from "./lift/RouteHeading"; +import SeatStepper from "./lift/SeatStepper"; +import TextField from "./lift/TextField"; +import chevronDown from "../assets/figma/chevron-down.svg"; import { MAX_CAPACITY, - autocompleteStyling, + getShortPlaceName, placeToLocation, - renderToAndFrom, + tapTargetInline, } from "../utils/utils"; +import { fromEasternWallTime, toEasternWallTime } from "../utils/easternTime"; const autocompleteOptions = { fields: ["formatted_address", "geometry", "name", "place_id"], types: ["establishment", "geocode"], }; +// dayjs's timezone plugin is not loaded, so go through Intl for ET const formatForEmail = (dateTime) => - dayjs(dateTime).tz("America/New_York").format("MMMM D, YYYY, h:mm A"); + dayjs(toEasternWallTime(dateTime)).format("MMMM D, YYYY, h:mm A"); + +const LABEL = + "text-mobile-small-bold md:text-desktop-small text-content-primary"; +const HELPER = "text-mobile-small md:text-desktop-small text-content-secondary"; +const SUBHEAD = + "text-mobile-subhead md:text-desktop-subhead text-content-primary"; +const INPUT = + "w-full h-control max-md:h-11 px-4 bg-surface border border-line-strong rounded-lg text-mobile-body md:text-desktop-body text-content-primary placeholder:text-content-placeholder outline-none focus:border-2 focus:border-line-inverse"; export default function RideEditor({ ride, onDone, onCancel }) { const google_api_key = import.meta.env.VITE_GOOGLE_API_KEY; const [origin, setOrigin] = useState(ride.origin); const [destination, setDestination] = useState(ride.destination); - const [arrivalDate, setArrivalDate] = useState(dayjs(ride.arrival_time)); - const [arrivalTime, setArrivalTime] = useState(dayjs(ride.arrival_time)); - const [capacity, setCapacity] = useState({ - value: ride.max_capacity, - label: ride.max_capacity, - }); + // the pickers show and take Eastern time, like Schedule a Ride + const [initialArrival] = useState(() => + dayjs(toEasternWallTime(ride.arrival_time)), + ); + const [arrivalDate, setArrivalDate] = useState(initialArrival); + const [arrivalTime, setArrivalTime] = useState(initialArrival); + const [capacity, setCapacity] = useState(ride.max_capacity); const [note, setNote] = useState(ride.note || ""); const [currentRiders, setCurrentRiders] = useState(ride.current_riders); - const [requestedRiders, setRequestedRiders] = useState( - ride.requested_riders - ); + const [requestedRiders, setRequestedRiders] = useState(ride.requested_riders); const [rejectedRiders, setRejectedRiders] = useState([]); const [isSaving, setIsSaving] = useState(false); @@ -53,9 +65,9 @@ export default function RideEditor({ ride, onDone, onCancel }) { const locationChanged = origin?.id !== ride.origin.id || destination?.id !== ride.destination.id; const timeChanged = - !dayjs(arrivalDate).isSame(dayjs(ride.arrival_time), "day") || - !dayjs(arrivalTime).isSame(dayjs(ride.arrival_time), "minute"); - const capacityChanged = capacity.label !== ride.max_capacity; + !dayjs(arrivalDate).isSame(initialArrival, "day") || + dayjs(arrivalTime).format("HH:mm") !== initialArrival.format("HH:mm"); + const capacityChanged = capacity !== ride.max_capacity; const noteChanged = note !== (ride.note || ""); const ridersChanged = currentRiders.length !== ride.current_riders.length || @@ -73,11 +85,6 @@ export default function RideEditor({ ride, onDone, onCancel }) { arrivalDate?.isValid?.() && arrivalTime?.isValid?.(); - const capacityOptions = []; - for (let i = Math.max(1, currentRiders.length); i <= MAX_CAPACITY; i++) { - capacityOptions.push({ value: i, label: i }); - } - const handleCancel = () => { if (hasChanges) { setWarning({ @@ -92,7 +99,7 @@ export default function RideEditor({ ride, onDone, onCancel }) { }; const handleAcceptRider = (rider) => { - if (currentRiders.length >= capacity.label) { + if (currentRiders.length >= capacity) { setWarning({ title: "Capacity Full", message: `The capacity for this rideshare is full. Please remove a rider before accepting another, or increase the capacity of the rideshare (maximum ${MAX_CAPACITY}).`, @@ -135,9 +142,11 @@ export default function RideEditor({ ride, onDone, onCancel }) { }; const handleSave = () => { - // picked in the browser's timezone, like when creating a ride + // picked in Eastern time, like when creating a ride const new_arrival_time = dayjs( - `${arrivalDate.format("YYYY-MM-DD")}T${arrivalTime.format("HH:mm:ss")}` + fromEasternWallTime( + `${arrivalDate.format("YYYY-MM-DD")}T${arrivalTime.format("HH:mm:ss")}`, + ), ); if (timeChanged && !new_arrival_time.isAfter(dayjs())) { setWarning({ @@ -159,7 +168,7 @@ export default function RideEditor({ ride, onDone, onCancel }) { accepting_riders: currentRiders.map(toRider), rejecting_riders: rejectedRiders.map(toRider), pending_riders: requestedRiders.map(toRider), - new_capacity: capacity.label, + new_capacity: capacity, new_arrival_time: new_arrival_time.toISOString(), formatted_arrival_time: formatForEmail(new_arrival_time), origin_name: origin.name, @@ -191,188 +200,231 @@ export default function RideEditor({ ride, onDone, onCancel }) { }; // any typing invalidates the location until a suggestion is picked - const renderLocationInput = (label, location, setLocation) => ( -
-

{label}

- { - if (place?.place_id) setLocation(placeToLocation(place)); - }} - onChange={() => setLocation(null)} - onKeyDown={(e) => e.key === "Enter" && e.preventDefault()} - options={autocompleteOptions} - /> - {!location && ( -

- Choose a place from the suggestions. -

- )} -
- ); + const renderLocationInput = (label, location, setLocation) => { + const id = `edit-${ride.id}-${label.toLowerCase()}`; + return ( +
+ + { + if (place?.place_id) setLocation(placeToLocation(place)); + }} + onChange={() => setLocation(null)} + onKeyDown={(e) => e.key === "Enter" && e.preventDefault()} + options={autocompleteOptions} + aria-describedby={location ? undefined : `${id}-hint`} + /> + {!location && ( +

+ Choose a place from the suggestions. +

+ )} +
+ ); + }; const isDeleteWarning = warning?.title === "Delete this Rideshare?"; const isInfoWarning = warning?.title === "Capacity Full" || warning?.title === "Invalid Input"; + const timeLabelId = `edit-${ride.id}-time-label`; + return (
- {origin && destination ? ( - renderToAndFrom({ origin, destination }) - ) : ( -

Choose both locations

- )} +
+

Editing your ride

+ {origin && destination ? ( + + ) : ( +

Choose both places

+ )} +
{isLocationLocked ? ( -

- Location is locked because people have joined or requested this - ride. Changing it could send them to the wrong place. +

+ Location is locked because people have joined or requested this ride. + Changing it could send them to the wrong place.

) : ( -
- {renderLocationInput("Origin", origin, setOrigin)} - {renderLocationInput("Destination", destination, setDestination)} +
+ {renderLocationInput("From", origin, setOrigin)} + {renderLocationInput("To", destination, setDestination)}
)} -
-

Arrival Time (in ET)

+
+

+ Arrive by (Eastern time) +

} + dateProps={{ + "aria-label": "Arrival date", + format: ["ddd, MMM D", "M/D/YYYY", "YYYY-MM-DD"], + popupClassName: "lift-picker-popup", + }} + timeProps={{ + "aria-label": "Arrival time", + popupClassName: "lift-picker-popup", + }} /> {ride.current_riders.length > 0 && ( -

+

Current riders will be emailed if you change the time.

)}
-
-

- Capacity{" "} - - ({currentRiders.length} seats taken) - -

- -
+ -
-

Note to Riders

- -
+ setNote(e.target.value)} + /> -
-

Current Riders

+
+

Riders ({currentRiders.length})

{currentRiders.length > 0 ? ( -
+
    {currentRiders.map((rider) => ( - -
    -
    {rider[1]}
    - handleRemoveRider(rider)} - ariaLabel={`Remove ${rider[1]}`} - className="text-zinc-700 hover:text-zinc-500" - /> -
    -
    +
  • + + {rider[1]} + + +
  • ))} -
+ ) : ( -

No current riders.

+

No riders yet.

)}
-
-

Requests to Join

-
- {requestedRiders.length > 0 ? ( - requestedRiders.map((rider) => ( - -
-
- {rider[1]} - {rider[3] && ( - - “{rider[3]}” - - )} -
-
- handleAcceptRider(rider)} - ariaLabel={`Accept ${rider[1]}`} - className="bg-theme_green text-theme_dark_green hover:bg-theme_light_green" - /> - handleRejectRider(rider)} - ariaLabel={`Reject ${rider[1]}`} - className="bg-theme_red text-theme_dark_red hover:bg-theme_light_red" - /> -
-
-
- )) - ) : ( -

No requests to join

+
+

+ {requestedRiders.length > 0 && ( +

-

- Newly accepted riders are emailed when you save. You are - responsible for coordinating logistics with them. + Requests to join ({requestedRiders.length}) +

+ {requestedRiders.length > 0 ? ( +
    + {requestedRiders.map((rider) => ( +
  • +

    {rider[1]} wants to join

    + {rider[3] && ( +

    + “{rider[3]}” +

    + )} +
    + + +
    +
  • + ))} +
+ ) : ( +

No requests to join.

+ )} +

+ Newly accepted riders are emailed when you save. You are responsible + for coordinating logistics with them.

-
+
-
+
@@ -387,18 +439,22 @@ export default function RideEditor({ ride, onDone, onCancel }) { Please give a reason for deleting this rideshare. The riders you have currently accepted will be notified.

- setDeleteRideMessage(e.target.value)} />
)}
{!isInfoWarning && ( )} + ))} +
+ ); +} diff --git a/frontend/src/components/lift/ErrorBanner.jsx b/frontend/src/components/lift/ErrorBanner.jsx new file mode 100644 index 0000000..32d798b --- /dev/null +++ b/frontend/src/components/lift/ErrorBanner.jsx @@ -0,0 +1,31 @@ +import alertIcon from "../../assets/figma/alert-circle.svg"; + +// Error banner from the Figma "Error State" component (node 214:909): an +// alert icon, the message and an optional ghost "Retry" button. +export default function ErrorBanner({ + message, + onRetry, + retryLabel = "Retry", + className = "", +}) { + return ( +
+ +

+ {message} +

+ {onRetry && ( + + )} +
+ ); +} diff --git a/frontend/src/components/lift/PageStates.jsx b/frontend/src/components/lift/PageStates.jsx new file mode 100644 index 0000000..bb3218c --- /dev/null +++ b/frontend/src/components/lift/PageStates.jsx @@ -0,0 +1,47 @@ +import LiftButton from "./LiftButton"; + +// Placeholder blocks shown while ride data loads. +export function RideCardSkeleton() { + return ( +