initial commit
This commit is contained in:
commit
b58358b37a
|
@ -0,0 +1 @@
|
|||
/target
|
|
@ -0,0 +1,5 @@
|
|||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
|
@ -0,0 +1,11 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="CPP_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/backend/src" isTestSource="false" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/backend/target" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/lmspos.iml" filepath="$PROJECT_DIR$/.idea/lmspos.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
|
@ -0,0 +1,2 @@
|
|||
target
|
||||
lms.bonsaidb
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "lmspos"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
simple_logger = "4"
|
||||
actix-web = "4"
|
||||
bonsaidb = { version = "0.4", features = ["local-full"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
actix-cors = "0.6.4"
|
|
@ -0,0 +1,10 @@
|
|||
use bonsaidb::core::schema::Collection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Collection)]
|
||||
#[collection(name = "products")]
|
||||
pub struct Product {
|
||||
pub name: String,
|
||||
pub price_usd: f64,
|
||||
pub stock: u64
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct APIError {
|
||||
pub code: String,
|
||||
pub message: String
|
||||
}
|
|
@ -0,0 +1,54 @@
|
|||
use std::error::Error;
|
||||
use actix_cors::Cors;
|
||||
use actix_web::{App, get, HttpResponse, HttpServer};
|
||||
use actix_web::web::Data;
|
||||
use bonsaidb::core::schema::Schema;
|
||||
use bonsaidb::local::AsyncDatabase;
|
||||
use bonsaidb::local::config::{Builder, StorageConfiguration};
|
||||
|
||||
use crate::db_products::Product;
|
||||
use crate::route_products::{create_product, delete_product, get_product, get_products, update_product};
|
||||
|
||||
pub mod db_products;
|
||||
pub mod route_products;
|
||||
pub mod error;
|
||||
|
||||
#[derive(Debug, Schema)]
|
||||
#[schema(name = "lmsposschema", collections = [Product])]
|
||||
pub struct DbSchema;
|
||||
|
||||
pub struct AppState {
|
||||
pub db: AsyncDatabase
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
simple_logger::init_with_env()?;
|
||||
|
||||
let db = AsyncDatabase::open::<DbSchema>(StorageConfiguration::new("lms.bonsaidb")).await?;
|
||||
|
||||
let state = Data::new(AppState {
|
||||
db
|
||||
});
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.wrap(Cors::permissive())
|
||||
.app_data(state.clone())
|
||||
.service(get_products)
|
||||
.service(create_product)
|
||||
.service(update_product)
|
||||
.service(get_product)
|
||||
.service(delete_product)
|
||||
.service(status)
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.run()
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[get("/status")]
|
||||
pub async fn status() -> HttpResponse {
|
||||
HttpResponse::Ok().body("{\"status\":\"ok\"}")
|
||||
}
|
|
@ -0,0 +1,176 @@
|
|||
use actix_web::{get, post, HttpResponse, put, delete};
|
||||
use actix_web::web::{Data, Json, Path};
|
||||
use bonsaidb::core::schema::SerializedCollection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::AppState;
|
||||
use crate::db_products::Product;
|
||||
use crate::error::APIError;
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ProductsResponse {
|
||||
pub products: Vec<ProductResponse>
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ProductResponse {
|
||||
pub id: u64,
|
||||
pub name: String,
|
||||
pub price_usd: f64,
|
||||
pub stock: u64
|
||||
}
|
||||
|
||||
#[get("/products")]
|
||||
pub async fn get_products(db: Data<AppState>) -> HttpResponse {
|
||||
let products = match Product::list_async(0.., &db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let resp: Vec<ProductResponse> = products.iter().map(|u| ProductResponse { name: u.contents.name.clone(), price_usd: u.contents.price_usd, id: u.header.id, stock: u.contents.stock }).collect();
|
||||
|
||||
HttpResponse::Ok().json(ProductsResponse { products: resp })
|
||||
}
|
||||
|
||||
#[get("/products/{id}")]
|
||||
pub async fn get_product(id: Path<u64>, db: Data<AppState>) -> HttpResponse {
|
||||
let product = match Product::get_async(id.into_inner(), &db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let document = match product {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
return HttpResponse::NotFound().finish();
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().json(ProductResponse {
|
||||
id: document.header.id,
|
||||
name: document.contents.name.clone(),
|
||||
price_usd: document.contents.price_usd,
|
||||
stock: document.contents.stock,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct CreateProductRequest {
|
||||
pub name: String,
|
||||
pub price_usd: f64,
|
||||
pub stock: u64
|
||||
}
|
||||
|
||||
#[post("/products")]
|
||||
pub async fn create_product(req: Json<CreateProductRequest>, db: Data<AppState>) -> HttpResponse {
|
||||
let document = Product {
|
||||
name: req.name.clone(),
|
||||
price_usd: req.price_usd,
|
||||
stock: req.stock
|
||||
};
|
||||
let document = match document.push_into_async(&db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().json(ProductResponse {
|
||||
id: document.header.id,
|
||||
name: document.contents.name,
|
||||
price_usd: document.contents.price_usd,
|
||||
stock: document.contents.stock
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct UpdateProductRequest {
|
||||
pub name: String,
|
||||
pub price_usd: f64,
|
||||
pub stock: u64
|
||||
}
|
||||
|
||||
#[put("/products/{id}")]
|
||||
pub async fn update_product(id: Path<u64>, req: Json<CreateProductRequest>, db: Data<AppState>) -> HttpResponse {
|
||||
let document = match Product::get_async(id.into_inner(), &db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let mut document = match document {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
return HttpResponse::NotFound().finish();
|
||||
}
|
||||
};
|
||||
|
||||
document.contents.stock = req.stock;
|
||||
document.contents.name = req.name.clone();
|
||||
document.contents.price_usd = req.price_usd;
|
||||
|
||||
match document.update_async(&db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().json(ProductResponse {
|
||||
id: document.header.id,
|
||||
name: document.contents.name,
|
||||
price_usd: document.contents.price_usd,
|
||||
stock: document.contents.stock
|
||||
})
|
||||
}
|
||||
|
||||
#[delete("/products/{id}")]
|
||||
pub async fn delete_product(id: Path<u64>, db: Data<AppState>) -> HttpResponse {
|
||||
let document = match Product::get_async(id.into_inner(), &db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
let document = match document {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
return HttpResponse::NotFound().finish();
|
||||
}
|
||||
};
|
||||
|
||||
match document.delete_async(&db.db).await {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
return HttpResponse::InternalServerError().json(APIError {
|
||||
code: "DB_ERROR".to_string(),
|
||||
message: e.to_string(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
HttpResponse::Ok().finish()
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
.DS_Store
|
||||
node_modules
|
||||
/build
|
||||
/.svelte-kit
|
||||
/package
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
|
@ -0,0 +1,2 @@
|
|||
engine-strict=true
|
||||
resolution-mode=highest
|
|
@ -0,0 +1,38 @@
|
|||
# create-svelte
|
||||
|
||||
Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
|
||||
|
||||
## Creating a project
|
||||
|
||||
If you're seeing this, you've probably already done this step. Congrats!
|
||||
|
||||
```bash
|
||||
# create a new project in the current directory
|
||||
npm create svelte@latest
|
||||
|
||||
# create a new project in my-app
|
||||
npm create svelte@latest my-app
|
||||
```
|
||||
|
||||
## Developing
|
||||
|
||||
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
|
||||
|
||||
```bash
|
||||
npm run dev
|
||||
|
||||
# or start the server and open the app in a new browser tab
|
||||
npm run dev -- --open
|
||||
```
|
||||
|
||||
## Building
|
||||
|
||||
To create a production version of your app:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
You can preview the production build with `npm run preview`.
|
||||
|
||||
> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
|
|
@ -0,0 +1,37 @@
|
|||
{
|
||||
"name": "frontend",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "vite dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
|
||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||
"prepare": "npm run smui-theme-light && npm run smui-theme-dark",
|
||||
"smui-theme-light": "smui-theme compile static/smui.css -i src/theme",
|
||||
"smui-theme-dark": "smui-theme compile static/smui-dark.css -i src/theme/dark"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@smui/button": "^7.0.0-beta.8",
|
||||
"@smui/card": "^7.0.0-beta.8",
|
||||
"@smui/circular-progress": "^7.0.0-beta.8",
|
||||
"@smui/data-table": "^7.0.0-beta.8",
|
||||
"@smui/dialog": "^7.0.0-beta.8",
|
||||
"@smui/icon-button": "^7.0.0-beta.8",
|
||||
"@smui/linear-progress": "^7.0.0-beta.8",
|
||||
"@smui/paper": "^7.0.0-beta.8",
|
||||
"@smui/snackbar": "^7.0.0-beta.8",
|
||||
"@smui/textfield": "^7.0.0-beta.8",
|
||||
"@smui/touch-target": "^7.0.0-beta.8",
|
||||
"@sveltejs/adapter-auto": "^2.0.0",
|
||||
"@sveltejs/kit": "^1.5.0",
|
||||
"smui-theme": "^7.0.0-beta.8",
|
||||
"svelte": "^3.54.0",
|
||||
"svelte-check": "^3.0.1",
|
||||
"tslib": "^2.4.1",
|
||||
"typescript": "^5.0.0",
|
||||
"vite": "^4.3.0"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
// See https://kit.svelte.dev/docs/types#app
|
||||
// for information about these interfaces
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface Platform {}
|
||||
}
|
||||
}
|
||||
|
||||
export {};
|
|
@ -0,0 +1,34 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
|
||||
<meta name="viewport" content="width=device-width" />
|
||||
%sveltekit.head%
|
||||
<!-- SMUI Styles -->
|
||||
<link rel="stylesheet" href="/smui.css" media="(prefers-color-scheme: light)" />
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="/smui-dark.css"
|
||||
media="screen and (prefers-color-scheme: dark)"
|
||||
/>
|
||||
<!-- Material Icons -->
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/icon?family=Material+Icons"
|
||||
/>
|
||||
<!-- Roboto -->
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,600,700"
|
||||
/>
|
||||
<!-- Roboto Mono -->
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="https://fonts.googleapis.com/css?family=Roboto+Mono"
|
||||
/>
|
||||
</head>
|
||||
<body data-sveltekit-preload-data="hover">
|
||||
<div style="display: contents">%sveltekit.body%</div>
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,11 @@
|
|||
import type { Writable } from "svelte/store";
|
||||
import {writable} from "svelte/store";
|
||||
import {browser} from "$app/environment";
|
||||
|
||||
export function persist(name: string, def_val = ""): Writable<any> {
|
||||
const store = writable(browser && localStorage.getItem(name) || def_val);
|
||||
store.subscribe((value: any) => {
|
||||
if (browser) return (localStorage.setItem(name, value));
|
||||
});
|
||||
return store;
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
<script lang="ts">
|
||||
import Button, { Label } from '@smui/button';
|
||||
import Wrapper from '@smui/touch-target';
|
||||
|
||||
export let selected;
|
||||
</script>
|
||||
|
||||
<div class="header">
|
||||
<Wrapper>
|
||||
<Button on:click={() => {window.location.href = "/"}} disabled={selected === "pos"}>
|
||||
<Label>PoS</Label>
|
||||
</Button>
|
||||
</Wrapper>
|
||||
|
||||
<Wrapper>
|
||||
<Button on:click={() => {window.location.href = "/manage/products"}} disabled={selected === "manage/products"}>
|
||||
<Label>Manage Products</Label>
|
||||
</Button>
|
||||
</Wrapper>
|
||||
|
||||
<Wrapper>
|
||||
<Button on:click={() => {window.location.href = "/manage/env"}} disabled={selected === "manage/env"}>
|
||||
<Label>Manage Env</Label>
|
||||
</Button>
|
||||
</Wrapper>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.header {
|
||||
width: 100%;
|
||||
|
||||
}
|
||||
</style>
|
|
@ -0,0 +1,3 @@
|
|||
import { persist } from "$lib/PersistentStore";
|
||||
|
||||
export const serverUrl = persist("server", "http://localhost:8080");
|
|
@ -0,0 +1,5 @@
|
|||
<script lang="ts">
|
||||
import Header from "$lib/components/Header.svelte";
|
||||
</script>
|
||||
|
||||
<Header selected="pos" />
|
|
@ -0,0 +1,93 @@
|
|||
<script lang="ts">
|
||||
import Paper, {Title as PaperTitle, Subtitle as PaperSubtitle, Content as PaperContent} from "@smui/paper";
|
||||
import Button, {Label} from "@smui/button";
|
||||
import Dialog, {Actions, Title as DialogTitle, Content as DialogContent} from "@smui/dialog";
|
||||
import Textfield from "@smui/textfield";
|
||||
import HelperText from "@smui/textfield/helper-text";
|
||||
import Header from "$lib/components/Header.svelte";
|
||||
import {serverUrl} from "$lib/stores/ServerStore";
|
||||
|
||||
import Snackbar from "@smui/snackbar";
|
||||
|
||||
let snackbarTesting: Snackbar;
|
||||
let snackbarTestSuccess: Snackbar;
|
||||
let snackbarTestFailure: Snackbar;
|
||||
let changeServerUrlOpen = false;
|
||||
|
||||
let changeServerUrlFocused;
|
||||
let changeServerUrlDirty;
|
||||
let newServerUrl = $serverUrl;
|
||||
let changeServerUrlInvalid;
|
||||
|
||||
async function testServerConnection() {
|
||||
snackbarTesting.open();
|
||||
try {
|
||||
let resp = await fetch(`${$serverUrl}/status`);
|
||||
if (resp.ok) {
|
||||
let json = await resp.json();
|
||||
if (json.status === "ok") {
|
||||
// ok!
|
||||
snackbarTesting.close();
|
||||
snackbarTestSuccess.open();
|
||||
return;
|
||||
} else {
|
||||
console.error("Response .status was not ok");
|
||||
snackbarTesting.close();
|
||||
snackbarTestFailure.open();
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
snackbarTesting.close();
|
||||
snackbarTestFailure.open();
|
||||
return;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Header selected="manage/env" />
|
||||
|
||||
<Paper>
|
||||
<PaperTitle>Server URL</PaperTitle>
|
||||
<PaperSubtitle>Configure the URL that LMSPOS uses to connect to the backend.</PaperSubtitle>
|
||||
<PaperContent>
|
||||
<p>Current: <pre>{$serverUrl}</pre>
|
||||
<Button variant="raised" on:click={() => {changeServerUrlOpen = true}}>
|
||||
<Label>Change</Label>
|
||||
</Button>
|
||||
<Button variant="outlined" on:click={testServerConnection}>
|
||||
<Label>Test</Label>
|
||||
</Button>
|
||||
</PaperContent>
|
||||
</Paper>
|
||||
|
||||
<Snackbar bind:this={snackbarTesting}>
|
||||
<Label>Testing server connection, this may take a moment...</Label>
|
||||
</Snackbar>
|
||||
<Snackbar bind:this={snackbarTestSuccess}>
|
||||
<Label>Connection successful!</Label>
|
||||
</Snackbar>
|
||||
<Snackbar bind:this={snackbarTestFailure}>
|
||||
<Label>Connection failed. Check browser console for details.</Label>
|
||||
</Snackbar>
|
||||
|
||||
<Dialog bind:open={changeServerUrlOpen} aria-labelledby="change-title" aria-describedby="change-content">
|
||||
<DialogTitle id="change-title">Change server URL</DialogTitle>
|
||||
<DialogContent id="change-content">
|
||||
This is the URL that LMSPOS will use to connect to it's backend. It is <i>highly recommended</i> that you use the "Test" button to ensure this is working properly before proceeding. <br>
|
||||
<Textfield type="url" bind:dirty={changeServerUrlDirty} bind:invalid={changeServerUrlInvalid} updateInvalid bind:value={newServerUrl} label="Server URL" on:focus={() => {changeServerUrlFocused = true}} on:blur={() => {changeServerUrlFocused = false}}>
|
||||
<HelperText validationMsg slot="helper">
|
||||
That's not a valid URL.
|
||||
</HelperText>
|
||||
</Textfield>
|
||||
</DialogContent>
|
||||
<Actions>
|
||||
<Button on:click={() => {serverUrl.set(newServerUrl); window.location.reload();}}>
|
||||
<Label>Save</Label>
|
||||
</Button>
|
||||
<Button on:click={() => {changeServerUrlOpen = false; newServerUrl = $serverUrl;}}>
|
||||
<Label>Cancel</Label>
|
||||
</Button>
|
||||
</Actions>
|
||||
</Dialog>
|
|
@ -0,0 +1,312 @@
|
|||
<script lang="ts">
|
||||
import Header from "$lib/components/Header.svelte";
|
||||
|
||||
import DataTable, { Head, Body, Row, Cell } from '@smui/data-table';
|
||||
import IconButton from "@smui/icon-button";
|
||||
import LinearProgress from '@smui/linear-progress';
|
||||
import Snackbar, {Label as SnackbarLabel} from "@smui/snackbar";
|
||||
import { onMount } from 'svelte';
|
||||
import {serverUrl} from "$lib/stores/ServerStore";
|
||||
import Textfield from "@smui/textfield";
|
||||
import HelperText from "@smui/textfield/helper-text";
|
||||
import Button, {Label as ButtonLabel} from "@smui/button";
|
||||
import Dialog, {Actions, Title as DialogTitle, Content as DialogContent} from "@smui/dialog";
|
||||
|
||||
let loaded = false;
|
||||
let products = [];
|
||||
|
||||
let failureSnackbar: Snackbar;
|
||||
let failureSnackbarText = "";
|
||||
|
||||
const formatter = new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'});
|
||||
|
||||
async function loadProducts() {
|
||||
loaded = false;
|
||||
try {
|
||||
let resp = await fetch(`${$serverUrl}/products`);
|
||||
if (resp.ok) {
|
||||
let json = await resp.json();
|
||||
console.log(json);
|
||||
products = json.products;
|
||||
loaded = true;
|
||||
} else {
|
||||
console.error(await resp.text());
|
||||
failureSnackbarText = "There was an error loading the products list. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
failureSnackbarText = "There was an error loading the products list. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
await loadProducts();
|
||||
});
|
||||
|
||||
let productEditOpen = false;
|
||||
let editingProductID = 0;
|
||||
|
||||
let editNameDirty;
|
||||
let editNameFocused;
|
||||
let editName = "";
|
||||
|
||||
let editPriceDirty;
|
||||
let editPriceInvalid;
|
||||
let editPriceFocused;
|
||||
let editPrice = 0.0;
|
||||
|
||||
let editStockDirty;
|
||||
let editStockInvalid;
|
||||
let editStockFocused;
|
||||
let editStock = 0;
|
||||
|
||||
$: canFinishEdit = (!(editStockInvalid || editPriceInvalid));
|
||||
|
||||
function editProduct(product) {
|
||||
console.log(product);
|
||||
editingProductID = product.id;
|
||||
editName = product.name;
|
||||
editPrice = product.price_usd;
|
||||
editStock = product.stock;
|
||||
productEditOpen = true;
|
||||
}
|
||||
|
||||
async function finishEdit() {
|
||||
loaded = false;
|
||||
try {
|
||||
let resp = await fetch(`${$serverUrl}/products/${editingProductID}`, {
|
||||
method: 'PUT',
|
||||
headers: [
|
||||
['Content-Type', 'application/json']
|
||||
],
|
||||
body: JSON.stringify({
|
||||
name: editName,
|
||||
price_usd: editPrice,
|
||||
stock: editStock
|
||||
})
|
||||
});
|
||||
if (resp.ok) {
|
||||
loaded = true;
|
||||
productEditOpen = false;
|
||||
await loadProducts();
|
||||
} else {
|
||||
console.error(await resp.text());
|
||||
failureSnackbarText = "There was an error editing the product. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
failureSnackbarText = "There was an error editing the product. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let deletingProduct = false;
|
||||
let deletingProductId = 0;
|
||||
|
||||
async function deleteProduct(id) {
|
||||
deletingProduct = true;
|
||||
deletingProductId = id;
|
||||
}
|
||||
|
||||
async function deleteProductConfirmed(id) {
|
||||
deletingProduct = false;
|
||||
loaded = false;
|
||||
try {
|
||||
let resp = await fetch(`${$serverUrl}/products/${id}`, {method: 'DELETE'});
|
||||
if (resp.ok) {
|
||||
loaded = true;
|
||||
await loadProducts();
|
||||
} else {
|
||||
console.error(await resp.text());
|
||||
failureSnackbarText = "There was an error deleting the product. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
failureSnackbarText = "There was an error deleting the product. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let productCreateOpen = false;
|
||||
|
||||
let createNameDirty;
|
||||
let createNameFocused;
|
||||
let createName = "";
|
||||
|
||||
let createPriceDirty;
|
||||
let createPriceInvalid;
|
||||
let createPriceFocused;
|
||||
let createPrice = 0.0;
|
||||
|
||||
let createStockDirty;
|
||||
let createStockInvalid;
|
||||
let createStockFocused;
|
||||
let createStock = 0;
|
||||
|
||||
$: canFinishCreate = (!(createStockInvalid || createPriceInvalid));
|
||||
|
||||
function createProduct() {
|
||||
createName = "New product"
|
||||
createPrice = 1.00;
|
||||
createStock = 10;
|
||||
productCreateOpen = true;
|
||||
}
|
||||
|
||||
async function finishCreate() {
|
||||
loaded = false;
|
||||
try {
|
||||
let resp = await fetch(`${$serverUrl}/products`, {
|
||||
method: 'POST',
|
||||
headers: [
|
||||
['Content-Type', 'application/json']
|
||||
],
|
||||
body: JSON.stringify({
|
||||
name: createName,
|
||||
price_usd: createPrice,
|
||||
stock: createStock
|
||||
})
|
||||
});
|
||||
if (resp.ok) {
|
||||
loaded = true;
|
||||
productCreateOpen = false;
|
||||
await loadProducts();
|
||||
} else {
|
||||
console.error(await resp.text());
|
||||
failureSnackbarText = "There was an error creating the product. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
failureSnackbarText = "There was an error creating the product. Check the browser console for more information.";
|
||||
failureSnackbar.open();
|
||||
loaded = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<Header selected="manage/products"></Header>
|
||||
|
||||
<DataTable table$aria-label="Product list" style="width: 100%;">
|
||||
<Head>
|
||||
<Row>
|
||||
<Cell numeric>ID</Cell>
|
||||
<Cell style="width: 70%;">Name</Cell>
|
||||
<Cell>Price</Cell>
|
||||
<Cell>Stock</Cell>
|
||||
<Cell>
|
||||
Actions
|
||||
</Cell>
|
||||
</Row>
|
||||
</Head>
|
||||
<Body>
|
||||
{#each products as product (product.id)}
|
||||
<Row>
|
||||
<Cell numeric>{product.id}</Cell>
|
||||
<Cell>{product.name}</Cell>
|
||||
<Cell>{formatter.format(product.price_usd)}</Cell>
|
||||
<Cell>{product.stock}</Cell>
|
||||
<Cell>
|
||||
<IconButton class="material-icons" on:click={() => {editProduct(product)}}>edit</IconButton>
|
||||
<IconButton style="color: #f44336;" class="material-icons" on:click={() => {deleteProduct(product.id)}}>delete</IconButton>
|
||||
</Cell>
|
||||
</Row>
|
||||
{/each}
|
||||
</Body>
|
||||
|
||||
<LinearProgress indeterminate bind:closed={loaded} aria-label="Data is being loaded..." slot="progress" />
|
||||
</DataTable>
|
||||
|
||||
<Button on:click={createProduct}>
|
||||
<ButtonLabel>Create Product</ButtonLabel>
|
||||
</Button>
|
||||
|
||||
<Snackbar bind:this={failureSnackbar}>
|
||||
<SnackbarLabel>{failureSnackbarText}</SnackbarLabel>
|
||||
</Snackbar>
|
||||
|
||||
<Dialog bind:open={productEditOpen} aria-labelledby="edit-title" aria-describedby="edit-content">
|
||||
<DialogTitle id="edit-title">Edit product</DialogTitle>
|
||||
<DialogContent id="change-content">
|
||||
<Textfield type="text" bind:dirty={editNameDirty} bind:value={editName} label="Product Name" on:focus={() => {editNameFocused = true}} on:blur={() => {editNameFocused = false}}>
|
||||
</Textfield>
|
||||
<Textfield input$step="0.01" input$min="0" type="number" bind:dirty={editPriceDirty} bind:invalid={editPriceInvalid} updateInvalid bind:value={editPrice} label="Product Price" on:focus={() => {editPriceFocused = true}} on:blur={() => {editPriceFocused = false}}>
|
||||
<HelperText validationMsg slot="helper">
|
||||
That's not a valid price.
|
||||
</HelperText>
|
||||
</Textfield>
|
||||
<Textfield input$min="0" type="number" bind:dirty={editStockDirty} bind:invalid={editStockInvalid} updateInvalid bind:value={editStock} label="Product Stock" on:focus={() => {editStockFocused = true}} on:blur={() => {editStockFocused = false}}>
|
||||
<HelperText validationMsg slot="helper">
|
||||
That's not a valid stock.
|
||||
</HelperText>
|
||||
</Textfield>
|
||||
</DialogContent>
|
||||
<Actions>
|
||||
<Button disabled={!canFinishEdit} on:click={finishEdit}>
|
||||
<ButtonLabel>Save</ButtonLabel>
|
||||
</Button>
|
||||
<Button>
|
||||
<ButtonLabel>Cancel</ButtonLabel>
|
||||
</Button>
|
||||
</Actions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog bind:open={productCreateOpen} aria-labelledby="create-title" aria-describedby="create-content">
|
||||
<DialogTitle id="create-title">Create product</DialogTitle>
|
||||
<DialogContent id="create-content">
|
||||
<Textfield type="text" bind:dirty={createNameDirty} bind:value={createName} label="Product Name" on:focus={() => {createNameFocused = true}} on:blur={() => {createNameFocused = false}}>
|
||||
</Textfield>
|
||||
<Textfield input$step="0.01" input$min="0" type="number" bind:dirty={createPriceDirty} bind:invalid={createPriceInvalid} updateInvalid bind:value={createPrice} label="Product Price" on:focus={() => {createPriceFocused = true}} on:blur={() => {createPriceFocused = false}}>
|
||||
<HelperText validationMsg slot="helper">
|
||||
That's not a valid price.
|
||||
</HelperText>
|
||||
</Textfield>
|
||||
<Textfield input$min="0" type="number" bind:dirty={createStockDirty} bind:invalid={createStockInvalid} updateInvalid bind:value={createStock} label="Product Stock" on:focus={() => {createStockFocused = true}} on:blur={() => {createStockFocused = false}}>
|
||||
<HelperText validationMsg slot="helper">
|
||||
That's not a valid stock.
|
||||
</HelperText>
|
||||
</Textfield>
|
||||
</DialogContent>
|
||||
<Actions>
|
||||
<Button disabled={!canFinishCreate} on:click={finishCreate}>
|
||||
<ButtonLabel>Create</ButtonLabel>
|
||||
</Button>
|
||||
<Button>
|
||||
<ButtonLabel>Cancel</ButtonLabel>
|
||||
</Button>
|
||||
</Actions>
|
||||
</Dialog>
|
||||
|
||||
<Dialog bind:open={deletingProduct} aria-labelledby="delete-title" aria-describedby="delete-content">
|
||||
<DialogTitle id="edit-title">Are you sure?</DialogTitle>
|
||||
<DialogContent id="change-content">
|
||||
This is an irreversible action. You will not be able to get this product back if you delete it. Are you sure you want to delete this product?
|
||||
</DialogContent>
|
||||
<Actions>
|
||||
<Button on:click={() => {deletingProduct = false}}>
|
||||
<ButtonLabel>Cancel</ButtonLabel>
|
||||
</Button>
|
||||
<Button on:click={() => {deleteProductConfirmed(deletingProductId)}}>
|
||||
<ButtonLabel>I'm sure</ButtonLabel>
|
||||
</Button>
|
||||
</Actions>
|
||||
</Dialog>
|
|
@ -0,0 +1,25 @@
|
|||
@use 'sass:color';
|
||||
|
||||
@use '@material/theme/color-palette';
|
||||
|
||||
// Svelte Colors!
|
||||
@use '@material/theme/index' as theme with (
|
||||
$primary: #ff3e00,
|
||||
$secondary: #676778,
|
||||
$surface: #fff,
|
||||
$background: #fff,
|
||||
$error: color-palette.$red-900
|
||||
);
|
||||
|
||||
html,
|
||||
body {
|
||||
background-color: theme.$surface;
|
||||
color: theme.$on-surface;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #40b3ff;
|
||||
}
|
||||
a:visited {
|
||||
color: color.scale(#40b3ff, $lightness: -35%);
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
@use 'sass:color';
|
||||
|
||||
@use '@material/theme/color-palette';
|
||||
|
||||
// Svelte Colors! (Dark Theme)
|
||||
@use '@material/theme/index' as theme with (
|
||||
$primary: #ff3e00,
|
||||
$secondary: color.scale(#676778, $whiteness: -10%),
|
||||
$surface: color.adjust(color-palette.$grey-900, $blue: +4),
|
||||
$background: #000,
|
||||
$error: color-palette.$red-700
|
||||
);
|
||||
|
||||
html,
|
||||
body {
|
||||
background-color: #000;
|
||||
color: theme.$on-surface;
|
||||
}
|
||||
|
||||
a {
|
||||
color: #40b3ff;
|
||||
}
|
||||
a:visited {
|
||||
color: color.scale(#40b3ff, $lightness: -35%);
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 1.5 KiB |
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,18 @@
|
|||
import adapter from '@sveltejs/adapter-auto';
|
||||
import { vitePreprocess } from '@sveltejs/kit/vite';
|
||||
|
||||
/** @type {import('@sveltejs/kit').Config} */
|
||||
const config = {
|
||||
// Consult https://kit.svelte.dev/docs/integrations#preprocessors
|
||||
// for more information about preprocessors
|
||||
preprocess: vitePreprocess(),
|
||||
|
||||
kit: {
|
||||
// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
|
||||
// If your environment is not supported or you settled on a specific environment, switch out the adapter.
|
||||
// See https://kit.svelte.dev/docs/adapters for more information about adapters.
|
||||
adapter: adapter()
|
||||
}
|
||||
};
|
||||
|
||||
export default config;
|
|
@ -0,0 +1,17 @@
|
|||
{
|
||||
"extends": "./.svelte-kit/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"allowJs": true,
|
||||
"checkJs": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"skipLibCheck": true,
|
||||
"sourceMap": true,
|
||||
"strict": true
|
||||
}
|
||||
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias
|
||||
//
|
||||
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
|
||||
// from the referenced tsconfig.json - TypeScript does not merge them in
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
import { sveltekit } from '@sveltejs/kit/vite';
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [sveltekit()]
|
||||
});
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue