Skip to content

Commit

Permalink
Merge branch 'ayush/2075' of github.com:quadratichq/quadratic into ai…
Browse files Browse the repository at this point in the history
…-prompt-logging
  • Loading branch information
AyushAgrawal-A2 committed Jan 10, 2025
2 parents 8f03c26 + 4172c38 commit 57f3c67
Show file tree
Hide file tree
Showing 31 changed files with 799 additions and 106 deletions.
1 change: 1 addition & 0 deletions .env.docker
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ QUADRATIC_CLIENT_IN_DOCKER_COMPOSE=true
QUADRATIC_API_IN_DOCKER_COMPOSE=true
QUADRATIC_API_URL_EXTERNAL=http://localhost:8000
QUADRATIC_API_URL_INTERNAL=http://host.docker.internal:8000
QUADRATIC_API_CORS=*

# multiplayer
QUADRATIC_MULTIPLAYER_IN_DOCKER_COMPOSE=true
Expand Down
33 changes: 30 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ services:
service: quadratic-api
container_name: api
environment:
CORS: "*"
CORS: ${QUADRATIC_API_CORS}
DATABASE_URL: ${DATABASE_DSN}
ENVIRONMENT: ${ENVIRONMENT}
STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY}
Expand Down
10 changes: 6 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions quadratic-api/src/ai/docs/FormulaDocs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,12 @@ Returns the counterclockwise angle, in radians, from the X axis to the point \`(
If both arguments are zero, returns zero.
## Financial functions
| **Function** | **Description** |
| ------------ | --------------- |
| \`PMT(rate, nper, pv, [fv], [type])\` | Calculates the payment for a loan based on constant payments and a constant interest rate. Rate is the interest rate per period (e.g., 0.08/12 for 8% annual rate with monthly payments), nper is the total number of payments (e.g., 5*12 for 5 years of monthly payments), pv is the present value (loan amount), fv is the future value (default 0), and type indicates when payments are due (0=end of period, 1=beginning of period, default 0). Returns the negative of the payment amount. |
## Statistics functions
| **Function** | **Description** |
Expand All @@ -371,6 +377,8 @@ If both arguments are zero, returns zero.
| \`COUNTIFS(eval_range1, criteria1, [more_eval_ranges_and_criteria...])\` | Evaluates multiple values on they're respective criteria, and then counts how many sets of values met all their criteria. See [the documentation](https://docs.quadratichq.com/formulas) for more details about how criteria work in formulas. |
| \`MIN([numbers...])\` | Returns the smallest value. Returns +∞ if given no values. |
| \`MAX([numbers...])\` | Returns the largest value. Returns -∞ if given no values. |
| \`STDEV([numbers...])\` | Returns the standard deviation of all values. |
| \`VAR([numbers...])\` | Returns the variance of all values. |
### COUNT
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export function EmptyGridMessage() {
</div>
<h2 className="text-md font-semibold">Import data</h2>
<p className="text-sm text-muted-foreground">
Bring in your own data via a file (CSV, Excel, Parquet) or a connection (Postgres, MySQL, and more).
Drag and drop a file (CSV, Excel, Parquet) or use a connection (Postgres, MySQL, and more).
</p>
<div className="mt-2 flex w-full flex-col justify-center gap-2">
<UploadFileButton teamUuid={teamUuid} />
Expand Down
2 changes: 1 addition & 1 deletion quadratic-client/src/routes/examples.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const Component = () => {

const files: FilesListExampleFile[] = examples.map(({ name, description, thumbnail, url }, i) => ({
description,
href: ROUTES.CREATE_FILE_EXAMPLE(activeTeamUuid, url, true),
href: ROUTES.CREATE_FILE_EXAMPLE(activeTeamUuid, url),
name,
thumbnail: thumbnail + '?w=800&h=450&fit=crop&auto=format', // 16/9 aspect ratio
}));
Expand Down
27 changes: 24 additions & 3 deletions quadratic-client/src/routes/files.create.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,36 @@
import getActiveTeam from '@/dashboard/shared/getActiveTeam';
import { apiClient } from '@/shared/api/apiClient';
import { ROUTES } from '@/shared/constants/routes';
import { ROUTES, SEARCH_PARAMS } from '@/shared/constants/routes';
import { LoaderFunctionArgs, redirect } from 'react-router-dom';

export const loader = async ({ request }: LoaderFunctionArgs) => {
const url = new URL(request.url);
const prompt = url.searchParams.get('prompt');

// Get the active team
const { teams } = await apiClient.teams.list();
const { teamUuid } = await getActiveTeam(teams, undefined);

const redirectUrl = ROUTES.CREATE_FILE(teamUuid, { prompt, private: true });
// Ensure the active team is _writeable_. If it's not, redirect them to the dashboard.
// (They may have write access to another team, but not the 'active' one.)
const team = teams.find(({ team }) => team.uuid === teamUuid);
if (!team?.userMakingRequest.teamPermissions.includes('TEAM_EDIT')) {
return redirect(
`/?${SEARCH_PARAMS.SNACKBAR_MSG.KEY}=${encodeURIComponent('Failed to create file. You can only view this team.')}`
);
}

// Are they trying to duplicate an example file? Do that.
const example = url.searchParams.get('example');
if (example) {
return redirect(ROUTES.CREATE_FILE_EXAMPLE(teamUuid, example));
}

// Otherwise, start a new file by redirecting them to the file creation route
const redirectUrl = ROUTES.CREATE_FILE(teamUuid, {
// Are they creating a new file with a prompt?
prompt: url.searchParams.get('prompt'),
// Creating via this route is _always_ private
private: true,
});
return redirect(redirectUrl);
};
4 changes: 2 additions & 2 deletions quadratic-client/src/shared/components/ShareDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export function ShareTeamDialog({ data }: { data: ApiTypes['/v0/teams/:uuid.GET.
)}

{license.status === 'exceeded' && (
<div className="relative rounded border border-red-400 bg-red-100 px-4 py-3 text-red-700" role="alert">
<div className="relative rounded border border-red-400 bg-red-100 px-4 py-3 text-sm text-red-700" role="alert">
<div>
<strong className="font-bold">Over the user limit!</strong>
</div>
Expand All @@ -132,7 +132,7 @@ export function ShareTeamDialog({ data }: { data: ApiTypes['/v0/teams/:uuid.GET.
)}

{license.status === 'revoked' && (
<div className="relative rounded border border-red-400 bg-red-100 px-4 py-3 text-red-700" role="alert">
<div className="relative rounded border border-red-400 bg-red-100 px-4 py-3 text-sm text-red-700" role="alert">
<div>
<strong className="font-bold">License Revoked!</strong>
</div>
Expand Down
4 changes: 2 additions & 2 deletions quadratic-client/src/shared/constants/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ export const ROUTES = {

return url.toString();
},
CREATE_FILE_EXAMPLE: (teamUuid: string, publicFileUrlInProduction: string, isPrivate: boolean) =>
`/teams/${teamUuid}/files/create?example=${publicFileUrlInProduction}${isPrivate ? '&private' : ''}`,
CREATE_FILE_EXAMPLE: (teamUuid: string, publicFileUrlInProduction: string) =>
`/teams/${teamUuid}/files/create?example=${publicFileUrlInProduction}&private`,
TEAMS: `/teams`,
TEAMS_CREATE: `/teams/create`,
TEAM: (teamUuid: string) => `/teams/${teamUuid}`,
Expand Down
1 change: 1 addition & 0 deletions quadratic-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ bincode = "1.3.3"
flate2 = "1.0.30"
serde_with = "3.8.1"
dateparser = "0.2.1"
fancy-regex = "0.14.0"

[dev-dependencies]
criterion = { version = "0.4", default-features = false }
Expand Down
44 changes: 44 additions & 0 deletions quadratic-core/src/a1/a1_selection/a1_selection_mutate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,25 @@ impl A1Selection {
selection.translate_in_place(x, y);
selection
}

pub fn adjust_column_row_in_place(
&mut self,
column: Option<i64>,
row: Option<i64>,
delta: i64,
) {
self.cursor.adjust_column_row_in_place(column, row, delta);
self.ranges.iter_mut().for_each(|range| {
range.adjust_column_row_in_place(column, row, delta);
});
}
}

#[cfg(test)]
#[serial_test::parallel]
mod tests {
use crate::{grid::SheetId, SheetNameIdMap};

use super::*;

#[test]
Expand Down Expand Up @@ -426,4 +440,34 @@ mod tests {
assert_eq!(translated, A1Selection::test_a1("A1"));
assert_eq!(selection, A1Selection::test_a1("A1"));
}

#[test]
fn test_adjust_column_row() {
let sheet_id = SheetId::test();
let sheet_map = SheetNameIdMap::new();

let mut selection = A1Selection::test_a1("B3");
selection.adjust_column_row_in_place(Some(2), None, 1);
assert_eq!(selection.to_string(Some(sheet_id), &sheet_map), "C3");

let mut selection = A1Selection::test_a1("B3");
selection.adjust_column_row_in_place(None, Some(2), 1);
assert_eq!(selection.to_string(Some(sheet_id), &sheet_map), "B4");

let mut selection = A1Selection::test_a1("B3");
selection.adjust_column_row_in_place(Some(3), None, 1);
assert_eq!(selection.to_string(Some(sheet_id), &sheet_map), "B3");

let mut selection = A1Selection::test_a1("B3");
selection.adjust_column_row_in_place(None, Some(4), 1);
assert_eq!(selection.to_string(Some(sheet_id), &sheet_map), "B3");

let mut selection = A1Selection::test_a1("B3");
selection.adjust_column_row_in_place(Some(1), None, -1);
assert_eq!(selection.to_string(Some(sheet_id), &sheet_map), "A3");

let mut selection = A1Selection::test_a1("B3");
selection.adjust_column_row_in_place(None, Some(1), -1);
assert_eq!(selection.to_string(Some(sheet_id), &sheet_map), "B2");
}
}
13 changes: 12 additions & 1 deletion quadratic-core/src/a1/a1_selection/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,9 +188,12 @@ impl A1Selection {
let mut current_segment = String::new();
let mut in_quotes = false;

for c in a1.chars() {
for (i, c) in a1.trim().chars().enumerate() {
match c {
'\'' => {
if !in_quotes && i > 0 {
return Err(A1Error::InvalidSheetName(a1.to_string()));
}
in_quotes = !in_quotes;
current_segment.push(c);
}
Expand Down Expand Up @@ -632,6 +635,14 @@ mod tests {
);
}

#[test]
fn test_invalid_sheet_name() {
assert_eq!(
A1Selection::from_str("Sheet' 1'!A1", &SheetId::test(), &HashMap::new()),
Err(A1Error::InvalidSheetName("Sheet' 1'!A1".to_string())),
);
}

#[test]
fn test_different_sheet() {
let sheet_id = SheetId::test();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ impl GridController {
}
_ => {
let mut new_code = code.clone();
new_code.adjust_code_cell_column_row(column, row, delta);
let sheet_map = self.grid.sheet_name_id_map();
new_code.adjust_code_cell_column_row(
column, row, delta, &sheet_id, &sheet_map,
);
new_code.code
}
};
Expand Down Expand Up @@ -434,7 +437,7 @@ mod tests {
gc.set_code_cell(
sheet_pos,
CodeCellLanguage::Python,
"q.cells('B1:B2')".into(),
r#"q.cells("B1:B2")"#.into(),
None,
);

Expand Down Expand Up @@ -470,7 +473,7 @@ mod tests {
sheet_pos,
values: CellValue::Code(CodeCellValue {
language: CodeCellLanguage::Python,
code: "q.cells('B1:B3')".to_string()
code: r#"q.cells("B1:B3")"#.to_string()
})
.into(),
}
Expand Down Expand Up @@ -510,7 +513,7 @@ mod tests {
gc.set_code_cell(
sheet_pos,
CodeCellLanguage::Javascript,
"return q.cells('B1:B2');".into(),
r#"return q.cells("B1:B2");"#.into(),
None,
);

Expand Down Expand Up @@ -546,7 +549,7 @@ mod tests {
sheet_pos,
values: CellValue::Code(CodeCellValue {
language: CodeCellLanguage::Javascript,
code: "return q.cells('B1:B3');".to_string()
code: r#"return q.cells("B1:B3");"#.to_string()
})
.into(),
}
Expand Down
2 changes: 1 addition & 1 deletion quadratic-core/src/controller/formula.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ mod tests {

fn parse(s: &str) -> FormulaParseResult {
println!("Parsing {s}");

parse_formula(s, crate::Pos::ORIGIN)
}

Expand Down
8 changes: 7 additions & 1 deletion quadratic-core/src/controller/operations/autocomplete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,13 @@ impl GridController {
.filter_map(|(i, Pos { x, y })| {
if let Some((CellValue::Code(code_cell), original_pos)) = series.get_mut(i) {
if let Some(original_pos) = original_pos {
code_cell.update_cell_references(x - original_pos.x, y - original_pos.y);
let sheet_map = self.grid.sheet_name_id_map();
code_cell.update_cell_references(
x - original_pos.x,
y - original_pos.y,
&sheet_id,
&sheet_map,
);
original_pos.x = x;
original_pos.y = y;
}
Expand Down
Loading

0 comments on commit 57f3c67

Please sign in to comment.