diff --git a/backend/excel.go b/backend/excel.go new file mode 100644 index 0000000..6a095cb --- /dev/null +++ b/backend/excel.go @@ -0,0 +1,15 @@ +//go:build !windows + +package main + +import "fmt" + +// Stub implementations for non-Windows platforms (for testing API without Excel COM). + +func FillCells(cells map[string]interface{}, fileContent []byte, printArea string) ([]byte, error) { + return nil, fmt.Errorf("Excel COM is only available on Windows") +} + +func ReadCells(fileContent []byte) (map[string]interface{}, error) { + return map[string]interface{}{"cells": map[string]interface{}{}, "merged": []interface{}{}}, nil +} diff --git a/backend/excel_windows.go b/backend/excel_windows.go new file mode 100644 index 0000000..432f98f --- /dev/null +++ b/backend/excel_windows.go @@ -0,0 +1,131 @@ +//go:build windows + +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/go-ole/go-ole" + "github.com/go-ole/go-ole/oleutil" +) + +func FillCells(cells map[string]interface{}, fileContent []byte, printArea string) ([]byte, error) { + ole.CoInitialize(0) + defer ole.CoUninitialize() + + tmpInput, err := os.CreateTemp("", "*.xlsx") + if err != nil { + return nil, err + } + tmpInput.Write(fileContent) + tmpInput.Close() + inputPath, _ := filepath.Abs(tmpInput.Name()) + defer os.Remove(inputPath) + + outputPath, _ := filepath.Abs(filepath.Join(os.TempDir(), "out_"+filepath.Base(inputPath))) + defer os.Remove(outputPath) + + unknown, err := oleutil.CreateObject("Excel.Application") + if err != nil { + return nil, fmt.Errorf("Excel COM not available: %w", err) + } + excel, _ := unknown.QueryInterface(ole.IID_IDispatch) + defer excel.Release() + + oleutil.PutProperty(excel, "Visible", false) + oleutil.PutProperty(excel, "DisplayAlerts", false) + + workbooks := oleutil.MustGetProperty(excel, "Workbooks").ToIDispatch() + workbook := oleutil.MustCallMethod(workbooks, "Open", inputPath).ToIDispatch() + sheet := oleutil.MustGetProperty(workbook, "ActiveSheet").ToIDispatch() + + for addr, value := range cells { + cell := oleutil.MustGetProperty(sheet, "Range", addr).ToIDispatch() + oleutil.PutProperty(cell, "Value", value) + cell.Release() + } + + if printArea != "" { + pageSetup := oleutil.MustGetProperty(sheet, "PageSetup").ToIDispatch() + oleutil.PutProperty(pageSetup, "PrintArea", printArea) + pageSetup.Release() + } + + oleutil.MustCallMethod(workbook, "SaveAs", outputPath) + oleutil.MustCallMethod(workbook, "Close") + oleutil.MustCallMethod(excel, "Quit") + + return os.ReadFile(outputPath) +} + +func ReadCells(fileContent []byte) (map[string]interface{}, error) { + ole.CoInitialize(0) + defer ole.CoUninitialize() + + tmpInput, err := os.CreateTemp("", "*.xlsx") + if err != nil { + return nil, err + } + tmpInput.Write(fileContent) + tmpInput.Close() + inputPath, _ := filepath.Abs(tmpInput.Name()) + defer os.Remove(inputPath) + + unknown, err := oleutil.CreateObject("Excel.Application") + if err != nil { + return nil, fmt.Errorf("Excel COM not available: %w", err) + } + excel, _ := unknown.QueryInterface(ole.IID_IDispatch) + defer excel.Release() + + oleutil.PutProperty(excel, "Visible", false) + oleutil.PutProperty(excel, "DisplayAlerts", false) + + workbooks := oleutil.MustGetProperty(excel, "Workbooks").ToIDispatch() + workbook := oleutil.MustCallMethod(workbooks, "Open", inputPath).ToIDispatch() + sheet := oleutil.MustGetProperty(workbook, "ActiveSheet").ToIDispatch() + + usedRange := oleutil.MustGetProperty(sheet, "UsedRange").ToIDispatch() + rowCount := int(oleutil.MustGetProperty(oleutil.MustGetProperty(usedRange, "Rows").ToIDispatch(), "Count").Val) + colCount := int(oleutil.MustGetProperty(oleutil.MustGetProperty(usedRange, "Columns").ToIDispatch(), "Count").Val) + + cells := map[string]interface{}{} + for r := 1; r <= rowCount; r++ { + for c := 1; c <= colCount; c++ { + cell := oleutil.MustGetProperty(sheet, "Cells", r, c).ToIDispatch() + val, _ := oleutil.GetProperty(cell, "Value") + if val.Val != 0 { + addr := oleutil.MustGetProperty(cell, "Address", false, false).ToString() + addr = strings.ReplaceAll(addr, "$", "") + cells[addr] = val.Value() + } + cell.Release() + } + } + + var merged []map[string]string + mergedAreas := oleutil.MustGetProperty(sheet, "MergedCells").ToIDispatch() + if mergedAreas != nil { + mergeCount, err := oleutil.GetProperty(mergedAreas, "Count") + if err == nil && mergeCount.Val > 0 { + for i := 1; i <= int(mergeCount.Val); i++ { + area := oleutil.MustGetProperty(mergedAreas, "Item", i).ToIDispatch() + addrStr := oleutil.MustGetProperty(area, "Address", false, false).ToString() + addrStr = strings.ReplaceAll(addrStr, "$", "") + parts := strings.Split(addrStr, ":") + if len(parts) == 2 { + merged = append(merged, map[string]string{"from": parts[0], "to": parts[1]}) + } + area.Release() + } + } + } + + oleutil.MustCallMethod(workbook, "Close", false) + oleutil.MustCallMethod(excel, "Quit") + + return map[string]interface{}{"cells": cells, "merged": merged}, nil +} diff --git a/backend/go.mod b/backend/go.mod new file mode 100644 index 0000000..56242c1 --- /dev/null +++ b/backend/go.mod @@ -0,0 +1,50 @@ +module protoc-backend + +go 1.25.5 + +require ( + github.com/gin-gonic/gin v1.12.0 + github.com/go-ole/go-ole v1.3.0 + github.com/google/uuid v1.6.0 + gorm.io/driver/postgres v1.6.0 + gorm.io/gorm v1.31.1 +) + +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/pgx/v5 v5.6.0 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + 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.22.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/sync v0.19.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect +) diff --git a/backend/go.sum b/backend/go.sum new file mode 100644 index 0000000..9892b6f --- /dev/null +++ b/backend/go.sum @@ -0,0 +1,113 @@ +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/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-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= +github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= +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.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= +github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= +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/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +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.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.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.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4= +golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +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.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +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= +gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4= +gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo= +gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg= +gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= diff --git a/backend/handler.go b/backend/handler.go new file mode 100644 index 0000000..f76a609 --- /dev/null +++ b/backend/handler.go @@ -0,0 +1,726 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "gorm.io/gorm" +) + +// --- Helpers --- + +func parseUUID(c *gin.Context, param string) (uuid.UUID, bool) { + id, err := uuid.Parse(c.Param(param)) + if err != nil { + c.JSON(400, gin.H{"detail": "invalid uuid"}) + return uuid.Nil, false + } + return id, true +} + +func templateAttributeDetails(db *gorm.DB, templateID uuid.UUID) []gin.H { + var allAttrs []Attribute + db.Find(&allAttrs) + + var tas []TemplateAttribute + db.Where("template_id = ?", templateID).Preload("Attribute").Find(&tas) + + taMap := map[uuid.UUID]*TemplateAttribute{} + for i := range tas { + taMap[tas[i].AttributeID] = &tas[i] + } + + result := []gin.H{} + for _, a := range allAttrs { + detail := gin.H{ + "attribute_id": a.ID, + "attribute_name": a.Name, + "is_required": a.IsRequired, + "value": nil, + } + if ta, ok := taMap[a.ID]; ok { + detail["value"] = ta.Value + } + result = append(result, detail) + } + return result +} + +func templateWithAttrs(db *gorm.DB, t Template) gin.H { + return gin.H{ + "id": t.ID, + "name": t.Name, + "description": t.Description, + "elements": json.RawMessage(t.Elements), + "group_id": t.GroupID, + "attributes": templateAttributeDetails(db, t.ID), + "order": t.Order, + "created_at": t.CreatedAt, + "updated_at": t.UpdatedAt, + "deleted_at": t.DeletedAt, + } +} + +// --- Templates --- + +func getTemplates(c *gin.Context, db *gorm.DB) { + var templates []Template + db.Find(&templates) + + result := []gin.H{} + for _, t := range templates { + result = append(result, templateWithAttrs(db, t)) + } + c.JSON(200, gin.H{"templates": result}) +} + +func getTemplate(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var t Template + if db.First(&t, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"template": nil}) + return + } + c.JSON(200, gin.H{"template": templateWithAttrs(db, t)}) +} + +func createTemplate(c *gin.Context, db *gorm.DB) { + var input struct { + Name string `json:"name"` + Description string `json:"description"` + Elements json.RawMessage `json:"elements"` + Attributes []setTemplateAttrInput `json:"attributes"` + GroupID *uuid.UUID `json:"group_id"` + } + if c.BindJSON(&input) != nil { + return + } + + t := Template{Name: input.Name, Description: &input.Description, Elements: JSON(input.Elements), GroupID: input.GroupID} + db.Create(&t) + + for _, a := range input.Attributes { + db.Create(&TemplateAttribute{TemplateID: t.ID, AttributeID: a.AttributeID, Value: a.Value}) + } + c.JSON(200, gin.H{"id": t.ID}) +} + +type setTemplateAttrInput struct { + AttributeID uuid.UUID `json:"attribute_id"` + Value *string `json:"value"` +} + +func patchTemplate(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var t Template + if db.First(&t, "id = ?", id).Error != nil { + c.JSON(404, gin.H{"detail": "Template not found"}) + return + } + + var input struct { + Name *string `json:"name"` + Description *string `json:"description"` + Elements *json.RawMessage `json:"elements"` + Attributes []setTemplateAttrInput `json:"attributes"` + GroupID interface{} `json:"group_id"` + Order *float64 `json:"order"` + } + if c.BindJSON(&input) != nil { + return + } + + updates := map[string]interface{}{} + if input.Name != nil { + updates["name"] = *input.Name + } + if input.Description != nil { + updates["description"] = *input.Description + } + if input.Elements != nil { + updates["elements"] = JSON(*input.Elements) + } + if input.Order != nil { + updates["order"] = *input.Order + } + if input.GroupID != nil { + switch v := input.GroupID.(type) { + case string: + if v == "ungroup" { + updates["group_id"] = nil + } else { + if uid, err := uuid.Parse(v); err == nil { + updates["group_id"] = uid + } + } + } + } + + if len(updates) > 0 { + db.Model(&t).Updates(updates) + } + + for _, a := range input.Attributes { + res := db.Model(&TemplateAttribute{}).Where("template_id = ? AND attribute_id = ?", id, a.AttributeID).Update("value", a.Value) + if res.RowsAffected == 0 { + db.Create(&TemplateAttribute{TemplateID: id, AttributeID: a.AttributeID, Value: a.Value}) + } + } + + c.JSON(200, gin.H{"id": t.ID}) +} + +func deleteTemplate(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + res := db.Delete(&Template{}, "id = ?", id) + if res.RowsAffected == 0 { + c.JSON(404, gin.H{"detail": "Template not found"}) + return + } + c.JSON(200, gin.H{"success": true, "template_id": id}) +} + +func copyTemplate(c *gin.Context, db *gorm.DB) { + var input struct { + TemplateID uuid.UUID `json:"template_id"` + NewName string `json:"new_name"` + NewDescription *string `json:"new_description"` + NewAttributes []setTemplateAttrInput `json:"new_attributes"` + GroupID *uuid.UUID `json:"group_id"` + CopyFirstSheetEmpty bool `json:"copy_first_sheet_empty"` + } + if c.BindJSON(&input) != nil { + return + } + + var orig Template + if db.First(&orig, "id = ?", input.TemplateID).Error != nil { + c.JSON(400, gin.H{"detail": "Template not found"}) + return + } + + // Update element IDs + newElements := updateElementIDs(orig.Elements) + + newT := Template{Name: input.NewName, Description: input.NewDescription, Elements: newElements, GroupID: input.GroupID} + db.Create(&newT) + + // Copy files + var files []File + db.Where("template_id = ?", input.TemplateID).Find(&files) + for _, f := range files { + newF := File{Name: f.Name, Content: f.Content, Cells: f.Cells, TemplateID: &newT.ID} + db.Create(&newF) + } + + // Copy sheets + var sheets []Sheet + db.Where("template_id = ?", input.TemplateID).Find(&sheets) + for _, s := range sheets { + cells := s.Cells + if s.Name == "L" && input.CopyFirstSheetEmpty { + cells = JSON("{}") + } + newS := Sheet{Name: s.Name, Cells: cells, TemplateID: newT.ID} + db.Create(&newS) + } + + // Copy or set attributes + if len(input.NewAttributes) > 0 { + for _, a := range input.NewAttributes { + db.Create(&TemplateAttribute{TemplateID: newT.ID, AttributeID: a.AttributeID, Value: a.Value}) + } + } else { + var origAttrs []TemplateAttribute + db.Where("template_id = ?", input.TemplateID).Find(&origAttrs) + for _, a := range origAttrs { + db.Create(&TemplateAttribute{TemplateID: newT.ID, AttributeID: a.AttributeID, Value: a.Value}) + } + } + + c.JSON(200, gin.H{"new_template_id": newT.ID}) +} + +func updateElementIDs(elements JSON) JSON { + var parsed map[string]interface{} + if json.Unmarshal(elements, &parsed) != nil || parsed == nil { + return elements + } + newElements := map[string]interface{}{} + for _, data := range parsed { + newID := uuid.New().String() + if m, ok := data.(map[string]interface{}); ok { + m["id"] = newID + } + newElements[newID] = data + } + result, _ := json.Marshal(newElements) + return JSON(result) +} + +// --- Files --- + +func getFiles(c *gin.Context, db *gorm.DB) { + var files []File + q := db.Model(&File{}) + if tid := c.Query("template_id"); tid != "" { + q = q.Where("template_id = ?", tid) + } + q.Find(&files) + c.JSON(200, gin.H{"files": files}) +} + +func getFile(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var f File + if db.First(&f, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"file": nil}) + return + } + c.JSON(200, gin.H{"file": f}) +} + +func uploadFile(c *gin.Context, db *gorm.DB) { + templateID, err := uuid.Parse(c.Query("template_id")) + if err != nil { + c.JSON(400, gin.H{"detail": "invalid template_id"}) + return + } + + fileHeader, err := c.FormFile("file") + if err != nil { + c.JSON(400, gin.H{"detail": "file required"}) + return + } + + f, _ := fileHeader.Open() + defer f.Close() + content, _ := io.ReadAll(f) + + cellsData, err := ReadCells(content) + if err != nil { + c.JSON(500, gin.H{"detail": fmt.Sprintf("failed to read cells: %v", err)}) + return + } + + cellsJSON, _ := json.Marshal(cellsData) + file := File{Name: fileHeader.Filename, Content: content, Cells: JSON(cellsJSON), TemplateID: &templateID} + db.Create(&file) + + c.JSON(200, gin.H{"file_id": file.ID, "cells": cellsData}) +} + +// --- Sheets --- + +func getSheets(c *gin.Context, db *gorm.DB) { + var sheets []Sheet + q := db.Model(&Sheet{}) + if tid := c.Query("template_id"); tid != "" { + q = q.Where("template_id = ?", tid) + } + q.Find(&sheets) + c.JSON(200, gin.H{"sheets": sheets}) +} + +func getSheet(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var s Sheet + if db.First(&s, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"sheet": nil}) + return + } + c.JSON(200, gin.H{"sheet": s}) +} + +func createSheet(c *gin.Context, db *gorm.DB) { + var input struct { + Name string `json:"name"` + Cells json.RawMessage `json:"cells"` + TemplateID uuid.UUID `json:"template_id"` + } + if c.BindJSON(&input) != nil { + return + } + s := Sheet{Name: input.Name, Cells: JSON(input.Cells), TemplateID: input.TemplateID} + db.Create(&s) + c.JSON(200, gin.H{"id": s.ID}) +} + +func patchSheet(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var s Sheet + if db.First(&s, "id = ?", id).Error != nil { + c.JSON(404, gin.H{"detail": "Sheet not found"}) + return + } + var input struct { + Name *string `json:"name"` + Cells *json.RawMessage `json:"cells"` + } + if c.BindJSON(&input) != nil { + return + } + updates := map[string]interface{}{} + if input.Name != nil { + updates["name"] = *input.Name + } + if input.Cells != nil { + updates["cells"] = JSON(*input.Cells) + } + if len(updates) > 0 { + db.Model(&s).Updates(updates) + } + c.JSON(200, gin.H{"id": s.ID}) +} + +// --- Attributes --- + +func getAttributes(c *gin.Context, db *gorm.DB) { + var attrs []Attribute + db.Find(&attrs) + c.JSON(200, gin.H{"attributes": attrs}) +} + +func createAttribute(c *gin.Context, db *gorm.DB) { + var input struct { + Name string `json:"name"` + IsRequired bool `json:"is_required"` + } + if c.BindJSON(&input) != nil { + return + } + var existing Attribute + if db.Where("name = ?", input.Name).First(&existing).Error == nil { + c.JSON(400, gin.H{"detail": fmt.Sprintf("Атрибут с именем '%s' уже существует", input.Name)}) + return + } + a := Attribute{Name: input.Name, IsRequired: input.IsRequired} + db.Create(&a) + c.JSON(200, gin.H{"id": a.ID}) +} + +func getAttributeValues(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var attr Attribute + if db.First(&attr, "id = ?", id).Error != nil { + c.JSON(404, gin.H{"detail": "Attribute not found"}) + return + } + + type valCount struct { + Value string `json:"value"` + UsageCount int `json:"usage_count"` + } + var values []valCount + db.Model(&TemplateAttribute{}). + Select("value, count(template_id) as usage_count"). + Where("attribute_id = ? AND value IS NOT NULL", id). + Group("value"). + Order("usage_count DESC"). + Find(&values) + + c.JSON(200, gin.H{ + "attribute_id": attr.ID, + "attribute_name": attr.Name, + "values": values, + "total_count": len(values), + }) +} + +// --- Standards --- + +func getStandards(c *gin.Context, db *gorm.DB) { + var standards []Standard + db.Find(&standards) + c.JSON(200, gin.H{"standards": standards}) +} + +func getStandard(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var s Standard + if db.First(&s, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"standard": nil}) + return + } + c.JSON(200, gin.H{"standard": s}) +} + +func createStandard(c *gin.Context, db *gorm.DB) { + var input struct { + Name string `json:"name"` + ProtocolName string `json:"protocol_name"` + RegistryNumber string `json:"registry_number"` + Range string `json:"range"` + Accuracy string `json:"accuracy"` + ValidUntil string `json:"valid_until"` + } + if c.BindJSON(&input) != nil { + return + } + validUntil, _ := time.Parse("2006-01-02", input.ValidUntil) + s := Standard{ + Name: input.Name, ProtocolName: input.ProtocolName, RegistryNumber: input.RegistryNumber, + Range: input.Range, Accuracy: input.Accuracy, ValidUntil: validUntil, + } + db.Create(&s) + c.JSON(200, gin.H{"id": s.ID}) +} + +func patchStandard(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var s Standard + if db.First(&s, "id = ?", id).Error != nil { + c.JSON(404, gin.H{"detail": "Standard not found"}) + return + } + var raw map[string]interface{} + if c.BindJSON(&raw) != nil { + return + } + db.Model(&s).Updates(raw) + c.JSON(200, gin.H{"id": s.ID}) +} + +func deleteStandard(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + res := db.Delete(&Standard{}, "id = ?", id) + if res.RowsAffected == 0 { + c.JSON(404, gin.H{"detail": "Standard not found"}) + return + } + c.JSON(200, gin.H{"message": "Standard deleted successfully"}) +} + +// --- Laboratories --- + +func getLaboratories(c *gin.Context, db *gorm.DB) { + var labs []Laboratory + db.Preload("ConditionTypes").Find(&labs) + c.JSON(200, gin.H{"laboratories": labs}) +} + +func getLaboratory(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var lab Laboratory + if db.Preload("ConditionTypes").First(&lab, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"laboratory": nil}) + return + } + c.JSON(200, gin.H{"laboratory": lab}) +} + +// --- Daily Conditions --- + +func getDailyConditions(c *gin.Context, db *gorm.DB) { + q := db.Model(&DailyCondition{}) + if lid := c.Query("laboratory_id"); lid != "" { + q = q.Where("laboratory_id = ?", lid) + } + if sd := c.Query("start_date"); sd != "" { + q = q.Where("measurement_date >= ?", sd) + } + if ed := c.Query("end_date"); ed != "" { + q = q.Where("measurement_date <= ?", ed) + } + var dcs []DailyCondition + q.Find(&dcs) + c.JSON(200, gin.H{"daily_conditions": dcs}) +} + +func getDailyCondition(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var dc DailyCondition + if db.First(&dc, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"daily_condition": nil}) + return + } + c.JSON(200, gin.H{"daily_condition": dc}) +} + +func createDailyCondition(c *gin.Context, db *gorm.DB) { + var input struct { + LaboratoryID uuid.UUID `json:"laboratory_id"` + MeasurementDate string `json:"measurement_date"` + Conditions json.RawMessage `json:"conditions"` + } + if c.BindJSON(&input) != nil { + return + } + var lab Laboratory + if db.First(&lab, "id = ?", input.LaboratoryID).Error != nil { + c.JSON(404, gin.H{"detail": "Laboratory not found"}) + return + } + md, _ := time.Parse("2006-01-02", input.MeasurementDate) + dc := DailyCondition{LaboratoryID: input.LaboratoryID, MeasurementDate: md, Conditions: JSON(input.Conditions)} + db.Create(&dc) + c.JSON(200, gin.H{"id": dc.ID}) +} + +func updateDailyCondition(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var dc DailyCondition + if db.First(&dc, "id = ?", id).Error != nil { + c.JSON(404, gin.H{"detail": "Daily condition not found"}) + return + } + var raw map[string]interface{} + if c.BindJSON(&raw) != nil { + return + } + db.Model(&dc).Updates(raw) + c.JSON(200, gin.H{"id": dc.ID}) +} + +func deleteDailyCondition(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + res := db.Delete(&DailyCondition{}, "id = ?", id) + if res.RowsAffected == 0 { + c.JSON(404, gin.H{"detail": "Daily condition not found"}) + return + } + c.JSON(200, gin.H{"message": "Daily condition deleted successfully"}) +} + +// --- Groups --- + +func getGroups(c *gin.Context, db *gorm.DB) { + var groups []Group + db.Order("\"order\", name").Find(&groups) + c.JSON(200, gin.H{"groups": groups}) +} + +func getGroup(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var g Group + if db.First(&g, "id = ?", id).Error != nil { + c.JSON(200, gin.H{"group": nil}) + return + } + c.JSON(200, gin.H{"group": g}) +} + +func createGroup(c *gin.Context, db *gorm.DB) { + var input struct { + Name string `json:"name"` + Order float64 `json:"order"` + IsVisible *bool `json:"is_visible"` + } + if c.BindJSON(&input) != nil { + return + } + isVisible := true + if input.IsVisible != nil { + isVisible = *input.IsVisible + } + g := Group{Name: input.Name, Order: input.Order, IsVisible: isVisible} + db.Create(&g) + c.JSON(200, gin.H{"id": g.ID}) +} + +func patchGroup(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + var g Group + if db.First(&g, "id = ?", id).Error != nil { + c.JSON(404, gin.H{"detail": "Group not found"}) + return + } + var raw map[string]interface{} + if c.BindJSON(&raw) != nil { + return + } + db.Model(&g).Updates(raw) + db.First(&g, "id = ?", id) // reload + c.JSON(200, g) +} + +func deleteGroup(c *gin.Context, db *gorm.DB) { + id, ok := parseUUID(c, "id") + if !ok { + return + } + res := db.Delete(&Group{}, "id = ?", id) + c.JSON(200, gin.H{"success": res.RowsAffected > 0}) +} + +// --- Protocols --- + +func createProtocol(c *gin.Context, db *gorm.DB) { + var input struct { + TemplateID uuid.UUID `json:"template_id"` + FileID uuid.UUID `json:"file_id"` + CellsToUpdate map[string]interface{} `json:"cells_to_update"` + PrintArea string `json:"print_area"` + } + if c.BindJSON(&input) != nil { + return + } + + var file File + if db.First(&file, "id = ?", input.FileID).Error != nil { + c.JSON(404, gin.H{"detail": "File not found"}) + return + } + + modified, err := FillCells(input.CellsToUpdate, file.Content, input.PrintArea) + if err != nil { + c.JSON(500, gin.H{"detail": fmt.Sprintf("Excel error: %v", err)}) + return + } + + protocolID := uuid.New() + c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=protocol_%s.xlsx", protocolID)) + c.Data(200, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", modified) +} diff --git a/backend/main.go b/backend/main.go new file mode 100644 index 0000000..8ad5973 --- /dev/null +++ b/backend/main.go @@ -0,0 +1,121 @@ +package main + +import ( + "embed" + "flag" + "fmt" + "io/fs" + "log" + "net/http" + "strings" + + "github.com/gin-gonic/gin" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +//go:embed dist/* +var distFS embed.FS + +func main() { + port := flag.Int("port", 1111, "port to listen on") + flag.Parse() + + dsn := "host=localhost user=user password=pass dbname=app port=5432 sslmode=disable" + + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) + if err != nil { + log.Fatalf("failed to connect to database: %v", err) + } + + db.AutoMigrate( + &Template{}, &File{}, &Sheet{}, &Attribute{}, &TemplateAttribute{}, + &Standard{}, &Group{}, &Laboratory{}, &ConditionType{}, &DailyCondition{}, + ) + + r := gin.Default() + + // API routes under /api/ + api := r.Group("/api") + registerRoutesOnGroup(api, db) + + // SPA: embedded frontend + distSub, err := fs.Sub(distFS, "dist") + if err != nil { + log.Fatalf("failed to open embedded dist: %v", err) + } + fileServer := http.FileServer(http.FS(distSub)) + + r.NoRoute(func(c *gin.Context) { + c.Header("Cache-Control", "no-store") + + path := strings.TrimPrefix(c.Request.URL.Path, "/") + if path == "" { + path = "index.html" + } + + // Serve static file if exists + if f, err := distSub.Open(path); err == nil { + f.Close() + fileServer.ServeHTTP(c.Writer, c.Request) + return + } + + // SPA fallback + indexFile, err := fs.ReadFile(distSub, "index.html") + if err != nil { + c.String(500, "index.html not found") + return + } + c.Data(200, "text/html; charset=utf-8", indexFile) + }) + + addr := fmt.Sprintf(":%d", *port) + log.Printf("Serving on http://localhost%s", addr) + r.Run(addr) +} + +func registerRoutesOnGroup(api *gin.RouterGroup, db *gorm.DB) { + api.GET("/templates/", func(c *gin.Context) { getTemplates(c, db) }) + api.GET("/templates/:id", func(c *gin.Context) { getTemplate(c, db) }) + api.POST("/templates/", func(c *gin.Context) { createTemplate(c, db) }) + api.PATCH("/templates/:id", func(c *gin.Context) { patchTemplate(c, db) }) + api.DELETE("/templates/:id", func(c *gin.Context) { deleteTemplate(c, db) }) + api.POST("/templates/copy", func(c *gin.Context) { copyTemplate(c, db) }) + + api.GET("/files/", func(c *gin.Context) { getFiles(c, db) }) + api.GET("/files/:id", func(c *gin.Context) { getFile(c, db) }) + api.POST("/files/upload", func(c *gin.Context) { uploadFile(c, db) }) + + api.GET("/sheets/", func(c *gin.Context) { getSheets(c, db) }) + api.GET("/sheets/:id", func(c *gin.Context) { getSheet(c, db) }) + api.POST("/sheets/", func(c *gin.Context) { createSheet(c, db) }) + api.PATCH("/sheets/:id", func(c *gin.Context) { patchSheet(c, db) }) + + api.GET("/attributes/", func(c *gin.Context) { getAttributes(c, db) }) + api.POST("/attributes/", func(c *gin.Context) { createAttribute(c, db) }) + api.GET("/attributes/:id/values", func(c *gin.Context) { getAttributeValues(c, db) }) + + api.GET("/standards/", func(c *gin.Context) { getStandards(c, db) }) + api.GET("/standards/:id", func(c *gin.Context) { getStandard(c, db) }) + api.POST("/standards/", func(c *gin.Context) { createStandard(c, db) }) + api.PATCH("/standards/:id", func(c *gin.Context) { patchStandard(c, db) }) + api.DELETE("/standards/:id", func(c *gin.Context) { deleteStandard(c, db) }) + + api.GET("/laboratories/", func(c *gin.Context) { getLaboratories(c, db) }) + api.GET("/laboratories/:id", func(c *gin.Context) { getLaboratory(c, db) }) + + api.GET("/daily-conditions/", func(c *gin.Context) { getDailyConditions(c, db) }) + api.GET("/daily-conditions/:id", func(c *gin.Context) { getDailyCondition(c, db) }) + api.POST("/daily-conditions/", func(c *gin.Context) { createDailyCondition(c, db) }) + api.PATCH("/daily-conditions/:id", func(c *gin.Context) { updateDailyCondition(c, db) }) + api.DELETE("/daily-conditions/:id", func(c *gin.Context) { deleteDailyCondition(c, db) }) + + api.GET("/groups/", func(c *gin.Context) { getGroups(c, db) }) + api.GET("/groups/:id", func(c *gin.Context) { getGroup(c, db) }) + api.POST("/groups/", func(c *gin.Context) { createGroup(c, db) }) + api.PATCH("/groups/:id", func(c *gin.Context) { patchGroup(c, db) }) + api.DELETE("/groups/:id", func(c *gin.Context) { deleteGroup(c, db) }) + + api.POST("/protocols/", func(c *gin.Context) { createProtocol(c, db) }) +} diff --git a/backend/model.go b/backend/model.go new file mode 100644 index 0000000..79b2f04 --- /dev/null +++ b/backend/model.go @@ -0,0 +1,158 @@ +package main + +import ( + "database/sql/driver" + "encoding/json" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" +) + +// JSON is a generic JSON column type for GORM. +type JSON json.RawMessage + +func (j JSON) Value() (driver.Value, error) { + if len(j) == 0 { + return nil, nil + } + return []byte(j), nil +} + +func (j *JSON) Scan(value interface{}) error { + if value == nil { + *j = JSON("null") + return nil + } + switch v := value.(type) { + case []byte: + *j = JSON(v) + case string: + *j = JSON(v) + } + return nil +} + +func (j JSON) MarshalJSON() ([]byte, error) { + if len(j) == 0 { + return []byte("null"), nil + } + return []byte(j), nil +} + +func (j *JSON) UnmarshalJSON(data []byte) error { + *j = JSON(data) + return nil +} + +func (JSON) GormDataType() string { return "jsonb" } + +// Base fields shared by all models. +type Base struct { + ID uuid.UUID `gorm:"type:uuid;primaryKey;default:gen_random_uuid()" json:"id"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` + DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at"` +} + +type Template struct { + Base + Name string `json:"name"` + Description *string `json:"description"` + Elements JSON `gorm:"type:jsonb" json:"elements"` + Order float64 `gorm:"default:0" json:"order"` + GroupID *uuid.UUID `gorm:"type:uuid" json:"group_id"` + + Group *Group `gorm:"foreignKey:GroupID" json:"group,omitempty"` + Files []File `gorm:"foreignKey:TemplateID;constraint:OnDelete:CASCADE" json:"files,omitempty"` + Sheets []Sheet `gorm:"foreignKey:TemplateID;constraint:OnDelete:CASCADE" json:"sheets,omitempty"` + TemplateAttributes []TemplateAttribute `gorm:"foreignKey:TemplateID;constraint:OnDelete:CASCADE" json:"template_attributes,omitempty"` +} + +type File struct { + Base + Name string `json:"name"` + Content []byte `gorm:"type:bytea" json:"-"` + Cells JSON `gorm:"type:jsonb" json:"cells"` + TemplateID *uuid.UUID `gorm:"type:uuid" json:"template_id"` + + Template *Template `gorm:"foreignKey:TemplateID" json:"template,omitempty"` +} + +type Sheet struct { + Base + Name string `json:"name"` + Cells JSON `gorm:"type:jsonb" json:"cells"` + TemplateID uuid.UUID `gorm:"type:uuid" json:"template_id"` + + Template *Template `gorm:"foreignKey:TemplateID" json:"template,omitempty"` +} + +type Attribute struct { + Base + Name string `json:"name"` + IsRequired bool `json:"is_required"` + + TemplateAttributes []TemplateAttribute `gorm:"foreignKey:AttributeID" json:"template_attributes,omitempty"` +} + +type TemplateAttribute struct { + TemplateID uuid.UUID `gorm:"type:uuid;primaryKey" json:"template_id"` + AttributeID uuid.UUID `gorm:"type:uuid;primaryKey" json:"attribute_id"` + Value *string `json:"value"` + CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"` + UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"` + + Template *Template `gorm:"foreignKey:TemplateID" json:"template,omitempty"` + Attribute *Attribute `gorm:"foreignKey:AttributeID" json:"attribute,omitempty"` +} + +type Standard struct { + Base + Name string `json:"name"` + ProtocolName string `json:"protocol_name"` + RegistryNumber string `json:"registry_number"` + Range string `json:"range"` + Accuracy string `json:"accuracy"` + ValidUntil time.Time `gorm:"type:date" json:"valid_until"` +} + +type Group struct { + Base + Name string `json:"name"` + Order float64 `gorm:"default:0" json:"order"` + IsVisible bool `gorm:"default:true" json:"is_visible"` + + Templates []Template `gorm:"foreignKey:GroupID" json:"templates,omitempty"` +} + +type Laboratory struct { + Base + Name string `json:"name"` + + ConditionTypes []ConditionType `gorm:"many2many:laboratory_condition_type" json:"condition_types"` + DailyConditions []DailyCondition `gorm:"foreignKey:LaboratoryID;constraint:OnDelete:CASCADE" json:"daily_conditions,omitempty"` +} + +func (Laboratory) TableName() string { return "laboratorys" } + +type ConditionType struct { + Base + Name string `json:"name"` + Unit string `json:"unit"` + + Laboratories []Laboratory `gorm:"many2many:laboratory_condition_type" json:"laboratories,omitempty"` +} + +func (ConditionType) TableName() string { return "conditiontypes" } + +type DailyCondition struct { + Base + LaboratoryID uuid.UUID `gorm:"type:uuid" json:"laboratory_id"` + MeasurementDate time.Time `gorm:"type:date" json:"measurement_date"` + Conditions JSON `gorm:"type:jsonb" json:"conditions"` + + Laboratory *Laboratory `gorm:"foreignKey:LaboratoryID" json:"laboratory,omitempty"` +} + +func (DailyCondition) TableName() string { return "daily_conditions" }