Compare commits

..
13 Commits
Author SHA1 Message Date
Egor Pozharov 8d6f4a4c52 update docker deploy config 2026-04-14 18:25:47 +06:00
Egor Pozharov 9abc1e3888 add /api proxy 2026-04-14 17:30:43 +06:00
Egor Pozharov 9c9f01b2f2 add pwa 2026-04-14 17:13:47 +06:00
Egor Pozharov cb3f91c17f refactor [2] 2026-04-14 17:11:00 +06:00
Egor Pozharov 9b90a8aa7f frontend refactor 2026-04-14 17:10:13 +06:00
Egor Pozharov 0540218332 switch frontend to real API instead of mocks 2026-04-14 16:17:42 +06:00
Egor Pozharov 7f410e814b add CORS 2026-04-14 16:17:22 +06:00
Egor Pozharov b36a6fb262 add PATCH update delivery status by id 2026-04-14 15:46:32 +06:00
Egor Pozharov d3cd92b9f3 add dockerfile for backend && update docker-compose.yml 2026-04-14 15:39:21 +06:00
Egor Pozharov 10233808f4 add GET delivery count route 2026-04-14 15:38:45 +06:00
Egor Pozharov fc46fb372f update .dockerignore to include nginxproxy 2026-04-14 13:21:13 +06:00
Egor Pozharov 4e0899d3ce chore: restructure project into backend and frontend folders
- Move all frontend code to frontend/ directory
- Add backend/ with Go project structure (cmd, internal, pkg)
- Add docker-compose.yml for orchestration
2026-04-14 13:14:28 +06:00
Egor Pozharov 11e12f964d Initial commit 2026-03-30 17:58:06 +06:00
68 changed files with 13898 additions and 1 deletions
+12
View File
@@ -0,0 +1,12 @@
# Database
POSTGRES_USER=delivery_user
POSTGRES_PASSWORD=your_secure_password_here
POSTGRES_DB=delivery_tracker
# JWT
JWT_SECRET=your_random_jwt_secret_min_32_chars
# Gitea Registry credentials for Watchtower
GITEA_REGISTRY=gitea.your-domain.com/yourusername
GITEA_USER=your_gitea_username
GITEA_TOKEN=your_gitea_token_or_password
+41
View File
@@ -0,0 +1,41 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dev-dist
dist-ssr
*.local
# Environment files
.env
.env.local
.env.*.local
# Testing
coverage
.nyc_output
# Cache
.cache
.temp
.tmp
*.tsbuildinfo
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
.windsurf/*
+72 -1
View File
@@ -1,2 +1,73 @@
# delivery-tracker # React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
+1
View File
@@ -0,0 +1 @@
DATABASE_URL=postgres://egor:barsik@localhost:5432/delivery_tracker
+34
View File
@@ -0,0 +1,34 @@
# Stage 1: Builder
FROM golang:1.25-alpine AS builder
WORKDIR /app
# Install git and build dependencies
RUN apk add --no-cache git
# Copy go mod files
COPY go.mod go.sum ./
RUN go mod download
# Copy source code
COPY . .
# Build the application
RUN CGO_ENABLED=0 GOOS=linux go build -o api ./cmd/api
# Stage 2: Production
FROM alpine:latest AS production
RUN apk --no-cache add ca-certificates
WORKDIR /app
# Copy binary from builder
COPY --from=builder /app/api .
# Copy migrations
COPY internal/db/migrations ./migrations
EXPOSE 8080
CMD ["./api"]
+56
View File
@@ -0,0 +1,56 @@
package main
import (
"context"
"log"
"net/http"
"os"
"time"
db "github.com/chedius/delivery-tracker/internal/db/sqlc"
"github.com/chedius/delivery-tracker/internal/delivery"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
)
func main() {
ctx := context.Background()
godotenv.Load()
dsn := os.Getenv("DATABASE_URL")
pool, err := pgxpool.New(ctx, dsn)
if err != nil {
log.Fatalf("db connect: %v", err)
}
defer pool.Close()
queries := db.New(pool)
h := delivery.NewHandler(queries)
r := gin.Default()
// CORS middleware - allow all origins in development
r.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
AllowCredentials: false,
MaxAge: 12 * time.Hour,
}))
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
})
r.GET("/api/deliveries", h.GetDeliveries)
r.GET("/api/deliveries/:id", h.GetDeliveryByID)
r.GET("/api/deliveries/count", h.GetDeliveryCount)
r.POST("/api/deliveries", h.CreateDelivery)
r.PATCH("/api/deliveries/:id", h.UpdateDelivery)
r.PATCH("/api/deliveries/:id/status", h.UpdateDeliveryStatus)
r.DELETE("/api/deliveries/:id", h.DeleteDelivery)
r.Run(":8080")
}
+50
View File
@@ -0,0 +1,50 @@
module github.com/chedius/delivery-tracker
go 1.25.0
require (
github.com/gin-gonic/gin v1.12.0
github.com/jackc/pgx/v5 v5.9.1
)
require (
github.com/gin-contrib/cors v1.7.7
github.com/google/uuid v1.6.0
)
require (
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
github.com/cloudwego/base64x v0.1.6 // indirect
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.30.1 // indirect
github.com/goccy/go-json v0.10.5 // indirect
github.com/goccy/go-yaml v1.19.2 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
github.com/joho/godotenv v1.5.1
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.3.1 // indirect
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
golang.org/x/arch v0.23.0 // indirect
golang.org/x/crypto v0.48.0 // indirect
golang.org/x/net v0.51.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.35.0 // indirect
google.golang.org/protobuf v1.36.10 // indirect
)
+106
View File
@@ -0,0 +1,106 @@
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
github.com/gin-contrib/cors v1.7.7 h1:Oh9joP463x7Mw72vhvJ61YQm8ODh9b04YR7vsOErD0Q=
github.com/gin-contrib/cors v1.7.7/go.mod h1:K5tW0RkzJtWSiOdikXloy8VEZlgdVNpHNw8FpjUPNrE=
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.9.1 h1:uwrxJXBnx76nyISkhr33kQLlUqjv7et7b9FjCen/tdc=
github.com/jackc/pgx/v5 v5.9.1/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
golang.org/x/arch v0.23.0 h1:lKF64A2jF6Zd8L0knGltUnegD62JMFBiCPBmQpToHhg=
golang.org/x/arch v0.23.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
@@ -0,0 +1 @@
DROP TABLE IF EXISTS deliveries;
@@ -0,0 +1,14 @@
CREATE TABLE deliveries (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
date date NOT NULL, -- хранить как date, отдавать как DD-MM-YYYY
pickup_location varchar(20) NOT NULL, -- warehouse|symbat|nursaya|galaktika
product_name text NOT NULL,
address text NOT NULL,
phone varchar(30) NOT NULL,
additional_phone varchar(30),
has_elevator boolean NOT NULL DEFAULT false,
comment text,
status varchar(20) NOT NULL DEFAULT 'new', -- new|delivered
created_at timestamptz DEFAULT now(),
updated_at timestamptz DEFAULT now()
);
@@ -0,0 +1 @@
DROP TABLE IF EXISTS users;
@@ -0,0 +1,6 @@
CREATE TABLE users (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
username VARCHAR(50) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
+22
View File
@@ -0,0 +1,22 @@
-- name: GetDeliveriesByDate :many
SELECT * FROM deliveries WHERE date = $1;
-- name: CreateDelivery :one
INSERT INTO deliveries (date, pickup_location, product_name, address, phone, additional_phone, has_elevator, comment)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING *;
-- name: GetDeliveryByID :one
SELECT * FROM deliveries WHERE id = $1;
-- name: DeleteDelivery :exec
DELETE FROM deliveries WHERE id = $1;
-- name: UpdateDelivery :exec
UPDATE deliveries SET date = $1, pickup_location = $2, product_name = $3, address = $4, phone = $5, additional_phone = $6, has_elevator = $7, comment = $8, updated_at = NOW() WHERE id = $9;
-- name: GetDeliveryCount :many
SELECT COUNT(*) as count, date FROM deliveries WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY date;
-- name: UpdateDeliveryStatus :exec
UPDATE deliveries SET status = $1, updated_at = NOW() WHERE id = $2;
+32
View File
@@ -0,0 +1,32 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package db
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type DBTX interface {
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
QueryRow(context.Context, string, ...interface{}) pgx.Row
}
func New(db DBTX) *Queries {
return &Queries{db: db}
}
type Queries struct {
db DBTX
}
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
return &Queries{
db: tx,
}
}
+31
View File
@@ -0,0 +1,31 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package db
import (
"github.com/jackc/pgx/v5/pgtype"
)
type Delivery struct {
ID pgtype.UUID `db:"id" json:"id"`
Date pgtype.Date `db:"date" json:"date"`
PickupLocation string `db:"pickup_location" json:"pickup_location"`
ProductName string `db:"product_name" json:"product_name"`
Address string `db:"address" json:"address"`
Phone string `db:"phone" json:"phone"`
AdditionalPhone pgtype.Text `db:"additional_phone" json:"additional_phone"`
HasElevator bool `db:"has_elevator" json:"has_elevator"`
Comment pgtype.Text `db:"comment" json:"comment"`
Status string `db:"status" json:"status"`
CreatedAt pgtype.Timestamptz `db:"created_at" json:"created_at"`
UpdatedAt pgtype.Timestamptz `db:"updated_at" json:"updated_at"`
}
type User struct {
ID pgtype.UUID `db:"id" json:"id"`
Username string `db:"username" json:"username"`
PasswordHash string `db:"password_hash" json:"password_hash"`
CreatedAt pgtype.Timestamp `db:"created_at" json:"created_at"`
}
+23
View File
@@ -0,0 +1,23 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
package db
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
type Querier interface {
CreateDelivery(ctx context.Context, arg CreateDeliveryParams) (Delivery, error)
DeleteDelivery(ctx context.Context, id pgtype.UUID) error
GetDeliveriesByDate(ctx context.Context, date pgtype.Date) ([]Delivery, error)
GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error)
GetDeliveryCount(ctx context.Context) ([]GetDeliveryCountRow, error)
UpdateDelivery(ctx context.Context, arg UpdateDeliveryParams) error
UpdateDeliveryStatus(ctx context.Context, arg UpdateDeliveryStatusParams) error
}
var _ Querier = (*Queries)(nil)
+202
View File
@@ -0,0 +1,202 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.30.0
// source: query.sql
package db
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const createDelivery = `-- name: CreateDelivery :one
INSERT INTO deliveries (date, pickup_location, product_name, address, phone, additional_phone, has_elevator, comment)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id, date, pickup_location, product_name, address, phone, additional_phone, has_elevator, comment, status, created_at, updated_at
`
type CreateDeliveryParams struct {
Date pgtype.Date `db:"date" json:"date"`
PickupLocation string `db:"pickup_location" json:"pickup_location"`
ProductName string `db:"product_name" json:"product_name"`
Address string `db:"address" json:"address"`
Phone string `db:"phone" json:"phone"`
AdditionalPhone pgtype.Text `db:"additional_phone" json:"additional_phone"`
HasElevator bool `db:"has_elevator" json:"has_elevator"`
Comment pgtype.Text `db:"comment" json:"comment"`
}
func (q *Queries) CreateDelivery(ctx context.Context, arg CreateDeliveryParams) (Delivery, error) {
row := q.db.QueryRow(ctx, createDelivery,
arg.Date,
arg.PickupLocation,
arg.ProductName,
arg.Address,
arg.Phone,
arg.AdditionalPhone,
arg.HasElevator,
arg.Comment,
)
var i Delivery
err := row.Scan(
&i.ID,
&i.Date,
&i.PickupLocation,
&i.ProductName,
&i.Address,
&i.Phone,
&i.AdditionalPhone,
&i.HasElevator,
&i.Comment,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const deleteDelivery = `-- name: DeleteDelivery :exec
DELETE FROM deliveries WHERE id = $1
`
func (q *Queries) DeleteDelivery(ctx context.Context, id pgtype.UUID) error {
_, err := q.db.Exec(ctx, deleteDelivery, id)
return err
}
const getDeliveriesByDate = `-- name: GetDeliveriesByDate :many
SELECT id, date, pickup_location, product_name, address, phone, additional_phone, has_elevator, comment, status, created_at, updated_at FROM deliveries WHERE date = $1
`
func (q *Queries) GetDeliveriesByDate(ctx context.Context, date pgtype.Date) ([]Delivery, error) {
rows, err := q.db.Query(ctx, getDeliveriesByDate, date)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Delivery{}
for rows.Next() {
var i Delivery
if err := rows.Scan(
&i.ID,
&i.Date,
&i.PickupLocation,
&i.ProductName,
&i.Address,
&i.Phone,
&i.AdditionalPhone,
&i.HasElevator,
&i.Comment,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getDeliveryByID = `-- name: GetDeliveryByID :one
SELECT id, date, pickup_location, product_name, address, phone, additional_phone, has_elevator, comment, status, created_at, updated_at FROM deliveries WHERE id = $1
`
func (q *Queries) GetDeliveryByID(ctx context.Context, id pgtype.UUID) (Delivery, error) {
row := q.db.QueryRow(ctx, getDeliveryByID, id)
var i Delivery
err := row.Scan(
&i.ID,
&i.Date,
&i.PickupLocation,
&i.ProductName,
&i.Address,
&i.Phone,
&i.AdditionalPhone,
&i.HasElevator,
&i.Comment,
&i.Status,
&i.CreatedAt,
&i.UpdatedAt,
)
return i, err
}
const getDeliveryCount = `-- name: GetDeliveryCount :many
SELECT COUNT(*) as count, date FROM deliveries WHERE date >= DATE_TRUNC('month', CURRENT_DATE) GROUP BY date
`
type GetDeliveryCountRow struct {
Count int64 `db:"count" json:"count"`
Date pgtype.Date `db:"date" json:"date"`
}
func (q *Queries) GetDeliveryCount(ctx context.Context) ([]GetDeliveryCountRow, error) {
rows, err := q.db.Query(ctx, getDeliveryCount)
if err != nil {
return nil, err
}
defer rows.Close()
items := []GetDeliveryCountRow{}
for rows.Next() {
var i GetDeliveryCountRow
if err := rows.Scan(&i.Count, &i.Date); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateDelivery = `-- name: UpdateDelivery :exec
UPDATE deliveries SET date = $1, pickup_location = $2, product_name = $3, address = $4, phone = $5, additional_phone = $6, has_elevator = $7, comment = $8, updated_at = NOW() WHERE id = $9
`
type UpdateDeliveryParams struct {
Date pgtype.Date `db:"date" json:"date"`
PickupLocation string `db:"pickup_location" json:"pickup_location"`
ProductName string `db:"product_name" json:"product_name"`
Address string `db:"address" json:"address"`
Phone string `db:"phone" json:"phone"`
AdditionalPhone pgtype.Text `db:"additional_phone" json:"additional_phone"`
HasElevator bool `db:"has_elevator" json:"has_elevator"`
Comment pgtype.Text `db:"comment" json:"comment"`
ID pgtype.UUID `db:"id" json:"id"`
}
func (q *Queries) UpdateDelivery(ctx context.Context, arg UpdateDeliveryParams) error {
_, err := q.db.Exec(ctx, updateDelivery,
arg.Date,
arg.PickupLocation,
arg.ProductName,
arg.Address,
arg.Phone,
arg.AdditionalPhone,
arg.HasElevator,
arg.Comment,
arg.ID,
)
return err
}
const updateDeliveryStatus = `-- name: UpdateDeliveryStatus :exec
UPDATE deliveries SET status = $1, updated_at = NOW() WHERE id = $2
`
type UpdateDeliveryStatusParams struct {
Status string `db:"status" json:"status"`
ID pgtype.UUID `db:"id" json:"id"`
}
func (q *Queries) UpdateDeliveryStatus(ctx context.Context, arg UpdateDeliveryStatusParams) error {
_, err := q.db.Exec(ctx, updateDeliveryStatus, arg.Status, arg.ID)
return err
}
+233
View File
@@ -0,0 +1,233 @@
package delivery
import (
"net/http"
"time"
sqlc "github.com/chedius/delivery-tracker/internal/db/sqlc"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
)
type Handler struct {
queries *sqlc.Queries
}
// DeliveryRequest represents the request body for creating or updating a delivery
type DeliveryRequest struct {
Date string `json:"date" binding:"required"` // DD-MM-YYYY
PickupLocation string `json:"pickup_location" binding:"required,oneof=warehouse symbat nursaya galaktika"`
ProductName string `json:"product_name" binding:"required"`
Address string `json:"address" binding:"required"`
Phone string `json:"phone" binding:"required"`
AdditionalPhone string `json:"additional_phone"`
HasElevator bool `json:"has_elevator"`
Comment string `json:"comment"`
}
func NewHandler(queries *sqlc.Queries) *Handler {
return &Handler{queries: queries}
}
// GET /api/deliveries/:id
func (h *Handler) GetDeliveryByID(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID is required"})
return
}
parsedID, err := uuid.Parse(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid UUID format", "details": err.Error()})
return
}
delivery, err := h.queries.GetDeliveryByID(c.Request.Context(), pgtype.UUID{Bytes: parsedID, Valid: true})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get delivery", "details": err.Error(), "id": id, "bytes": [16]byte([]byte(id))})
return
}
c.JSON(http.StatusOK, gin.H{"delivery": delivery})
}
// GET /api/deliveries?date=DD-MM-YYYY
func (h *Handler) GetDeliveries(c *gin.Context) {
t, err := parseDate(c.Query("date"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format", "details": err.Error()})
return
}
date := pgtype.Date{Time: t, Valid: true}
deliveries, err := h.queries.GetDeliveriesByDate(c.Request.Context(), date)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get deliveries", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"deliveries": deliveries})
}
// GET /api/deliveries/count
func (h *Handler) GetDeliveryCount(c *gin.Context) {
counts, err := h.queries.GetDeliveryCount(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get delivery count", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"counts": counts})
}
// POST /api/deliveries
func (h *Handler) CreateDelivery(c *gin.Context) {
var req DeliveryRequest = DeliveryRequest{}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body", "details": err.Error()})
return
}
// Parse date from DD-MM-YYYY
t, err := parseDate(req.Date)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format", "details": err.Error()})
return
}
params := sqlc.CreateDeliveryParams{
Date: pgtype.Date{Time: t, Valid: true},
PickupLocation: req.PickupLocation,
ProductName: req.ProductName,
Address: req.Address,
Phone: req.Phone,
AdditionalPhone: pgtype.Text{String: req.AdditionalPhone, Valid: req.AdditionalPhone != ""},
HasElevator: req.HasElevator,
Comment: pgtype.Text{String: req.Comment, Valid: true},
}
res, err := h.queries.CreateDelivery(c.Request.Context(), params)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create delivery", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Delivery created", "id": res.ID.String()})
}
// PATCH /api/deliveries/:id
func (h *Handler) UpdateDelivery(c *gin.Context) {
var req DeliveryRequest = DeliveryRequest{}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body", "details": err.Error()})
return
}
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID is required"})
return
}
parsedID, err := uuid.Parse(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid UUID format", "details": err.Error()})
return
}
t, err := parseDate(req.Date)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format", "details": err.Error()})
return
}
if err := h.queries.UpdateDelivery(c.Request.Context(), sqlc.UpdateDeliveryParams{
ID: pgtype.UUID{Bytes: parsedID, Valid: true},
Date: pgtype.Date{Time: t, Valid: true},
PickupLocation: req.PickupLocation,
ProductName: req.ProductName,
Address: req.Address,
Phone: req.Phone,
AdditionalPhone: pgtype.Text{String: req.AdditionalPhone, Valid: req.AdditionalPhone != ""},
HasElevator: req.HasElevator,
Comment: pgtype.Text{String: req.Comment, Valid: true},
}); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update delivery", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Delivery updated"})
}
// PATCH /api/deliveries/:id/status
func (h *Handler) UpdateDeliveryStatus(c *gin.Context) {
var req struct {
Status string `json:"status"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body", "details": err.Error()})
return
}
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID is required"})
return
}
parsedID, err := uuid.Parse(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid UUID format", "details": err.Error()})
return
}
status := req.Status
if status == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Status is required"})
return
}
if err := h.queries.UpdateDeliveryStatus(c.Request.Context(), sqlc.UpdateDeliveryStatusParams{
ID: pgtype.UUID{Bytes: parsedID, Valid: true},
Status: status,
}); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update delivery status", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Delivery status updated"})
}
// DELETE /api/deliveries/:id
func (h *Handler) DeleteDelivery(c *gin.Context) {
id := c.Param("id")
if id == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "ID is required"})
return
}
parsedID, err := uuid.Parse(id)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid UUID format", "details": err.Error()})
return
}
if err := h.queries.DeleteDelivery(c.Request.Context(), pgtype.UUID{Bytes: parsedID, Valid: true}); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete delivery", "details": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Delivery deleted"})
}
func parseDate(dateStr string) (time.Time, error) {
t, err := time.Parse("02-01-2006", dateStr)
if err != nil {
return time.Time{}, err
}
return t, nil
}
+17
View File
@@ -0,0 +1,17 @@
version: "2"
sql:
- engine: "postgresql" # СУБД: postgresql, mysql или sqlite
queries: "internal/db/queries/" # Путь к .sql файлам с вашими SELECT/INSERT/UPDATE
schema: "internal/db/migrations/" # Путь к файлам схемы (миграциям)
gen:
go:
package: "db" # Имя Go-пакета для сгенерированного кода
out: "internal/db/sqlc" # Директория, куда sqlc положит файлы
sql_package: "pgx/v5" # Драйвер: pgx/v5 (рекомендуется) или database/sql
# Дополнительные полезные опции:
emit_json_tags: true # Добавить json-теги в структуры моделей
emit_db_tags: true # Добавить db-теги
emit_interface: true # Создать интерфейс Querier (удобно для моков в тестах)
emit_exact_table_names: false # Если true, имена структур будут как в БД (users -> Users)
emit_empty_slices: true # Возвращать [] вместо nil для пустых результатов
+61
View File
@@ -0,0 +1,61 @@
services:
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
interval: 5s
timeout: 5s
retries: 5
restart: unless-stopped
networks:
- delivery-network
backend:
image: ${GITEA_REGISTRY}/delivery-tracker/backend:latest
environment:
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
JWT_SECRET: ${JWT_SECRET}
# Нет expose - backend доступен только внутри сети delivery-network
depends_on:
postgres:
condition: service_healthy
restart: unless-stopped
networks:
- delivery-network
frontend:
image: ${GITEA_REGISTRY}/delivery-tracker/frontend:latest
expose:
- "80"
depends_on:
- backend
restart: unless-stopped
networks:
- delivery-network
watchtower:
image: containrrr/watchtower
environment:
- WATCHTOWER_CLEANUP=true
- WATCHTOWER_POLL_INTERVAL=60
- WATCHTOWER_INCLUDE_STOPPED=true
- WATCHTOWER_REVIVE_STOPPED=false
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /root/.docker/config.json:/config.json
command: backend frontend --interval 60
networks:
- delivery-network
volumes:
postgres_data:
networks:
delivery-network:
driver: bridge
+63
View File
@@ -0,0 +1,63 @@
services:
# PostgreSQL database
postgres:
image: postgres:16-alpine
environment:
POSTGRES_USER: egor
POSTGRES_PASSWORD: barsik
POSTGRES_DB: delivery_tracker
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U egor -d delivery_tracker"]
interval: 5s
timeout: 5s
retries: 5
# Backend API
backend:
build:
context: ./backend
dockerfile: Dockerfile
target: production
environment:
DATABASE_URL: postgres://egor:barsik@postgres:5432/delivery_tracker?sslmode=disable
ports:
- "8081:8080"
depends_on:
postgres:
condition: service_healthy
restart: unless-stopped
# Development service with hot reload
frontend-dev:
image: node:20-alpine
working_dir: /app
volumes:
- ./frontend:/app
- node_modules:/app/node_modules
ports:
- "5173:5173"
environment:
- NODE_ENV=development
command: sh -c "yarn install && yarn dev --host"
stdin_open: true
tty: true
# Production frontend service
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
target: production
ports:
- "8080:80"
depends_on:
- backend
restart: unless-stopped
volumes:
node_modules:
postgres_data:
+16
View File
@@ -0,0 +1,16 @@
node_modules
npm-debug.log
yarn-error.log
dist
.git
.gitignore
README.md
.env
.env.local
.DS_Store
.vscode
.idea
*.md
Dockerfile
docker-compose.yml
.dockerignore
+4
View File
@@ -0,0 +1,4 @@
# API Configuration
# Leave empty to use proxy (recommended for local dev and production)
# Or set full URL like http://localhost:8081 for direct API access
VITE_API_URL=
+29
View File
@@ -0,0 +1,29 @@
# syntax=docker/dockerfile:1
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
# Copy package files
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
# Copy source code
COPY . .
# Build application
RUN yarn build
# Stage 2: Production
FROM nginx:alpine AS production
# Copy custom nginx config
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Copy built files from builder stage
COPY --from=builder /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
+23
View File
@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])
+17
View File
@@ -0,0 +1,17 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="manifest" href="/manifest.json" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="theme-color" content="#1B263B" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<title>Delivery Tracker</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+43
View File
@@ -0,0 +1,43 @@
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Proxy API requests to backend
location /api/ {
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
# Handle client-side routing
location / {
try_files $uri $uri/ /index.html;
}
# Health check endpoint
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
+6902
View File
File diff suppressed because it is too large Load Diff
+38
View File
@@ -0,0 +1,38 @@
{
"name": "delivery-tracker",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tailwindcss/vite": "^4.2.2",
"date-fns": "^4.1.0",
"lucide-react": "^1.7.0",
"react": "^19.2.4",
"react-dom": "^19.2.4",
"tailwindcss": "^4.2.2",
"zustand": "^5.0.12"
},
"devDependencies": {
"@eslint/js": "^9.39.4",
"@types/node": "^24.12.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@types/workbox-window": "^4.3.4",
"@vitejs/plugin-react": "^6.0.1",
"eslint": "^9.39.4",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.4.0",
"typescript": "~5.9.3",
"typescript-eslint": "^8.57.0",
"vite": "^8.0.1",
"vite-plugin-pwa": "^1.2.0",
"workbox-window": "^7.4.0"
}
}
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

After

Width:  |  Height:  |  Size: 4.9 KiB

+21
View File
@@ -0,0 +1,21 @@
{
"name": "Delivery Tracker",
"short_name": "Deliveries",
"description": "Система контроля доставок мебели",
"start_url": "/",
"display": "standalone",
"background_color": "#fbf8fb",
"theme_color": "#1B263B",
"icons": [
{
"src": "/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="#1B263B" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="3" width="15" height="13"/><polygon points="16 8 20 8 23 11 23 16 16 16"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>

After

Width:  |  Height:  |  Size: 322 B

+117
View File
@@ -0,0 +1,117 @@
import { useState, useEffect, lazy, Suspense } from 'react';
import { Truck, Loader2 } from 'lucide-react';
import { DeliveryForm } from './components/delivery/DeliveryForm';
import { ToastContainer } from './components/ui/Toast';
import { useDeliveryStore } from './stores/deliveryStore';
// Lazy load pages for code splitting
const Dashboard = lazy(() => import('./pages/Dashboard'));
const DeliveryListPage = lazy(() => import('./pages/DeliveryListPage'));
// Fallback loading component
const PageLoader = () => (
<div className="flex items-center justify-center py-20">
<Loader2 className="w-8 h-8 animate-spin text-[#1B263B]" />
</div>
);
function App() {
const [view, setView] = useState<'dashboard' | 'delivery-list'>('dashboard');
const [selectedDate, setSelectedDate] = useState<string>('');
const [isFormOpen, setIsFormOpen] = useState(false);
const [formDate, setFormDate] = useState<string>('');
const [isSubmitting, setIsSubmitting] = useState(false);
const addDelivery = useDeliveryStore(state => state.addDelivery);
const fetchDeliveryCounts = useDeliveryStore(state => state.fetchDeliveryCounts);
// Refresh counts when form closes
useEffect(() => {
if (!isFormOpen) {
fetchDeliveryCounts();
}
}, [isFormOpen, fetchDeliveryCounts]);
const handleDateSelect = (date: string) => {
setSelectedDate(date);
setView('delivery-list');
};
const handleBackToDashboard = () => {
setView('dashboard');
setSelectedDate('');
};
const handleAddDelivery = () => {
const today = new Date().toLocaleDateString('ru-RU').split('.').join('-');
setFormDate(today);
setIsFormOpen(true);
};
const handleFormSubmit = async (data: Parameters<typeof addDelivery>[0]) => {
setIsSubmitting(true);
try {
await addDelivery(data);
setIsFormOpen(false);
// If created for different date, navigate to that date
const today = new Date().toLocaleDateString('ru-RU').split('.').join('-');
if (data.date !== today) {
setSelectedDate(data.date);
setView('delivery-list');
}
} catch {
// Error is handled by store
} finally {
setIsSubmitting(false);
}
};
return (
<div className="min-h-screen bg-[#fbf8fb]">
<header className="sticky top-0 z-40 bg-[#1B263B] text-white shadow-md">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-14">
<div className="flex items-center gap-3">
<div className="p-2 bg-white/10 rounded-lg">
<Truck size={24} className="text-white" />
</div>
<h1 className="text-lg font-semibold hidden sm:block">Delivery Tracker</h1>
</div>
<div className="text-sm text-white/70">
{view === 'dashboard' ? 'Панель управления' : `Доставки на ${selectedDate}`}
</div>
</div>
</div>
</header>
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
<Suspense fallback={<PageLoader />}>
{view === 'dashboard' ? (
<Dashboard
onDateSelect={handleDateSelect}
onAddDelivery={handleAddDelivery}
/>
) : (
<DeliveryListPage
selectedDate={selectedDate}
onBack={handleBackToDashboard}
/>
)}
</Suspense>
</main>
<DeliveryForm
isOpen={isFormOpen}
onClose={() => setIsFormOpen(false)}
onSubmit={handleFormSubmit}
defaultDate={formDate}
isSubmitting={isSubmitting}
/>
<ToastContainer />
</div>
);
}
export default App;
+108
View File
@@ -0,0 +1,108 @@
const API_BASE_URL = import.meta.env.VITE_API_URL || '';
// Request deduplication cache
const pendingRequests = new Map<string, Promise<unknown>>();
// Abort controllers for cancelling requests
const abortControllers = new Map<string, AbortController>();
export class ApiError extends Error {
status: number;
details?: unknown;
constructor(message: string, status: number, details?: unknown) {
super(message);
this.name = 'ApiError';
this.status = status;
this.details = details;
}
}
function getRequestKey(endpoint: string, method: string, body?: unknown): string {
return `${method}:${endpoint}:${body ? JSON.stringify(body) : ''}`;
}
async function fetchApi<T>(
endpoint: string,
options?: RequestInit & { deduplicate?: boolean }
): Promise<T> {
const url = `${API_BASE_URL}${endpoint}`;
const method = options?.method || 'GET';
const requestKey = getRequestKey(endpoint, method, options?.body);
// Cancel previous request with same key (for non-GET requests or explicit override)
const shouldCancelPrevious = method !== 'GET' || options?.deduplicate === false;
if (shouldCancelPrevious && abortControllers.has(requestKey)) {
abortControllers.get(requestKey)?.abort();
}
// Deduplicate GET requests
if (method === 'GET' && options?.deduplicate !== false) {
if (pendingRequests.has(requestKey)) {
return pendingRequests.get(requestKey) as Promise<T>;
}
}
// Create new abort controller
const controller = new AbortController();
abortControllers.set(requestKey, controller);
const requestPromise = (async (): Promise<T> => {
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
headers: {
'Content-Type': 'application/json',
...options?.headers,
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new ApiError(
errorData?.error || `HTTP ${response.status}`,
response.status,
errorData?.details
);
}
return response.json();
} finally {
pendingRequests.delete(requestKey);
abortControllers.delete(requestKey);
}
})();
if (method === 'GET' && options?.deduplicate !== false) {
pendingRequests.set(requestKey, requestPromise);
}
return requestPromise;
}
export const api = {
get: <T>(endpoint: string, options?: { deduplicate?: boolean }) =>
fetchApi<T>(endpoint, { method: 'GET', ...options }),
post: <T>(endpoint: string, data: unknown) =>
fetchApi<T>(endpoint, {
method: 'POST',
body: JSON.stringify(data),
}),
patch: <T>(endpoint: string, data?: unknown) =>
fetchApi<T>(endpoint, {
method: 'PATCH',
body: data ? JSON.stringify(data) : undefined,
}),
delete: <T>(endpoint: string) =>
fetchApi<T>(endpoint, { method: 'DELETE' }),
};
// Utility to cancel all pending requests (useful on unmount)
export function cancelAllRequests(): void {
abortControllers.forEach(controller => controller.abort());
abortControllers.clear();
pendingRequests.clear();
}
+137
View File
@@ -0,0 +1,137 @@
import { api } from './client';
import { backendDateToFrontend } from '../utils/date';
import type { Delivery, PickupLocation, DeliveryStatus } from '../types';
// Types matching backend responses
interface BackendDelivery {
id: string;
date: string; // YYYY-MM-DD from pgtype.Date
pickup_location: PickupLocation;
product_name: string;
address: string;
phone: string;
additional_phone: string | null;
has_elevator: boolean;
comment: string;
status: DeliveryStatus;
created_at: string; // ISO timestamp
updated_at: string; // ISO timestamp
}
interface DeliveryCount {
date: string; // YYYY-MM-DD
count: number;
}
// API Response types
interface GetDeliveriesResponse {
deliveries: BackendDelivery[];
}
interface GetDeliveryResponse {
delivery: BackendDelivery;
}
interface GetDeliveryCountResponse {
counts: DeliveryCount[];
}
interface CreateDeliveryResponse {
message: string;
id: string;
}
interface UpdateDeliveryResponse {
message: string;
}
// Map backend delivery to frontend delivery
function mapBackendToFrontend(backend: BackendDelivery): Delivery {
return {
id: backend.id,
date: backendDateToFrontend(backend.date),
pickupLocation: backend.pickup_location,
productName: backend.product_name,
address: backend.address,
phone: backend.phone,
additionalPhone: backend.additional_phone || undefined,
hasElevator: backend.has_elevator,
comment: backend.comment,
status: backend.status,
createdAt: new Date(backend.created_at).getTime(),
updatedAt: new Date(backend.updated_at).getTime(),
};
}
// Delivery API methods
export const deliveriesApi = {
// Get deliveries by date (DD-MM-YYYY)
getByDate: async (date: string): Promise<Delivery[]> => {
const response = await api.get<GetDeliveriesResponse>(
`/api/deliveries?date=${encodeURIComponent(date)}`
);
return response.deliveries.map(mapBackendToFrontend);
},
// Get single delivery by ID
getById: async (id: string): Promise<Delivery> => {
const response = await api.get<GetDeliveryResponse>(`/api/deliveries/${id}`);
return mapBackendToFrontend(response.delivery);
},
// Get delivery counts by date
getCounts: async (): Promise<Record<string, number>> => {
const response = await api.get<GetDeliveryCountResponse>('/api/deliveries/count');
const counts: Record<string, number> = {};
response.counts.forEach(({ date, count }) => {
counts[backendDateToFrontend(date)] = count;
});
return counts;
},
// Create delivery
create: async (
data: Omit<Delivery, 'id' | 'createdAt' | 'updatedAt'>
): Promise<string> => {
const payload = {
date: data.date,
pickup_location: data.pickupLocation,
product_name: data.productName,
address: data.address,
phone: data.phone,
additional_phone: data.additionalPhone || '',
has_elevator: data.hasElevator,
comment: data.comment,
};
const response = await api.post<CreateDeliveryResponse>('/api/deliveries', payload);
return response.id;
},
// Update delivery
update: async (
id: string,
data: Omit<Delivery, 'id' | 'createdAt' | 'updatedAt'>
): Promise<void> => {
const payload = {
date: data.date,
pickup_location: data.pickupLocation,
product_name: data.productName,
address: data.address,
phone: data.phone,
additional_phone: data.additionalPhone || '',
has_elevator: data.hasElevator,
comment: data.comment,
};
await api.patch<UpdateDeliveryResponse>(`/api/deliveries/${id}`, payload);
},
// Update delivery status
updateStatus: async (id: string, status: DeliveryStatus): Promise<void> => {
await api.patch(`/api/deliveries/${id}/status`, { status });
},
// Delete delivery
delete: async (id: string): Promise<void> => {
await api.delete(`/api/deliveries/${id}`);
},
};
+3
View File
@@ -0,0 +1,3 @@
export { api, ApiError, cancelAllRequests } from './client';
export { deliveriesApi } from './deliveries';
export { frontendDateToBackend } from '../utils/date';
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

@@ -0,0 +1,138 @@
import { memo } from 'react';
import { MapPin, Phone, Package, Store, Calendar, MessageSquare, CheckCircle2, Circle, CheckSquare } from 'lucide-react';
import type { Delivery } from '../../types';
import { pickupLocationLabels } from '../../types';
import { StatusBadge } from './StatusBadge';
import { Card } from '../ui/Card';
interface DeliveryCardProps {
delivery: Delivery;
onStatusChange: (id: string) => void;
onEdit: (delivery: Delivery) => void;
onDelete: (id: string) => void;
}
export const DeliveryCard = memo(({ delivery, onStatusChange, onEdit, onDelete }: DeliveryCardProps) => {
const handleAddressClick = () => {
const encodedAddress = encodeURIComponent(delivery.address);
window.open(`https://maps.google.com/?q=${encodedAddress}`, '_blank');
};
const handlePhoneClick = () => {
window.location.href = `tel:${delivery.phone}`;
};
return (
<Card className="relative">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-2">
<StatusBadge
status={delivery.status}
onClick={() => onStatusChange(delivery.id)}
size="md"
/>
</div>
<div className="flex gap-1">
<button
onClick={() => onEdit(delivery)}
className="p-1.5 rounded-md hover:bg-[#f5f3f5] text-[#75777d] transition-colors"
title="Редактировать"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/></svg>
</button>
<button
onClick={() => onDelete(delivery.id)}
className="p-1.5 rounded-md hover:bg-red-50 text-red-500 transition-colors"
title="Удалить"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</div>
<div className="space-y-2.5">
<div className="flex items-center gap-2 text-sm">
<Calendar size={16} className="text-[#75777d]" />
<span className="text-[#1b1b1d] font-medium">{delivery.date}</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Store size={16} className="text-[#75777d]" />
<span className="text-[#1b1b1d]">{pickupLocationLabels[delivery.pickupLocation]}</span>
</div>
<div className="flex items-center gap-2 text-sm">
<Package size={16} className="text-[#75777d]" />
<span className="text-[#1b1b1d]">{delivery.productName}</span>
</div>
<button
onClick={handleAddressClick}
className="flex items-start gap-2 text-sm w-full text-left hover:bg-[#f5f3f5] -mx-1 px-1 py-0.5 rounded transition-colors"
>
<MapPin size={16} className="text-[#F28C28] mt-0.5 shrink-0" />
<span className="text-[#1B263B] underline decoration-[#F28C28]/30 underline-offset-2">
{delivery.address}
</span>
</button>
<button
onClick={handlePhoneClick}
className="flex items-center gap-2 text-sm w-full text-left hover:bg-[#f5f3f5] -mx-1 px-1 py-0.5 rounded transition-colors"
>
<Phone size={16} className="text-[#16a34a] shrink-0" />
<span className="text-[#16a34a] font-medium">
{delivery.phone}
</span>
</button>
{delivery.additionalPhone && (
<button
onClick={() => window.location.href = `tel:${delivery.additionalPhone}`}
className="flex items-center gap-2 text-sm w-full text-left hover:bg-[#f5f3f5] -mx-1 px-1 py-0.5 rounded transition-colors"
>
<Phone size={16} className="text-[#75777d] shrink-0" />
<span className="text-[#75777d]">
{delivery.additionalPhone}
</span>
</button>
)}
<div className="flex items-center gap-2 text-sm">
<CheckSquare size={16} className={delivery.hasElevator ? 'text-[#16a34a]' : 'text-[#75777d]'} />
<span className="text-[#1b1b1d]">
{delivery.hasElevator ? 'Есть лифт' : 'Нет лифта'}
</span>
</div>
{delivery.comment && (
<div className="flex items-start gap-2 text-sm">
<MessageSquare size={16} className="text-[#75777d] mt-0.5 shrink-0" />
<span className="text-[#45474d]">{delivery.comment}</span>
</div>
)}
</div>
<div className="mt-4 pt-3 border-t border-[#e4e2e4]">
<button
onClick={() => onStatusChange(delivery.id)}
className="w-full flex items-center justify-center gap-2 py-2 rounded-md bg-[#f5f3f5] hover:bg-[#e4e2e4] transition-colors text-sm font-medium text-[#1b1b1d]"
>
{delivery.status === 'new' ? (
<>
<CheckCircle2 size={16} className="text-[#16a34a]" />
Отметить доставленным
</>
) : (
<>
<Circle size={16} className="text-[#F28C28]" />
Вернуть в "Новые"
</>
)}
</button>
</div>
</Card>
);
});
DeliveryCard.displayName = 'DeliveryCard';
@@ -0,0 +1,200 @@
import { useState, useEffect, useCallback } from 'react';
import { Button, Input, Select, Modal } from '../ui';
import { pickupOptions } from '../../constants/pickup';
import { formatDateForInput, parseDateFromInput, getTodayFrontend } from '../../utils/date';
import type { Delivery, PickupLocation, DeliveryStatus } from '../../types';
interface DeliveryFormProps {
isOpen: boolean;
onClose: () => void;
onSubmit: (delivery: Omit<Delivery, 'id' | 'createdAt' | 'updatedAt'>) => void | Promise<void>;
initialData?: Delivery | null;
defaultDate?: string;
isSubmitting?: boolean;
}
// Phone validation regex for Kazakhstan numbers
const PHONE_REGEX = /^\+7\s?\(?\d{3}\)?\s?\d{3}[\s-]?\d{2}[\s-]?\d{2}$/;
export const DeliveryForm = ({ isOpen, onClose, onSubmit, initialData, defaultDate, isSubmitting }: DeliveryFormProps) => {
const [formData, setFormData] = useState({
date: defaultDate || getTodayFrontend(),
pickupLocation: 'warehouse' as PickupLocation,
productName: '',
address: '',
phone: '',
additionalPhone: '',
hasElevator: false,
comment: '',
status: 'new' as DeliveryStatus,
});
useEffect(() => {
if (initialData) {
setFormData({
date: initialData.date,
pickupLocation: initialData.pickupLocation,
productName: initialData.productName,
address: initialData.address,
phone: initialData.phone,
additionalPhone: initialData.additionalPhone || '',
hasElevator: initialData.hasElevator,
comment: initialData.comment,
status: initialData.status,
});
} else if (defaultDate) {
setFormData(prev => ({ ...prev, date: defaultDate }));
}
}, [initialData, defaultDate, isOpen]);
const validatePhone = useCallback((phone: string): boolean => {
if (!phone) return false;
return PHONE_REGEX.test(phone);
}, []);
const isPhoneValid = !formData.phone || validatePhone(formData.phone);
const isAdditionalPhoneValid = !formData.additionalPhone || validatePhone(formData.additionalPhone);
const isFormValid = formData.productName && formData.address && formData.phone && isPhoneValid;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!isFormValid) return;
try {
await onSubmit(formData);
if (!initialData) {
setFormData({
date: defaultDate || getTodayFrontend(),
pickupLocation: 'warehouse',
productName: '',
address: '',
phone: '',
additionalPhone: '',
hasElevator: false,
comment: '',
status: 'new',
});
}
onClose();
} catch {
// Error is handled by parent, keep form open
}
};
return (
<Modal
isOpen={isOpen}
onClose={onClose}
title={initialData ? 'Редактировать доставку' : 'Новая доставка'}
footer={
<>
<Button variant="ghost" onClick={onClose} disabled={isSubmitting}>
Отмена
</Button>
<Button type="submit" form="delivery-form" disabled={isSubmitting || !isFormValid}>
{isSubmitting ? 'Сохранение...' : initialData ? 'Сохранить' : 'Создать'}
</Button>
</>
}
>
<form id="delivery-form" onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-[#1b1b1d] mb-1">
Дата доставки
</label>
<input
type="date"
value={formatDateForInput(formData.date)}
onChange={(e) => setFormData({ ...formData, date: parseDateFromInput(e.target.value) })}
className="w-full px-3 py-2 bg-[#f5f3f5] border border-[#c5c6cd] rounded-md text-[#1b1b1d] focus:outline-none focus:ring-2 focus:ring-[#1B263B] focus:border-transparent transition-colors"
required
/>
</div>
<Select
label="Место загрузки"
value={formData.pickupLocation}
onChange={(e) => setFormData({ ...formData, pickupLocation: e.target.value as PickupLocation })}
options={pickupOptions}
/>
<Input
label="Название товара"
value={formData.productName}
onChange={(e) => setFormData({ ...formData, productName: e.target.value })}
placeholder="Введите название товара"
required
/>
<Input
label="Адрес разгрузки"
value={formData.address}
onChange={(e) => setFormData({ ...formData, address: e.target.value })}
placeholder="ул. Примерная, д. 1"
required
/>
<Input
label="Телефон покупателя"
type="tel"
value={formData.phone}
onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
onFocus={(e) => {
if (!e.target.value) {
setFormData({ ...formData, phone: '+7' });
}
}}
placeholder="+7 (776)-567-89-01"
required
aria-invalid={!isPhoneValid}
aria-describedby={!isPhoneValid ? 'phone-error' : undefined}
/>
{!isPhoneValid && formData.phone && (
<p id="phone-error" className="text-sm text-red-500 mt-1">
Введите корректный номер: +7 (XXX) XXX-XX-XX
</p>
)}
<Input
label="Дополнительный номер телефона"
type="tel"
value={formData.additionalPhone}
onChange={(e) => setFormData({ ...formData, additionalPhone: e.target.value })}
onFocus={(e) => {
if (!e.target.value) {
setFormData({ ...formData, additionalPhone: '+7' });
}
}}
placeholder="+7 (776)-567-89-01"
aria-invalid={!isAdditionalPhoneValid}
aria-describedby={!isAdditionalPhoneValid ? 'additional-phone-error' : undefined}
/>
{!isAdditionalPhoneValid && formData.additionalPhone && (
<p id="additional-phone-error" className="text-sm text-red-500 mt-1">
Введите корректный номер: +7 (XXX) XXX-XX-XX
</p>
)}
<div className="flex items-center gap-2">
<input
type="checkbox"
id="hasElevator"
checked={formData.hasElevator}
onChange={(e) => setFormData({ ...formData, hasElevator: e.target.checked })}
className="w-4 h-4 text-[#1B263B] border-[#c5c6cd] rounded focus:ring-[#1B263B]"
/>
<label htmlFor="hasElevator" className="text-sm text-[#1b1b1d]">
Наличие лифта
</label>
</div>
<Input
label="Комментарий"
value={formData.comment}
onChange={(e) => setFormData({ ...formData, comment: e.target.value })}
placeholder="Дополнительная информация..."
/>
</form>
</Modal>
);
};
@@ -0,0 +1,139 @@
import { useState, useMemo } from 'react';
import { Plus, LayoutGrid, Table as TableIcon } from 'lucide-react';
import { DeliveryCard } from './DeliveryCard';
import { DeliveryRow } from './DeliveryRow';
import { Button } from '../ui/Button';
import type { Delivery } from '../../types';
interface DeliveryListProps {
deliveries: Delivery[];
onStatusChange: (id: string) => void;
onEdit: (delivery: Delivery) => void;
onDelete: (id: string) => void;
onAdd: () => void;
date: string;
}
export const DeliveryList = ({ deliveries, onStatusChange, onEdit, onDelete, onAdd, date }: DeliveryListProps) => {
const [viewMode, setViewMode] = useState<'kanban' | 'table'>('kanban');
const newDeliveries = useMemo(() => deliveries.filter(d => d.status === 'new'), [deliveries]);
const deliveredDeliveries = useMemo(() => deliveries.filter(d => d.status === 'delivered'), [deliveries]);
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold text-[#1b1b1d]">
Доставки на {date}
</h2>
<div className="flex items-center gap-2">
<div className="flex bg-[#f0edef] rounded-lg p-1">
<button
onClick={() => setViewMode('kanban')}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
viewMode === 'kanban' ? 'bg-white shadow-sm text-[#1b1b1d]' : 'text-[#75777d] hover:text-[#1b1b1d]'
}`}
>
<LayoutGrid size={16} />
<span className="hidden sm:inline">Канбан</span>
</button>
<button
onClick={() => setViewMode('table')}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
viewMode === 'table' ? 'bg-white shadow-sm text-[#1b1b1d]' : 'text-[#75777d] hover:text-[#1b1b1d]'
}`}
>
<TableIcon size={16} />
<span className="hidden sm:inline">Таблица</span>
</button>
</div>
<Button onClick={onAdd} size="sm">
<Plus size={16} className="mr-1" />
<span className="hidden sm:inline">Добавить</span>
</Button>
</div>
</div>
{deliveries.length === 0 ? (
<div className="text-center py-12 bg-[#f5f3f5] rounded-lg">
<p className="text-[#75777d]">Нет доставок на эту дату</p>
<Button onClick={onAdd} variant="ghost" className="mt-2">
Создать первую доставку
</Button>
</div>
) : viewMode === 'kanban' ? (
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-medium text-[#1b1b1d] flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-[#F28C28]"></span>
Новые
<span className="text-sm text-[#75777d] font-normal">({newDeliveries.length})</span>
</h3>
</div>
<div className="space-y-3">
{newDeliveries.map(delivery => (
<DeliveryCard
key={delivery.id}
delivery={delivery}
onStatusChange={onStatusChange}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</div>
</div>
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="font-medium text-[#1b1b1d] flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-[#16a34a]"></span>
Доставлено
<span className="text-sm text-[#75777d] font-normal">({deliveredDeliveries.length})</span>
</h3>
</div>
<div className="space-y-3">
{deliveredDeliveries.map(delivery => (
<DeliveryCard
key={delivery.id}
delivery={delivery}
onStatusChange={onStatusChange}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</div>
</div>
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full bg-white rounded-lg shadow-sm border border-[#e4e2e4]">
<thead className="bg-[#f5f3f5]">
<tr className="text-left text-xs font-semibold text-[#75777d] uppercase tracking-wider">
<th className="px-4 py-3">Статус</th>
<th className="px-4 py-3">Дата</th>
<th className="px-4 py-3">Загрузка</th>
<th className="px-4 py-3">Товар</th>
<th className="px-4 py-3">Адрес</th>
<th className="px-4 py-3">Телефон</th>
<th className="px-4 py-3">Комментарий</th>
<th className="px-4 py-3">Действия</th>
</tr>
</thead>
<tbody className="divide-y divide-[#e4e2e4]">
{deliveries.map(delivery => (
<DeliveryRow
key={delivery.id}
delivery={delivery}
onStatusChange={onStatusChange}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</tbody>
</table>
</div>
)}
</div>
);
};
@@ -0,0 +1,81 @@
import { memo } from 'react';
import { MapPin, Phone } from 'lucide-react';
import type { Delivery } from '../../types';
import { pickupLocationLabels } from '../../types';
import { StatusBadge } from './StatusBadge';
interface DeliveryRowProps {
delivery: Delivery;
onStatusChange: (id: string) => void;
onEdit: (delivery: Delivery) => void;
onDelete: (id: string) => void;
}
export const DeliveryRow = memo(({ delivery, onStatusChange, onEdit, onDelete }: DeliveryRowProps) => {
const handleAddressClick = (e: React.MouseEvent) => {
e.stopPropagation();
const encodedAddress = encodeURIComponent(delivery.address);
window.open(`https://maps.google.com/?q=${encodedAddress}`, '_blank');
};
const handlePhoneClick = (e: React.MouseEvent) => {
e.stopPropagation();
window.location.href = `tel:${delivery.phone}`;
};
return (
<tr className="hover:bg-[#f5f3f5] transition-colors border-b border-[#e4e2e4] last:border-b-0">
<td className="px-4 py-3">
<StatusBadge
status={delivery.status}
onClick={() => onStatusChange(delivery.id)}
size="sm"
/>
</td>
<td className="px-4 py-3 text-sm text-[#1b1b1d]">{delivery.date}</td>
<td className="px-4 py-3 text-sm text-[#1b1b1d]">{pickupLocationLabels[delivery.pickupLocation]}</td>
<td className="px-4 py-3 text-sm text-[#1b1b1d]">{delivery.productName}</td>
<td className="px-4 py-3">
<button
onClick={handleAddressClick}
className="flex items-center gap-1.5 text-sm text-[#1B263B] hover:text-[#F28C28] transition-colors text-left"
>
<MapPin size={14} />
<span className="max-w-[200px] truncate">{delivery.address}</span>
</button>
</td>
<td className="px-4 py-3">
<button
onClick={handlePhoneClick}
className="flex items-center gap-1.5 text-sm text-[#16a34a] hover:underline transition-colors"
>
<Phone size={14} />
{delivery.phone}
</button>
</td>
<td className="px-4 py-3 text-sm text-[#45474d] max-w-[200px] truncate">
{delivery.comment || '-'}
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-1">
<button
onClick={() => onEdit(delivery)}
className="p-1.5 rounded-md hover:bg-[#e4e2e4] text-[#75777d] transition-colors"
title="Редактировать"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/></svg>
</button>
<button
onClick={() => onDelete(delivery.id)}
className="p-1.5 rounded-md hover:bg-red-50 text-red-500 transition-colors"
title="Удалить"
>
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
</button>
</div>
</td>
</tr>
);
});
DeliveryRow.displayName = 'DeliveryRow';
@@ -0,0 +1,34 @@
import type { DeliveryStatus } from '../../types';
import { statusLabels } from '../../types';
interface StatusBadgeProps {
status: DeliveryStatus;
onClick?: () => void;
size?: 'sm' | 'md' | 'lg';
}
export const StatusBadge = ({ status, onClick, size = 'md' }: StatusBadgeProps) => {
const baseStyles = 'inline-flex items-center justify-center font-medium rounded-full transition-colors';
const variants = {
new: 'bg-[#ffdcc3] text-[#6e3900]',
delivered: 'bg-[#dcfce7] text-[#166534]',
};
const sizes = {
sm: 'px-2 py-0.5 text-xs',
md: 'px-3 py-1 text-sm',
lg: 'px-4 py-2 text-base',
};
const clickableStyles = onClick ? 'cursor-pointer hover:opacity-80 active:scale-95' : '';
return (
<span
className={`${baseStyles} ${variants[status]} ${sizes[size]} ${clickableStyles}`}
onClick={onClick}
>
{statusLabels[status]}
</span>
);
};
+39
View File
@@ -0,0 +1,39 @@
import type { ButtonHTMLAttributes, ReactNode } from 'react';
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: 'primary' | 'secondary' | 'tertiary' | 'ghost';
size?: 'sm' | 'md' | 'lg';
children: ReactNode;
}
export const Button = ({
variant = 'primary',
size = 'md',
children,
className = '',
...props
}: ButtonProps) => {
const baseStyles = 'inline-flex items-center justify-center font-medium rounded-md transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed';
const variants = {
primary: 'bg-[#1B263B] text-white hover:bg-[#2a3a52] focus:ring-[#1B263B]',
secondary: 'bg-[#f0edef] text-[#1b1b1d] hover:bg-[#e4e2e4] focus:ring-[#75777d]',
tertiary: 'bg-[#F28C28] text-white hover:bg-[#d97a1f] focus:ring-[#F28C28]',
ghost: 'bg-transparent text-[#1b1b1d] hover:bg-[#f5f3f5] focus:ring-[#75777d]',
};
const sizes = {
sm: 'px-3 py-1.5 text-sm',
md: 'px-4 py-2 text-base',
lg: 'px-6 py-3 text-lg',
};
return (
<button
className={`${baseStyles} ${variants[variant]} ${sizes[size]} ${className}`}
{...props}
>
{children}
</button>
);
};
+22
View File
@@ -0,0 +1,22 @@
import type { ReactNode } from 'react';
interface CardProps {
children: ReactNode;
className?: string;
padding?: 'none' | 'sm' | 'md' | 'lg';
}
export const Card = ({ children, className = '', padding = 'md' }: CardProps) => {
const paddings = {
none: '',
sm: 'p-3',
md: 'p-4',
lg: 'p-6',
};
return (
<div className={`bg-white rounded-lg shadow-sm border border-[#e4e2e4] ${paddings[padding]} ${className}`}>
{children}
</div>
);
};
+25
View File
@@ -0,0 +1,25 @@
import type { InputHTMLAttributes } from 'react';
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: string;
}
export const Input = ({ label, error, className = '', ...props }: InputProps) => {
return (
<div className="w-full">
{label && (
<label className="block text-sm font-medium text-[#1b1b1d] mb-1">
{label}
</label>
)}
<input
className={`w-full px-3 py-2 bg-[#f5f3f5] border border-[#c5c6cd] rounded-md text-[#1b1b1d] placeholder-[#75777d] focus:outline-none focus:ring-2 focus:ring-[#1B263B] focus:border-transparent transition-colors ${className}`}
{...props}
/>
{error && (
<p className="mt-1 text-sm text-red-600">{error}</p>
)}
</div>
);
};
+44
View File
@@ -0,0 +1,44 @@
import { X } from 'lucide-react';
import type { ReactNode } from 'react';
interface ModalProps {
isOpen: boolean;
onClose: () => void;
title: string;
children: ReactNode;
footer?: ReactNode;
}
export const Modal = ({ isOpen, onClose, title, children, footer }: ModalProps) => {
if (!isOpen) return null;
return (
<div className="fixed inset-0 z-50 overflow-y-auto">
<div className="flex min-h-full items-center justify-center p-4 text-center">
<div
className="fixed inset-0 bg-black/30 transition-opacity"
onClick={onClose}
/>
<div className="relative transform overflow-hidden rounded-lg bg-white text-left shadow-xl transition-all w-full max-w-lg">
<div className="flex items-center justify-between border-b border-[#e4e2e4] px-4 py-3">
<h3 className="text-lg font-semibold text-[#1b1b1d]">{title}</h3>
<button
onClick={onClose}
className="rounded-full p-1 hover:bg-[#f5f3f5] transition-colors"
>
<X size={20} className="text-[#75777d]" />
</button>
</div>
<div className="px-4 py-4">
{children}
</div>
{footer && (
<div className="border-t border-[#e4e2e4] px-4 py-3 flex justify-end gap-2">
{footer}
</div>
)}
</div>
</div>
</div>
);
};
+37
View File
@@ -0,0 +1,37 @@
import type { SelectHTMLAttributes } from 'react';
interface SelectOption {
value: string;
label: string;
}
interface SelectProps extends SelectHTMLAttributes<HTMLSelectElement> {
label?: string;
options: SelectOption[];
error?: string;
}
export const Select = ({ label, options, error, className = '', ...props }: SelectProps) => {
return (
<div className="w-full">
{label && (
<label className="block text-sm font-medium text-[#1b1b1d] mb-1">
{label}
</label>
)}
<select
className={`w-full px-3 py-2 bg-[#f5f3f5] border border-[#c5c6cd] rounded-md text-[#1b1b1d] focus:outline-none focus:ring-2 focus:ring-[#1B263B] focus:border-transparent transition-colors ${className}`}
{...props}
>
{options.map((option) => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
{error && (
<p className="mt-1 text-sm text-red-600">{error}</p>
)}
</div>
);
};
+45
View File
@@ -0,0 +1,45 @@
import { useToastStore } from '../../stores/toastStore';
import { X, CheckCircle, AlertCircle, Info } from 'lucide-react';
const icons = {
success: CheckCircle,
error: AlertCircle,
info: Info,
};
const styles = {
success: 'bg-green-50 border-green-200 text-green-800',
error: 'bg-red-50 border-red-200 text-red-800',
info: 'bg-blue-50 border-blue-200 text-blue-800',
};
export const ToastContainer = () => {
const { toasts, removeToast } = useToastStore();
if (toasts.length === 0) return null;
return (
<div className="fixed bottom-4 right-4 z-50 flex flex-col gap-2">
{toasts.map((toast) => {
const Icon = icons[toast.type];
return (
<div
key={toast.id}
className={`flex items-center gap-3 px-4 py-3 rounded-lg border shadow-lg min-w-[300px] animate-in slide-in-from-right ${styles[toast.type]}`}
role="alert"
>
<Icon size={20} />
<p className="flex-1 text-sm">{toast.message}</p>
<button
onClick={() => removeToast(toast.id)}
className="p-1 hover:bg-black/5 rounded transition-colors"
aria-label="Закрыть"
>
<X size={16} />
</button>
</div>
);
})}
</div>
);
};
+5
View File
@@ -0,0 +1,5 @@
export { Button } from './Button';
export { Card } from './Card';
export { Modal } from './Modal';
export { Input } from './Input';
export { Select } from './Select';
+14
View File
@@ -0,0 +1,14 @@
import type { PickupLocation } from '../types';
import { pickupLocationLabels } from '../types';
export const pickupOptions: { value: PickupLocation; label: string }[] = [
{ value: 'warehouse', label: pickupLocationLabels.warehouse },
{ value: 'symbat', label: pickupLocationLabels.symbat },
{ value: 'nursaya', label: pickupLocationLabels.nursaya },
{ value: 'galaktika', label: pickupLocationLabels.galaktika },
];
export const pickupFilterOptions: { value: PickupLocation | 'all'; label: string }[] = [
{ value: 'all', label: 'Все места загрузки' },
...pickupOptions,
];
+83
View File
@@ -0,0 +1,83 @@
import { useEffect, useCallback } from 'react';
import { useDeliveryStore } from '../stores/deliveryStore';
import type { Delivery } from '../types';
type WebSocketEvent =
| { type: 'delivery.created'; payload: Delivery }
| { type: 'delivery.updated'; payload: Delivery }
| { type: 'delivery.deleted'; payload: { id: string } };
type EventHandler = (event: WebSocketEvent) => void;
class MockWebSocket {
private handlers: EventHandler[] = [];
private isConnected = false;
connect() {
this.isConnected = true;
console.log('WebSocket connected (mock)');
}
disconnect() {
this.isConnected = false;
console.log('WebSocket disconnected (mock)');
}
subscribe(handler: EventHandler) {
this.handlers.push(handler);
return () => {
this.handlers = this.handlers.filter((h) => h !== handler);
};
}
emit(event: WebSocketEvent) {
if (!this.isConnected) return;
this.handlers.forEach((handler) => handler(event));
}
simulateIncomingEvent(event: WebSocketEvent) {
this.emit(event);
}
}
const mockWebSocket = new MockWebSocket();
export const useWebSocket = () => {
const { addDelivery, updateDelivery, deleteDelivery } = useDeliveryStore();
useEffect(() => {
mockWebSocket.connect();
const unsubscribe = mockWebSocket.subscribe((event) => {
switch (event.type) {
case 'delivery.created':
addDelivery(event.payload);
break;
case 'delivery.updated':
updateDelivery(event.payload.id, event.payload);
break;
case 'delivery.deleted':
deleteDelivery(event.payload.id);
break;
}
});
return () => {
unsubscribe();
mockWebSocket.disconnect();
};
}, [addDelivery, updateDelivery, deleteDelivery]);
const sendEvent = useCallback((event: WebSocketEvent) => {
mockWebSocket.emit(event);
}, []);
return { sendEvent, isConnected: true };
};
export const simulateIncomingDelivery = (delivery: Delivery) => {
mockWebSocket.simulateIncomingEvent({
type: 'delivery.created',
payload: delivery,
});
};
+34
View File
@@ -0,0 +1,34 @@
@import "tailwindcss";
@theme {
--color-primary: #1B263B;
--color-primary-container: #051125;
--color-tertiary: #F28C28;
--color-surface: #fbf8fb;
--color-surface-container: #f0edef;
--color-surface-container-low: #f5f3f5;
--color-surface-container-high: #eae7e9;
--color-on-surface: #1b1b1d;
--color-outline: #75777d;
--color-outline-variant: #c5c6cd;
--color-success: #16a34a;
--font-sans: 'Inter', system-ui, sans-serif;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: var(--font-sans);
background-color: var(--color-surface);
color: var(--color-on-surface);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
#root {
min-height: 100vh;
width: 100%;
}
+22
View File
@@ -0,0 +1,22 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js', { scope: '/' })
.then((registration) => {
console.log('SW registered:', registration)
})
.catch((error) => {
console.log('SW registration failed:', error)
})
})
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)
+241
View File
@@ -0,0 +1,241 @@
import { useState, useEffect, useMemo } from 'react';
import { Plus, Printer, ChevronRight, CalendarDays } from 'lucide-react';
import { format, startOfMonth, endOfMonth, eachDayOfInterval, isToday } from 'date-fns';
import { ru } from 'date-fns/locale';
import { useDeliveryStore } from '../stores/deliveryStore';
import type { Delivery } from '../types';
import { pickupLocationLabels } from '../types';
import { Button } from '../components/ui/Button';
import { Card } from '../components/ui/Card';
interface DashboardProps {
onDateSelect: (date: string) => void;
onAddDelivery: () => void;
}
const Dashboard = ({ onDateSelect, onAddDelivery }: DashboardProps) => {
const deliveryCounts = useDeliveryStore(state => state.deliveryCounts);
const fetchDeliveryCounts = useDeliveryStore(state => state.fetchDeliveryCounts);
const [currentMonth, setCurrentMonth] = useState(new Date());
// Fetch counts on mount
useEffect(() => {
fetchDeliveryCounts();
}, [fetchDeliveryCounts]);
const days = useMemo(() => {
const monthStart = startOfMonth(currentMonth);
const monthEnd = endOfMonth(currentMonth);
return eachDayOfInterval({ start: monthStart, end: monthEnd });
}, [currentMonth]);
const getCountForDate = (date: Date) => {
const dateStr = format(date, 'dd-MM-yyyy');
return deliveryCounts[dateStr] || 0;
};
const handlePrintDay = (date: Date) => {
const dateStr = format(date, 'dd-MM-yyyy');
const fetchDeliveriesByDate = useDeliveryStore.getState().fetchDeliveriesByDate;
// Fetch and print
fetchDeliveriesByDate(dateStr).then(() => {
const deliveries = useDeliveryStore.getState().deliveries;
printDeliveries(date, deliveries);
});
};
const printDeliveries = (date: Date, dayDeliveries: Delivery[]) => {
const printWindow = window.open('', '_blank');
if (!printWindow) return;
const html = `
<!DOCTYPE html>
<html>
<head>
<title>Доставки на ${format(date, 'dd MMMM yyyy', { locale: ru })}</title>
<style>
body { font-family: system-ui, sans-serif; margin: 20px; }
h1 { font-size: 18px; margin-bottom: 16px; }
table { width: 100%; border-collapse: collapse; }
th, td { text-align: left; padding: 8px; border-bottom: 1px solid #ddd; }
th { font-weight: 600; background: #f5f5f5; }
.status-new { background: #ffdcc3; padding: 2px 8px; border-radius: 12px; font-size: 12px; }
.status-delivered { background: #dcfce7; padding: 2px 8px; border-radius: 12px; font-size: 12px; }
</style>
</head>
<body>
<h1>Доставки на ${format(date, 'dd MMMM yyyy', { locale: ru })}</h1>
<table>
<tr>
<th>Статус</th>
<th>Загрузка</th>
<th>Товар</th>
<th>Адрес</th>
<th>Телефон</th>
<th>Комментарий</th>
</tr>
${dayDeliveries.map((d: Delivery) => `
<tr>
<td><span class="status-${d.status}">${d.status === 'new' ? 'Новое' : 'Доставлено'}</span></td>
<td>${pickupLocationLabels[d.pickupLocation]}</td>
<td>${d.productName}</td>
<td>${d.address}</td>
<td>${d.phone}</td>
<td>${d.comment || '-'}</td>
</tr>
`).join('')}
</table>
</body>
</html>
`;
printWindow.document.write(html);
printWindow.document.close();
printWindow?.print();
};
const navigateMonth = (direction: 'prev' | 'next') => {
setCurrentMonth(prev => {
const newDate = new Date(prev);
newDate.setMonth(prev.getMonth() + (direction === 'next' ? 1 : -1));
return newDate;
});
};
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-[#1b1b1d]">Панель управления</h1>
<p className="text-[#75777d] mt-1">Выберите дату для просмотра доставок</p>
</div>
<Button onClick={onAddDelivery}>
<Plus size={18} className="mr-2" />
Новая доставка
</Button>
</div>
<Card className="p-6">
<div className="flex items-center justify-between mb-6">
<h2 className="text-lg font-semibold text-[#1b1b1d] flex items-center gap-2">
<CalendarDays size={20} className="text-[#1B263B]" />
{format(currentMonth, 'LLLL yyyy', { locale: ru })}
</h2>
<div className="flex gap-2">
<Button variant="ghost" size="sm" onClick={() => navigateMonth('prev')}>
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setCurrentMonth(new Date())}
>
Сегодня
</Button>
<Button variant="ghost" size="sm" onClick={() => navigateMonth('next')}>
</Button>
</div>
</div>
<div className="grid grid-cols-7 gap-1 mb-2">
{['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'].map(day => (
<div key={day} className="text-center text-xs font-medium text-[#75777d] py-2">
{day}
</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">
{days.map((day) => {
const count = getCountForDate(day);
const isTodayDate = isToday(day);
return (
<button
key={day.toISOString()}
onClick={() => onDateSelect(format(day, 'dd-MM-yyyy'))}
className={`
relative p-3 rounded-lg text-left transition-all min-h-[80px]
${isTodayDate ? 'bg-[#1B263B] text-white' : 'hover:bg-[#f5f3f5]'}
${!isTodayDate && count > 0 ? 'bg-[#ffdcc3]/30' : ''}
`}
>
<div className={`text-sm font-medium ${isTodayDate ? 'text-white' : 'text-[#1b1b1d]'}`}>
{format(day, 'd')}
</div>
{count > 0 && (
<div className={`mt-1 text-[10px] truncate w-full ${isTodayDate ? 'text-white/80' : 'text-[#F28C28]'}`}>
{count} {count === 1 ? 'доставка' : count < 5 ? 'доставки' : 'доставок'}
</div>
)}
</button>
);
})}
</div>
</Card>
<div className="space-y-3">
<h3 className="font-semibold text-[#1b1b1d]">Ближайшие даты с доставками</h3>
{days
.filter(day => getCountForDate(day) > 0)
.slice(0, 7)
.map(day => {
const count = getCountForDate(day);
return (
<Card key={day.toISOString()} className="flex items-center justify-between p-4">
<div className="flex items-center gap-4">
<div className="text-center min-w-[60px]">
<div className="text-2xl font-bold text-[#1B263B]">
{format(day, 'd')}
</div>
<div className="text-xs text-[#75777d] uppercase">
{format(day, 'MMM', { locale: ru })}
</div>
</div>
<div>
<div className="font-medium text-[#1b1b1d]">
{count} {count === 1 ? 'доставка' : count < 5 ? 'доставки' : 'доставок'}
</div>
<div className="text-sm text-[#75777d]">
{format(day, 'EEEE', { locale: ru })}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => handlePrintDay(day)}
>
<Printer size={16} />
</Button>
<Button
variant="secondary"
size="sm"
onClick={() => onDateSelect(format(day, 'dd-MM-yyyy'))}
>
Открыть
<ChevronRight size={16} className="ml-1" />
</Button>
</div>
</Card>
);
})}
{days.filter(day => getCountForDate(day) > 0).length === 0 && (
<Card className="p-8 text-center">
<p className="text-[#75777d]">Нет запланированных доставок</p>
<Button onClick={onAddDelivery} variant="ghost" className="mt-2">
Создать первую доставку
</Button>
</Card>
)}
</div>
</div>
);
};
export default Dashboard;
+148
View File
@@ -0,0 +1,148 @@
import { useState, useEffect, useMemo } from 'react';
import { ArrowLeft, Filter, Loader2, AlertCircle } from 'lucide-react';
import { useDeliveryStore } from '../stores/deliveryStore';
import { DeliveryList as DeliveryListComponent } from '../components/delivery/DeliveryList';
import { DeliveryForm } from '../components/delivery/DeliveryForm';
import { Button } from '../components/ui/Button';
import { Select } from '../components/ui/Select';
import { pickupFilterOptions } from '../constants/pickup';
import type { Delivery, PickupLocation } from '../types';
interface DeliveryListPageProps {
selectedDate: string;
onBack: () => void;
}
const DeliveryListPage = ({ selectedDate, onBack }: DeliveryListPageProps) => {
const {
deliveries,
isLoading,
error,
fetchDeliveriesByDate,
toggleStatus,
deleteDelivery,
updateDelivery,
addDelivery,
clearError,
} = useDeliveryStore();
// Fetch deliveries when date changes
useEffect(() => {
fetchDeliveriesByDate(selectedDate);
}, [selectedDate, fetchDeliveriesByDate]);
const [isFormOpen, setIsFormOpen] = useState(false);
const [editingDelivery, setEditingDelivery] = useState<Delivery | null>(null);
const [pickupFilter, setPickupFilter] = useState<PickupLocation | 'all'>('all');
// Use all deliveries from store (already filtered by API)
const filteredDeliveries = useMemo(() => {
if (pickupFilter === 'all') return deliveries;
return deliveries.filter(d => d.pickupLocation === pickupFilter);
}, [deliveries, pickupFilter]);
const handleStatusChange = async (id: string) => {
const delivery = deliveries.find(d => d.id === id);
if (delivery) {
await toggleStatus(id, delivery.status);
}
};
const handleEdit = (delivery: Delivery) => {
setEditingDelivery(delivery);
setIsFormOpen(true);
};
const handleDelete = async (id: string) => {
if (confirm('Удалить эту доставку?')) {
try {
await deleteDelivery(id);
} catch {
// Error is handled by store
}
}
};
const handleSubmit = async (data: Omit<Delivery, 'id' | 'createdAt' | 'updatedAt'>) => {
try {
if (editingDelivery) {
await updateDelivery(editingDelivery.id, data);
} else {
await addDelivery(data);
}
setEditingDelivery(null);
} catch {
// Error is handled by store
}
};
const handleAdd = () => {
setEditingDelivery(null);
setIsFormOpen(true);
};
const handleCloseForm = () => {
setIsFormOpen(false);
setEditingDelivery(null);
};
return (
<div className="space-y-4">
<div className="flex items-center justify-between flex-wrap gap-4">
<div className="flex items-center gap-4">
<Button variant="ghost" size="sm" onClick={onBack}>
<ArrowLeft size={18} className="mr-1" />
Назад
</Button>
<div className="flex items-center gap-2 text-sm text-[#75777d]">
<Filter size={16} />
<span>Всего: {filteredDeliveries.length}</span>
</div>
</div>
<div className="w-48">
<Select
label=""
value={pickupFilter}
onChange={(e) => setPickupFilter(e.target.value as PickupLocation | 'all')}
options={pickupFilterOptions}
/>
</div>
</div>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-[#1B263B]" />
</div>
) : error ? (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3">
<AlertCircle className="w-5 h-5 text-red-500" />
<div className="flex-1">
<p className="text-red-700">{error}</p>
</div>
<Button variant="ghost" size="sm" onClick={() => { clearError(); fetchDeliveriesByDate(selectedDate); }}>
Повторить
</Button>
</div>
) : (
<DeliveryListComponent
deliveries={filteredDeliveries}
onStatusChange={handleStatusChange}
onEdit={handleEdit}
onDelete={handleDelete}
onAdd={handleAdd}
date={selectedDate}
/>
)}
<DeliveryForm
isOpen={isFormOpen}
onClose={handleCloseForm}
onSubmit={handleSubmit}
initialData={editingDelivery}
defaultDate={selectedDate}
/>
</div>
);
};
export default DeliveryListPage;
+177
View File
@@ -0,0 +1,177 @@
import { create } from 'zustand';
import { deliveriesApi } from '../api';
import { useToastStore } from './toastStore';
import type { Delivery, DeliveryStatus } from '../types';
interface DeliveryState {
// Data
deliveries: Delivery[];
deliveryCounts: Record<string, number>;
// Loading states
isLoading: boolean;
isLoadingCounts: boolean;
error: string | null;
// Actions
fetchDeliveriesByDate: (date: string) => Promise<void>;
fetchDeliveryCounts: () => Promise<void>;
addDelivery: (delivery: Omit<Delivery, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>;
updateDelivery: (id: string, updates: Omit<Delivery, 'id' | 'createdAt' | 'updatedAt'>) => Promise<void>;
deleteDelivery: (id: string) => Promise<void>;
toggleStatus: (id: string, currentStatus: DeliveryStatus) => Promise<void>;
getDeliveriesByDate: (date: string) => Delivery[];
getDeliveriesByDateRange: (startDate: string, endDate: string) => Delivery[];
getDeliveryCountsByDate: () => Record<string, number>;
clearError: () => void;
}
export const useDeliveryStore = create<DeliveryState>()((set, get) => ({
// Initial state
deliveries: [],
deliveryCounts: {},
isLoading: false,
isLoadingCounts: false,
error: null,
// Fetch deliveries for a specific date
fetchDeliveriesByDate: async (date: string) => {
set({ isLoading: true, error: null });
try {
const deliveries = await deliveriesApi.getByDate(date);
set({ deliveries, isLoading: false });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to fetch deliveries';
set({
error: message,
isLoading: false,
});
useToastStore.getState().addToast(message, 'error');
}
},
// Fetch delivery counts for calendar
fetchDeliveryCounts: async () => {
set({ isLoadingCounts: true, error: null });
try {
const counts = await deliveriesApi.getCounts();
set({ deliveryCounts: counts, isLoadingCounts: false });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to fetch counts';
set({
error: message,
isLoadingCounts: false,
});
useToastStore.getState().addToast(message, 'error');
}
},
// Add new delivery
addDelivery: async (delivery) => {
set({ isLoading: true, error: null });
try {
await deliveriesApi.create(delivery);
// Refresh deliveries for that date
await get().fetchDeliveriesByDate(delivery.date);
// Refresh counts
await get().fetchDeliveryCounts();
set({ isLoading: false });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to create delivery';
set({
error: message,
isLoading: false,
});
useToastStore.getState().addToast(message, 'error');
throw err;
}
},
// Update delivery
updateDelivery: async (id, updates) => {
set({ isLoading: true, error: null });
try {
await deliveriesApi.update(id, updates);
// Refresh deliveries for that date
await get().fetchDeliveriesByDate(updates.date);
// Refresh counts (in case date changed)
await get().fetchDeliveryCounts();
set({ isLoading: false });
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to update delivery';
set({
error: message,
isLoading: false,
});
useToastStore.getState().addToast(message, 'error');
throw err;
}
},
// Delete delivery
deleteDelivery: async (id) => {
set({ isLoading: true, error: null });
try {
await deliveriesApi.delete(id);
// Remove from local state
set((state) => ({
deliveries: state.deliveries.filter((d) => d.id !== id),
isLoading: false,
}));
// Refresh counts
await get().fetchDeliveryCounts();
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to delete delivery';
set({
error: message,
isLoading: false,
});
useToastStore.getState().addToast(message, 'error');
throw err;
}
},
// Toggle delivery status
toggleStatus: async (id, currentStatus) => {
set({ isLoading: true, error: null });
try {
const newStatus = currentStatus === 'new' ? 'delivered' : 'new';
await deliveriesApi.updateStatus(id, newStatus);
// Update local state
set((state) => ({
deliveries: state.deliveries.map((d) =>
d.id === id
? { ...d, status: newStatus, updatedAt: Date.now() }
: d
),
isLoading: false,
}));
} catch (err) {
const message = err instanceof Error ? err.message : 'Failed to update status';
set({
error: message,
isLoading: false,
});
useToastStore.getState().addToast(message, 'error');
throw err;
}
},
// Getters (local filtering)
getDeliveriesByDate: (date) => {
return get().deliveries.filter((d) => d.date === date);
},
getDeliveriesByDateRange: (startDate, endDate) => {
return get().deliveries.filter((d) => {
const date = d.date;
return date >= startDate && date <= endDate;
});
},
getDeliveryCountsByDate: () => {
return get().deliveryCounts;
},
clearError: () => set({ error: null }),
}));
+35
View File
@@ -0,0 +1,35 @@
import { create } from 'zustand';
export type ToastType = 'success' | 'error' | 'info';
interface Toast {
id: string;
message: string;
type: ToastType;
}
interface ToastState {
toasts: Toast[];
addToast: (message: string, type: ToastType) => void;
removeToast: (id: string) => void;
}
export const useToastStore = create<ToastState>((set) => ({
toasts: [],
addToast: (message, type) => {
const id = Math.random().toString(36).substring(2, 9);
set((state) => ({
toasts: [...state.toasts, { id, message, type }],
}));
// Auto remove after 5 seconds
setTimeout(() => {
set((state) => ({
toasts: state.toasts.filter((t) => t.id !== id),
}));
}, 5000);
},
removeToast: (id) =>
set((state) => ({
toasts: state.toasts.filter((t) => t.id !== id),
})),
}));
+30
View File
@@ -0,0 +1,30 @@
export type PickupLocation = 'warehouse' | 'symbat' | 'nursaya' | 'galaktika';
export type DeliveryStatus = 'new' | 'delivered';
export interface Delivery {
id: string;
date: string; // DD-MM-YYYY
pickupLocation: PickupLocation;
productName: string;
address: string;
phone: string;
additionalPhone?: string;
hasElevator: boolean;
comment: string;
status: DeliveryStatus;
createdAt: number;
updatedAt: number;
}
export const pickupLocationLabels: Record<PickupLocation, string> = {
warehouse: 'Склад',
symbat: 'Сымбат',
nursaya: 'Нурсая',
galaktika: 'Галактика',
};
export const statusLabels: Record<DeliveryStatus, string> = {
new: 'Новое',
delivered: 'Доставлено',
};
+52
View File
@@ -0,0 +1,52 @@
import { format, parse, type Locale } from 'date-fns';
/**
* Convert backend date format (YYYY-MM-DD) to frontend format (DD-MM-YYYY)
*/
export function backendDateToFrontend(dateStr: string): string {
const [year, month, day] = dateStr.split('-');
return `${day}-${month}-${year}`;
}
/**
* Convert frontend date format (DD-MM-YYYY) to backend format (YYYY-MM-DD)
*/
export function frontendDateToBackend(dateStr: string): string {
const [day, month, year] = dateStr.split('-');
return `${year}-${month}-${day}`;
}
/**
* Format frontend date for HTML input type="date" (YYYY-MM-DD)
*/
export function formatDateForInput(dateStr: string): string {
const [day, month, year] = dateStr.split('-');
return `${year}-${month}-${day}`;
}
/**
* Parse date from HTML input type="date" to frontend format (DD-MM-YYYY)
*/
export function parseDateFromInput(dateStr: string): string {
const [year, month, day] = dateStr.split('-');
return `${day}-${month}-${year}`;
}
/**
* Get today's date in frontend format
*/
export function getTodayFrontend(): string {
return format(new Date(), 'dd-MM-yyyy');
}
/**
* Format frontend date for display with date-fns
*/
export function formatFrontendDate(
dateStr: string,
formatStr: string,
options?: { locale?: Locale }
): string {
const date = parse(dateStr, 'dd-MM-yyyy', new Date());
return format(date, formatStr, options);
}
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2023",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
+7
View File
@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
+26
View File
@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}
+37
View File
@@ -0,0 +1,37 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { VitePWA } from 'vite-plugin-pwa'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
tailwindcss(),
VitePWA({
registerType: 'autoUpdate',
manifest: false, // manifest.json from public
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,json}'],
runtimeCaching: [
{
urlPattern: /^https:\/\/.*\/api\//,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
},
},
],
},
}),
],
server: {
allowedHosts: ['delivery.loca.lt', '.loca.lt'],
proxy: {
'/api': {
target: 'http://localhost:8081',
changeOrigin: true,
},
},
},
})
+3592
View File
File diff suppressed because it is too large Load Diff