diff --git a/configs/config.json b/configs/config.json index 9de5c16e..283a9b41 100644 --- a/configs/config.json +++ b/configs/config.json @@ -17,7 +17,12 @@ "token1": "token1", "token2": "token2", "token3": "token3" - } + }, + "timezone": "Asia/Tokyo" + }, + "stripe": { + "webhook_secret_key": "", + "secret_key": "" }, "db": { "ip": "127.0.0.1", diff --git a/go.mod b/go.mod index 61496811..9a3275b5 100644 --- a/go.mod +++ b/go.mod @@ -4,14 +4,17 @@ go 1.13 require ( github.com/ashwanthkumar/slack-go-webhook v0.0.0-20200209025033-430dd4e66960 + github.com/elazarl/goproxy v0.0.0-20210110162100-a92cc753f88e // indirect github.com/gin-gonic/gin v1.6.3 github.com/google/uuid v1.2.0 github.com/gorilla/websocket v1.4.2 - github.com/jinzhu/gorm v1.9.16 github.com/mitchellh/go-homedir v1.1.0 github.com/parnurzeal/gorequest v0.2.16 // indirect github.com/spf13/cobra v1.1.3 github.com/spf13/viper v1.7.1 + github.com/stripe/stripe-go/v72 v72.50.0 golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b + gorm.io/driver/mysql v1.1.1 + gorm.io/gorm v1.21.11 moul.io/http2curl v1.0.0 // indirect ) diff --git a/go.sum b/go.sum index dacbef3c..af4494ca 100644 --- a/go.sum +++ b/go.sum @@ -15,10 +15,8 @@ github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/PuerkitoBio/goquery v1.5.1/go.mod h1:GsLWisAFVj4WgDibEWF4pvYnkVQBpKBKeU+7zCJoLcc= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/andybalholm/cascadia v1.1.0/go.mod h1:GsXiBklL0woXo1j/WYWtSYYC4ouU9PqHO0sqidkEA4Y= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= @@ -28,7 +26,6 @@ github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24 github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= -github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= @@ -40,23 +37,15 @@ github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsr 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/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM= -github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/elazarl/goproxy v0.0.0-20201021153353-00ad82a08272 h1:Am81SElhR3XCQBunTisljzNkNese2T1FiV8jP79+dqg= -github.com/elazarl/goproxy v0.0.0-20201021153353-00ad82a08272/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM= +github.com/elazarl/goproxy v0.0.0-20210110162100-a92cc753f88e h1:/cwV7t2xezilMljIftb7WlFtzGANRCnoOhPjtl2ifcs= +github.com/elazarl/goproxy v0.0.0-20210110162100-a92cc753f88e/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM= github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 h1:dWB6v3RcOy03t/bUadywsbyrQwCqZeNIEX6M1OtSZOM= github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8= -github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= -github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y= -github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= -github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= -github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= @@ -74,15 +63,11 @@ github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD87 github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1Vv0sFl1UcHBOY= github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= -github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= -github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= -github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= @@ -93,29 +78,15 @@ github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3 h1:gyjaxf+svBWX08ZjK86iN9geUJF0H6gp2IRKX6Nf6/I= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= -github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= -github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= -github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= -github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= -github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= -github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/uuid v1.1.2 h1:EVhdT+1Kseyi1/pUmXKaFxYsDNy9RQYkMWRH68J/W7Y= -github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs= github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= @@ -150,18 +121,14 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/jinzhu/gorm v1.9.16 h1:+IyIjPEABKRpsu/F8OvDPy9fyQlgsg2luMV2ZIH5i5o= -github.com/jinzhu/gorm v1.9.16/go.mod h1:G3LB3wezTOWM2ITLzPxEXgSkOXAntiLHS7UdBefADcs= 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.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M= -github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI= +github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.10 h1:Kz6Cvnvv2wGdaG/V8yMvfkmNiXq9Ya2KUv4rouJJr68= -github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= @@ -169,7 +136,6 @@ github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7V github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -178,20 +144,12 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/leodido/go-urn v1.2.0 h1:hpXL4XnriNwQ/ABnpepYM/1vCLWNDfUNts8dX3xTG6Y= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= -github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= -github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4= -github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/magiconair/properties v1.8.4 h1:8KGKTcQQGm0Kv7vEbKFErAoAOFyyacLStRtQSeYtvkY= -github.com/magiconair/properties v1.8.4/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY= github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/QA= -github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= @@ -204,8 +162,6 @@ github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0Qu github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= -github.com/mitchellh/mapstructure v1.4.0 h1:7ks8ZkOP5/ujthUsT07rNv+nkLXCQWKNHuwzOAesEks= -github.com/mitchellh/mapstructure v1.4.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= 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= @@ -219,14 +175,9 @@ github.com/parnurzeal/gorequest v0.2.16/go.mod h1:3Kh2QUMJoqw3icWAecsyzkpY7UzRfD github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.8.1 h1:1Nf83orprkJyknT6h7zbuEGUEjcyVlCxSUGTENmNCRM= -github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= 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/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= @@ -234,7 +185,6 @@ github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXP github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro= github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= @@ -256,20 +206,12 @@ github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4k github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.5.1 h1:VHu76Lk0LSP1x254maIu2bplkWpfBWI+B+6fdoZprcg= -github.com/spf13/afero v1.5.1/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= -github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= -github.com/spf13/cobra v1.1.1 h1:KfztREH0tPxJJ+geloSLaAkaPkr4ki2Er5quFV1TDo4= -github.com/spf13/cobra v1.1.1/go.mod h1:WnodtKOvamDL/PwE2M4iKs8aMDBZ5Q5klgD3qfVJQMI= github.com/spf13/cobra v1.1.3 h1:xghbfqPkxzxP3C/f3n5DdpAbdKLj4ZE4BWQI362l53M= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= -github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= -github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= @@ -282,19 +224,17 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stripe/stripe-go/v72 v72.50.0 h1:oy+EsSKMrFS3zzayb8Ic+2LZ04Ux0vJ4990/7psaYsc= +github.com/stripe/stripe-go/v72 v72.50.0/go.mod h1:QwqJQtduHubZht9mek5sds9CtQcKFdsykV9ZepRWwo0= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo= github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go v1.2.2 h1:60ZHIOcsJlo3bJm9CbTVu7OSqT2mxaEmyQbK2NwCkn0= -github.com/ugorji/go v1.2.2/go.mod h1:bitgyERdV7L7Db/Z5gfd5v2NQMNhhiFiZwpgMw2SP7k= github.com/ugorji/go/codec v1.1.7 h1:2SvQaVZ1ouYrrKKwoSk2pzd4A9evlKJb9oTL+OaLUSs= github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/ugorji/go/codec v1.2.2 h1:08Gah8d+dXj4cZNUHhtuD/S4PXD5WpVbj5B8/ClELAQ= -github.com/ugorji/go/codec v1.2.2/go.mod h1:OM8g7OAy52uYl3Yk+RE/3AS1nXFn1Wh4PPLtupCxbuU= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= @@ -305,15 +245,8 @@ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad h1:DN0cp81fZ3njFcrLCytUHRSUkqBjfTo4Tx9RJTWs0EY= -golang.org/x/crypto v0.0.0-20201221181555-eec23a3978ad/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b h1:wSOdpTq0/eI46Ez/LkDwIsAKA71YP2SRKBODiRWM0as= golang.org/x/crypto v0.0.0-20210314154223-e6e6c4f2bb5b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -334,7 +267,6 @@ golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= -golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -349,11 +281,8 @@ golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b h1:iFwSg7t5GZmB/Q5TjiEAsdoLDrdJRC1RiF2WhuV29Qw= -golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 h1:qWPm9rbaAMKs8Bq/9LRpbMqxWRVUAQwMI9fVrssnTfw= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= @@ -377,16 +306,11 @@ golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68 h1:nxC68pudNYkKU6jWhgrqdreuFiOQWj1Fs7T3VrH4Pjw= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201223074533-0d417f636930 h1:vRgIt+nup/B/BwIS0g2oC0haq0iqbV3ZA+u6+0TlNCo= -golang.org/x/sys v0.0.0-20201223074533-0d417f636930/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -394,8 +318,6 @@ golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc= -golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= @@ -408,7 +330,6 @@ golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= -golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= @@ -417,8 +338,6 @@ golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtn golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= @@ -437,23 +356,9 @@ google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= -google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= -google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= -google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= -google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= -google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= -google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= @@ -461,8 +366,6 @@ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8 gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= -gopkg.in/ini.v1 v1.62.0 h1:duBzk771uxoUuOlyRLkHsygud9+5lrlGjdFBb4mSKDU= -gopkg.in/ini.v1 v1.62.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -472,15 +375,15 @@ gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/mysql v1.1.1 h1:yr1bpyqiwuSPJ4aGGUX9nu46RHXlF8RASQVb1QQNcvo= +gorm.io/driver/mysql v1.1.1/go.mod h1:KdrTanmfLPPyAOeYGyG+UpDys7/7eeWT1zCq+oekYnU= +gorm.io/gorm v1.21.9/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0= +gorm.io/gorm v1.21.11 h1:CxkXW6Cc+VIBlL8yJEHq+Co4RYXdSLiMKNvgoZPjLK4= +gorm.io/gorm v1.21.11/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -layeh.com/radius v0.0.0-20200828214147-d62a6e0a1819 h1:NPb3gcdAxZyKXq/BzbwzjTvwTof083G6dpIFoc/Lifc= -layeh.com/radius v0.0.0-20200828214147-d62a6e0a1819/go.mod h1:pFWM9De99EY9TPVyHIyA56QmoRViVck/x41WFkUlc9A= moul.io/http2curl v1.0.0 h1:6XwpyZOYsgZJrU8exnG87ncVkU1FVCcTRpwzOkTDUi8= moul.io/http2curl v1.0.0/go.mod h1:f6cULg+e4Md/oW1cYmwW4IWQOVl2lGbmCNGOHvzX2kE= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/pkg/api/api.go b/pkg/api/api.go index ac0d1cf7..e54c23f6 100644 --- a/pkg/api/api.go +++ b/pkg/api/api.go @@ -5,7 +5,7 @@ import ( controller "github.com/homenoc/dsbd-backend/pkg/api/core/controller/v0" connection "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection/v0" info "github.com/homenoc/dsbd-backend/pkg/api/core/group/info/v0" - ip "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/ip/v0" + memo "github.com/homenoc/dsbd-backend/pkg/api/core/group/memo/v0" service "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/v0" group "github.com/homenoc/dsbd-backend/pkg/api/core/group/v0" mail "github.com/homenoc/dsbd-backend/pkg/api/core/mail/v0" @@ -14,7 +14,7 @@ import ( tunnelEndPointRouterIP "github.com/homenoc/dsbd-backend/pkg/api/core/noc/tunnelEndPointRouterIP/v0" noc "github.com/homenoc/dsbd-backend/pkg/api/core/noc/v0" notice "github.com/homenoc/dsbd-backend/pkg/api/core/notice/v0" - chat "github.com/homenoc/dsbd-backend/pkg/api/core/support/chat/v0" + payment "github.com/homenoc/dsbd-backend/pkg/api/core/payment/v0" ticket "github.com/homenoc/dsbd-backend/pkg/api/core/support/ticket/v0" template "github.com/homenoc/dsbd-backend/pkg/api/core/template/v0" token "github.com/homenoc/dsbd-backend/pkg/api/core/token/v0" @@ -37,154 +37,178 @@ func AdminRestAPI() { { // Controller //noc - v1.POST("/controller/chat", controller.ReceiveChatAdmin) + v1.POST("/controller/chat", controller.ReceiveChatByAdmin) // Notice // - v1.POST("/notice", notice.AddAdmin) - v1.DELETE("/notice/:id", notice.DeleteAdmin) - v1.GET("/notice", notice.GetAllAdmin) - v1.GET("/notice/:id", notice.GetAdmin) - v1.PUT("/notice/:id", notice.UpdateAdmin) + v1.POST("/notice", notice.AddByAdmin) + v1.DELETE("/notice/:id", notice.DeleteByAdmin) + v1.GET("/notice", notice.GetAllByAdmin) + v1.GET("/notice/:id", notice.GetByAdmin) + v1.PUT("/notice/:id", notice.UpdateByAdmin) // // User // // User Create - v1.POST("/user", user.AddAdmin) + v1.POST("/user", user.AddByAdmin) // User Delete - v1.DELETE("/user", user.DeleteAdmin) + v1.DELETE("/user", user.DeleteByAdmin) // User Update - v1.PUT("/user/:id", user.UpdateAdmin) - v1.GET("/user", user.GetAllAdmin) - v1.GET("/user/:id", user.GetAdmin) + v1.PUT("/user/:id", user.UpdateByAdmin) + v1.GET("/user", user.GetAllByAdmin) + v1.GET("/user/:id", user.GetByAdmin) + // + // Login / Logout + // + v1.POST("/login", token.GenerateByAdmin) + v1.POST("/logout", token.DeleteAdminUser) + // // Token // - v1.POST("/token/generate", token.GenerateAdmin) + v1.POST("/token/generate", token.GenerateByAdmin) - v1.POST("/token", token.AddAdmin) + v1.POST("/token", token.AddByAdmin) // Token Delete - v1.DELETE("/token", token.DeleteAllAdmin) - v1.DELETE("/token/:id", token.DeleteAdmin) + v1.DELETE("/token", token.DeleteAllByAdmin) + v1.DELETE("/token/:id", token.DeleteByAdmin) // Token Update - v1.PUT("/token/:id", token.UpdateAdmin) - v1.GET("/token", token.GetAllAdmin) - v1.GET("/token/:id", token.GetAdmin) + v1.PUT("/token/:id", token.UpdateByAdmin) + v1.GET("/token", token.GetAllByAdmin) + v1.GET("/token/:id", token.GetByAdmin) // // Group // - v1.POST("/group", group.AddAdmin) + v1.POST("/group", group.AddByAdmin) // Group Delete - v1.DELETE("/group", group.DeleteAdmin) + v1.DELETE("/group", group.DeleteByAdmin) // Group Update - v1.PUT("/group/:id", group.UpdateAdmin) - v1.GET("/group", group.GetAllAdmin) - v1.GET("/group/:id", group.GetAdmin) + v1.PUT("/group/:id", group.UpdateByAdmin) + v1.DELETE("/group/:id/subscription", group.CancelSubscription) + v1.GET("/group", group.GetAllByAdmin) + v1.GET("/group/:id", group.GetByAdmin) + + // + // Memo + // + v1.POST("/memo", memo.AddByAdmin) + v1.DELETE("/memo/:id", memo.DeleteByAdmin) // Template - v1.GET("/template", template.GetAdmin) + v1.GET("/template", template.GetByAdmin) // // NOC // - v1.POST("/noc", noc.AddAdmin) - v1.GET("/noc", noc.GetAllAdmin) - v1.DELETE("/noc/:id", noc.DeleteAdmin) - v1.GET("/noc/:id", noc.GetAdmin) - v1.PUT("/noc/:id", noc.UpdateAdmin) + v1.POST("/noc", noc.AddByAdmin) + v1.GET("/noc", noc.GetAllByAdmin) + v1.DELETE("/noc/:id", noc.DeleteByAdmin) + v1.GET("/noc/:id", noc.GetByAdmin) + v1.PUT("/noc/:id", noc.UpdateByAdmin) // // NOC Router // - v1.POST("/router", bgpRouter.AddAdmin) - v1.GET("/router", bgpRouter.GetAllAdmin) - v1.DELETE("/router/:id", bgpRouter.DeleteAdmin) - v1.GET("/router/:id", bgpRouter.GetAdmin) - v1.PUT("/router/:id", bgpRouter.UpdateAdmin) + v1.POST("/router", bgpRouter.AddByAdmin) + v1.GET("/router", bgpRouter.GetAllByAdmin) + v1.DELETE("/router/:id", bgpRouter.DeleteByAdmin) + v1.GET("/router/:id", bgpRouter.GetByAdmin) + v1.PUT("/router/:id", bgpRouter.UpdateByAdmin) // // NOC Gateway // - v1.POST("/gateway", tunnelEndPointRouter.AddAdmin) - v1.GET("/gateway", tunnelEndPointRouter.GetAllAdmin) - v1.DELETE("/gateway/:id", tunnelEndPointRouter.DeleteAdmin) - v1.GET("/gateway/:id", tunnelEndPointRouter.GetAdmin) - v1.PUT("/gateway/:id", tunnelEndPointRouter.UpdateAdmin) + v1.POST("/gateway", tunnelEndPointRouter.AddByAdmin) + v1.GET("/gateway", tunnelEndPointRouter.GetAllByAdmin) + v1.DELETE("/gateway/:id", tunnelEndPointRouter.DeleteByAdmin) + v1.GET("/gateway/:id", tunnelEndPointRouter.GetByAdmin) + v1.PUT("/gateway/:id", tunnelEndPointRouter.UpdateByAdmin) // // NOC Gateway IP // - v1.POST("/gateway_ip", tunnelEndPointRouterIP.AddAdmin) - v1.GET("/gateway_ip", tunnelEndPointRouterIP.GetAllAdmin) - v1.DELETE("/gateway_ip/:id", tunnelEndPointRouterIP.DeleteAdmin) - v1.GET("/gateway_ip/:id", tunnelEndPointRouterIP.GetAdmin) - v1.PUT("/gateway_ip/:id", tunnelEndPointRouterIP.UpdateAdmin) + v1.POST("/gateway_ip", tunnelEndPointRouterIP.AddByAdmin) + v1.GET("/gateway_ip", tunnelEndPointRouterIP.GetAllByAdmin) + v1.DELETE("/gateway_ip/:id", tunnelEndPointRouterIP.DeleteByAdmin) + v1.GET("/gateway_ip/:id", tunnelEndPointRouterIP.GetByAdmin) + v1.PUT("/gateway_ip/:id", tunnelEndPointRouterIP.UpdateByAdmin) // // Support // - v1.POST("/support", ticket.CreateAdmin) - v1.GET("/support", ticket.GetAllAdmin) - //v1.POST("/support/:id", chat.AddAdmin) - v1.GET("/support/:id", ticket.GetAdmin) - v1.PUT("/support/:id", ticket.UpdateAdmin) + v1.POST("/support", ticket.CreateByAdmin) + v1.GET("/support", ticket.GetAllByAdmin) + //v1.POST("/support/:id", chat.AddByAdmin) + v1.GET("/support/:id", ticket.GetByAdmin) + v1.PUT("/support/:id", ticket.UpdateByAdmin) //// //// Connection //// - v1.POST("/group/:id/connection", connection.AddAdmin) + v1.POST("/service/:id/connection", connection.AddByAdmin) // Group Delete - v1.DELETE("/connection/:id", connection.DeleteAdmin) + v1.DELETE("/connection/:id", connection.DeleteByAdmin) // Group Update - v1.PUT("/connection/:id", connection.UpdateAdmin) - v1.GET("/connection", connection.GetAllAdmin) - v1.GET("/connection/:id", connection.GetAdmin) + v1.PUT("/connection/:id", connection.UpdateByAdmin) + v1.GET("/connection", connection.GetAllByAdmin) + v1.GET("/connection/:id", connection.GetByAdmin) // // Service // - v1.POST("/group/:id/service", service.AddAdmin) + v1.POST("/group/:id/service", service.AddByAdmin) // Service Delete - v1.DELETE("/service/:id", service.DeleteAdmin) + v1.DELETE("/service/:id", service.DeleteByAdmin) // Service Update - v1.PUT("/service/:id", service.UpdateAdmin) - v1.GET("/service", service.GetAllAdmin) - v1.GET("/service/:id", service.GetAdmin) + v1.PUT("/service/:id", service.UpdateByAdmin) + v1.GET("/service", service.GetAllByAdmin) + v1.GET("/service/:id", service.GetByAdmin) // - // JPNIC Admin + // Payment // - v1.POST("/service/:id/jpnic_admin", service.AddJPNICAdminAdmin) - v1.DELETE("/service/:id/jpnic_admin/:jpnic_id", service.DeleteJPNICAdminAdmin) - v1.PUT("/service/:id/jpnic_admin", service.UpdateJPNICAdminAdmin) + //v1.POST("/group/:id/service", service.AddByAdmin) + // Delete + v1.DELETE("/payment/:id", payment.DeleteByAdmin) + v1.POST("/payment/:id/refund", payment.RefundByAdmin) + // Update + //v1.PUT("/service/:id", service.UpdateByAdmin) + v1.GET("/payment", payment.GetAllByAdmin) + //v1.GET("/service/:id", service.GetByAdmin) // - // JPNIC Admin + // JPNIC ByAdmin // - v1.POST("/service/:id/jpnic_tech", service.AddJPNICTechAdmin) - v1.DELETE("/service/:id/jpnic_tech/:jpnic_id", service.DeleteJPNICTechAdmin) - v1.PUT("/service/:id/jpnic_tech/:jpnic_id", service.UpdateJPNICTechAdmin) + v1.POST("/service/:id/jpnic_ByAdmin", service.AddJPNICAdminByAdmin) + v1.DELETE("/jpnic_ByAdmin/:id", service.DeleteJPNICAdminByAdmin) + v1.PUT("/jpnic_ByAdmin/:id", service.UpdateJPNICAdminByAdmin) + + // + // JPNIC Tech + // + v1.POST("/service/:id/jpnic_tech", service.AddJPNICTechByAdmin) + v1.DELETE("/jpnic_tech/:id", service.DeleteJPNICTechByAdmin) + v1.PUT("/jpnic_tech/:id", service.UpdateJPNICTechByAdmin) // // IP // - v1.PUT("/service/:id/ip/:ip_id", service.UpdateIPAdmin) - v1.POST("/service/:id/ip", service.AddIPAdmin) - v1.DELETE("/service/:id/ip/:ip_id", service.DeleteIPAdmin) - v1.PUT("/ip/:id", ip.UpdateAdmin) + v1.POST("/service/:id/ip", service.AddIPByAdmin) + v1.DELETE("/ip/:id", service.DeleteIPByAdmin) + v1.PUT("/ip/:id", service.UpdateIPByAdmin) // // Plan // - v1.POST("/plan", service.AddPlanAdmin) - v1.DELETE("/plan/:id", service.DeletePlanAdmin) - v1.PUT("/plan/:id", service.UpdatePlanAdmin) + v1.POST("/ip/:id/plan", service.AddPlanByAdmin) + v1.DELETE("/plan/:id", service.DeletePlanByAdmin) + v1.PUT("/plan/:id", service.UpdatePlanByAdmin) // // Mail // - v1.POST("/mail", mail.SendAdmin) + v1.POST("/mail", mail.SendByAdmin) } } ws := router.Group("/ws") @@ -195,7 +219,7 @@ func AdminRestAPI() { } } - go ticket.HandleMessagesAdmin() + go ticket.HandleMessagesByAdmin() log.Fatal(http.ListenAndServe(":"+strconv.Itoa(config.Conf.Controller.Admin.Port), router)) } @@ -211,85 +235,75 @@ func UserRestAPI() { // v1.POST("/controller/chat", controller.ReceiveChatUser) + // Stripe + // + //v1.POST("/stripe", payment.GetStripeWebHook) + v1.Any("/stripe", payment.GetStripeWebHook) + + // User Mail MailVerify + v1.GET("/verify/:token", user.MailVerify) + + // + // Login / Logout + // + v1.POST("/login", token.Generate) + v1.GET("/login", token.GenerateInit) + v1.POST("/logout", token.Delete) + // // User // // User Create v1.POST("/user", user.Add) // User Create(Group) - v1.POST("/user/:id", user.AddGroup) - // User Delete - //router.DELETE("/user", user.Delete) - // User Get - v1.GET("/login", user.GetOwn) - v1.GET("/user/:id", user.Get) - v1.GET("/user", user.GetGroup) - // User ID Get + v1.POST("/group/:id/user", user.AddGroup) // User Update v1.PUT("/user/:id", user.Update) - // User Mail MailVerify - v1.GET("/verify/:token", user.MailVerify) // - // Token + // Info // - // get token for CHAP authentication - v1.GET("/token/init", token.GenerateInit) - // get token for user - v1.GET("/token", token.Generate) - // delete - v1.DELETE("/token", token.Delete) + v1.GET("/info", info.Get) + // // Group // // Group Create v1.POST("/group", group.Add) - v1.GET("/group", group.Get) - v1.PUT("/group", group.Update) - v1.GET("/group/all", group.GetAll) - // Group Delete - //v1.DELETE("/group", group.Delete) + + // Template + v1.GET("/template", template.Get) + // Service add - v1.POST("/group/service", service.Add) - v1.GET("/group/service/add_allow", service.GetAddAllow) + v1.POST("/service", service.Add) + v1.GET("/service/add_allow", service.GetAddAllow) //v1.PUT("/group/network", network.Update) // Connection Create - v1.POST("/group/service/:id/connection", connection.Add) + v1.POST("/service/:id/connection", connection.Add) // - // Info + // Payment // - v1.GET("/group/info", info.Get) - - // Template - v1.GET("/template", template.Get) - - // NOC - v1.GET("/noc", noc.GetAll) + v1.POST("/payment/membership", payment.MembershipPayment) + v1.POST("/payment/donate", payment.DonatePayment) + v1.PUT("/payment/card", payment.ChangeCardPayment) + v1.GET("/payment/card", payment.ChangeCardPaymentInit) // - // Support + // Support/Request // v1.POST("/support", ticket.Create) - v1.GET("/support", ticket.GetAll) - v1.POST("/support/:id", chat.Add) - v1.GET("/support/:id", ticket.Get) - // - // Notice - // - v1.GET("/notice", notice.Get) + v1.POST("/request", ticket.Request) + v1.PUT("/support/:id", ticket.Update) - // 現在検討中 + // User Delete + // User ID Get + + // Group Delete + //v1.DELETE("/group", group.Delete) - // Service JPNIC Admin - //v1.POST("/group/jpnic/admin", jpnicAdmin.Add) - //v1.DELETE("/group/jpnic/admin", jpnicAdmin.Delete) - //v1.GET("/group/network/jpnic/admin", jpnicAdmin.GetAll) - // Service JPNIC Tech - //v1.POST("/group/jpnic/tech", jpnicTech.Add) - //v1.DELETE("/group/jpnic/tech", jpnicTech.Delete) - //v1.GET("/group/service/jpnic/tech", jpnicTech.GetAll) + //v1.POST("/support/:id", chat.Add) } } diff --git a/pkg/api/core/admin/interface.go b/pkg/api/core/admin/interface.go index 99292ae1..d2a2bb02 100644 --- a/pkg/api/core/admin/interface.go +++ b/pkg/api/core/admin/interface.go @@ -1,7 +1,7 @@ package admin import ( - "github.com/jinzhu/gorm" + "gorm.io/gorm" ) const ( diff --git a/pkg/api/core/auth/v0/auth.go b/pkg/api/core/auth/v0/auth.go index 00f0572c..b22d0345 100644 --- a/pkg/api/core/auth/v0/auth.go +++ b/pkg/api/core/auth/v0/auth.go @@ -6,7 +6,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/auth" "github.com/homenoc/dsbd-backend/pkg/api/core/token" dbToken "github.com/homenoc/dsbd-backend/pkg/api/store/token/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -43,7 +43,7 @@ func GroupAuthentication(errorType uint, data core.Token) auth.GroupResult { return auth.GroupResult{Err: fmt.Errorf("deleted this user")} } - if resultToken.Token[0].User.GroupID == 0 { + if resultToken.Token[0].User.GroupID == nil { return auth.GroupResult{Err: fmt.Errorf("no group")} } diff --git a/pkg/api/core/controller/interface.go b/pkg/api/core/controller/interface.go index 504f80c3..b8d46124 100644 --- a/pkg/api/core/controller/interface.go +++ b/pkg/api/core/controller/interface.go @@ -11,6 +11,7 @@ type Chat struct { ID uint `json:"id"` Err string `json:"error"` CreatedAt time.Time `json:"created_at"` + TicketID uint `json:"ticket_id"` UserID uint `json:"user_id"` UserName string `json:"user_name"` GroupID uint `json:"group_id"` diff --git a/pkg/api/core/controller/v0/admin.go b/pkg/api/core/controller/v0/admin.go index 3078810a..3bd2a7ea 100644 --- a/pkg/api/core/controller/v0/admin.go +++ b/pkg/api/core/controller/v0/admin.go @@ -16,19 +16,11 @@ import ( "time" ) -func SendChatAdmin(data controller.Chat) { +func SendChatByAdmin(data controller.Chat) { client := &http.Client{} client.Timeout = time.Second * 5 - body, _ := json.Marshal(controller.Chat{ - Err: data.Err, - CreatedAt: data.CreatedAt, - UserID: data.UserID, - UserName: data.UserName, - GroupID: data.GroupID, - Admin: data.Admin, - Message: data.Message, - }) + body, _ := json.Marshal(data) //Header部分 header := http.Header{} @@ -60,12 +52,13 @@ func SendChatAdmin(data controller.Chat) { } } -func ReceiveChatAdmin(c *gin.Context) { +func ReceiveChatByAdmin(c *gin.Context) { token1 := c.Request.Header.Get("TOKEN_1") token2 := c.Request.Header.Get("TOKEN_2") if err := auth.ControllerAuthentication(controller.Controller{Token1: token1, Token2: token2}); err != nil { log.Println(err) + return } var input controller.Chat @@ -73,7 +66,9 @@ func ReceiveChatAdmin(c *gin.Context) { support.Broadcast <- support.WebSocketResult{ CreatedAt: time.Now(), + TicketID: input.TicketID, UserID: input.UserID, + UserName: input.UserName, GroupID: input.GroupID, Admin: input.Admin, Message: input.Message, diff --git a/pkg/api/core/controller/v0/user.go b/pkg/api/core/controller/v0/user.go index 0701c9f9..7466e898 100644 --- a/pkg/api/core/controller/v0/user.go +++ b/pkg/api/core/controller/v0/user.go @@ -20,8 +20,7 @@ func SendChatUser(data controller.Chat) { client := &http.Client{} client.Timeout = time.Second * 5 - body, _ := json.Marshal(controller.Chat{Err: data.Err, CreatedAt: data.CreatedAt, UserID: data.UserID, - GroupID: data.GroupID, Admin: data.Admin, Message: data.Message}) + body, _ := json.Marshal(data) //Header部分 header := http.Header{} @@ -72,6 +71,7 @@ func ReceiveChatUser(c *gin.Context) { support.Broadcast <- support.WebSocketResult{ CreatedAt: time.Now(), + TicketID: input.TicketID, UserID: input.UserID, GroupID: input.GroupID, Admin: input.Admin, diff --git a/pkg/api/core/group/connection/interface.go b/pkg/api/core/group/connection/interface.go index 2d0f612e..df8e128b 100644 --- a/pkg/api/core/group/connection/interface.go +++ b/pkg/api/core/group/connection/interface.go @@ -11,6 +11,7 @@ const ( Email = 3 ServiceID = 4 SearchNewNumber = 5 + NOCID = 6 UpdateID = 100 UpdateServiceID = 101 UpdateUserInfo = 102 @@ -21,13 +22,15 @@ const ( ) type Input struct { - ConnectionTemplateID *uint `json:"connection_template_id"` + ConnectionTemplateID uint `json:"connection_template_id"` ConnectionComment string `json:"connection_comment"` // ServiceがETCの時や補足説明で必要 - NTTTemplateID *uint `json:"ntt_template_id"` + NTTTemplateID uint `json:"ntt_template_id"` Address string `json:"address"` - NOCID *uint `json:"noc_id"` + IPv4RouteTemplateID uint `json:"ipv4_route_template_id"` + IPv6RouteTemplateID uint `json:"ipv6_route_template_id"` + NOCID uint `json:"noc_id"` TermIP string `json:"term_ip"` - Monitor *bool `json:"monitor"` + Monitor bool `json:"monitor"` } type Connection struct { diff --git a/pkg/api/core/group/connection/v0/admin.go b/pkg/api/core/group/connection/v0/admin.go index f2fdb79a..5e73e449 100644 --- a/pkg/api/core/group/connection/v0/admin.go +++ b/pkg/api/core/group/connection/v0/admin.go @@ -16,14 +16,16 @@ import ( dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" dbConnectionTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/connection/v0" + dbIPv4RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4_route/v0" + dbIPv6RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6_route/v0" dbNTTTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ntt/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { // ID取得 id, err := strconv.Atoi(c.Param("id")) if err != nil { @@ -57,19 +59,19 @@ func AddAdmin(c *gin.Context) { } resultConnectionTemplate := dbConnectionTemplate.Get(connectionTemplate.ID, - &core.ConnectionTemplate{Model: gorm.Model{ID: *input.ConnectionTemplateID}}) + &core.ConnectionTemplate{Model: gorm.Model{ID: input.ConnectionTemplateID}}) if resultConnectionTemplate.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultConnectionTemplate.Err.Error()}) return } - resultNTT := dbNTTTemplate.Get(ntt.ID, &core.NTTTemplate{Model: gorm.Model{ID: *input.NOCID}}) + resultNTT := dbNTTTemplate.Get(ntt.ID, &core.NTTTemplate{Model: gorm.Model{ID: input.NOCID}}) if resultNTT.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultNTT.Err.Error()}) return } - resultNOC := dbNOC.Get(noc.ID, &core.NOC{Model: gorm.Model{ID: *input.NOCID}}) + resultNOC := dbNOC.Get(noc.ID, &core.NOC{Model: gorm.Model{ID: input.NOCID}}) if resultNOC.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultNOC.Err.Error()}) return @@ -87,6 +89,20 @@ func AddAdmin(c *gin.Context) { return } + // if need_route is true + if *resultService.Service[0].ServiceTemplate.NeedRoute { + _, err = dbIPv4RouteTemplate.Get(input.IPv4RouteTemplateID) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "error: invalid ipv4 route template."}) + return + } + _, err = dbIPv6RouteTemplate.Get(input.IPv6RouteTemplateID) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "error: invalid ipv4 route template."}) + return + } + } + var number uint = 1 for _, tmp := range resultConnection.Connection { if tmp.ConnectionNumber >= 1 { @@ -101,16 +117,18 @@ func AddAdmin(c *gin.Context) { _, err = dbConnection.Create(&core.Connection{ ServiceID: resultService.Service[0].ID, - ConnectionTemplateID: input.ConnectionTemplateID, + ConnectionTemplateID: &[]uint{input.ConnectionTemplateID}[0], ConnectionComment: input.ConnectionComment, ConnectionNumber: number, - NTTTemplateID: input.NTTTemplateID, - NOCID: input.NOCID, + IPv4RouteTemplateID: &[]uint{input.IPv4RouteTemplateID}[0], + IPv6RouteTemplateID: &[]uint{input.IPv6RouteTemplateID}[0], + NTTTemplateID: &[]uint{input.NTTTemplateID}[0], + NOCID: &[]uint{input.NOCID}[0], TermIP: input.TermIP, Address: input.Address, - Monitor: input.Monitor, + Monitor: &[]bool{input.Monitor}[0], + Enable: &[]bool{true}[0], Open: &[]bool{false}[0], - Lock: &[]bool{true}[0], }) if err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) @@ -131,7 +149,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, connection.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -151,7 +169,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, connection.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.Connection id, err := strconv.Atoi(c.Param("id")) @@ -179,7 +197,7 @@ func UpdateAdmin(c *gin.Context) { return } - noticeSlackAdmin(tmp.Connection[0], input) + noticeSlackByAdmin(tmp.Connection[0], input) input.ID = uint(id) @@ -190,7 +208,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, connection.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -210,7 +228,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, connection.Result{Connection: result.Connection}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/group/connection/v0/check.go b/pkg/api/core/group/connection/v0/check.go index ef04e406..eeadfe2d 100644 --- a/pkg/api/core/group/connection/v0/check.go +++ b/pkg/api/core/group/connection/v0/check.go @@ -1,15 +1,10 @@ package v0 import ( - "fmt" "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection" ) func check(input connection.Input) error { - if input.Address == "" { - return fmt.Errorf("error: address is invalid") - } - return nil } diff --git a/pkg/api/core/group/connection/v0/connection.go b/pkg/api/core/group/connection/v0/connection.go index e7a19e2f..affd9436 100644 --- a/pkg/api/core/group/connection/v0/connection.go +++ b/pkg/api/core/group/connection/v0/connection.go @@ -7,7 +7,6 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" - "github.com/homenoc/dsbd-backend/pkg/api/core/group" "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" "github.com/homenoc/dsbd-backend/pkg/api/core/noc" @@ -16,11 +15,12 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" dbConnection "github.com/homenoc/dsbd-backend/pkg/api/store/group/connection/v0" dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" - dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" dbConnectionTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/connection/v0" + dbIPv4RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4_route/v0" + dbIPv6RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6_route/v0" dbNTTTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ntt/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" @@ -68,7 +68,7 @@ func Add(c *gin.Context) { return } - if !(*result.User.Group.Status == 3 && *result.User.Group.ExpiredStatus == 0) { + if *result.User.Group.ExpiredStatus != 0 { c.JSON(http.StatusUnauthorized, common.Error{Error: "error: failed group status"}) return } @@ -79,14 +79,14 @@ func Add(c *gin.Context) { } resultConnectionTemplate := dbConnectionTemplate.Get(connectionTemplate.ID, - &core.ConnectionTemplate{Model: gorm.Model{ID: *input.ConnectionTemplateID}}) + &core.ConnectionTemplate{Model: gorm.Model{ID: input.ConnectionTemplateID}}) if resultConnectionTemplate.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultConnectionTemplate.Err.Error()}) return } if *resultConnectionTemplate.Connections[0].NeedInternet { - resultNTT := dbNTTTemplate.Get(ntt.ID, &core.NTTTemplate{Model: gorm.Model{ID: *input.NTTTemplateID}}) + resultNTT := dbNTTTemplate.Get(ntt.ID, &core.NTTTemplate{Model: gorm.Model{ID: input.NTTTemplateID}}) if resultNTT.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultNTT.Err.Error()}) return @@ -94,8 +94,8 @@ func Add(c *gin.Context) { } // NOCIDが0の時、「どこでも収容」という意味 - if *input.NOCID != 0 { - resultNOC := dbNOC.Get(noc.ID, &core.NOC{Model: gorm.Model{ID: *input.NOCID}}) + if input.NOCID != 0 { + resultNOC := dbNOC.Get(noc.ID, &core.NOC{Model: gorm.Model{ID: input.NOCID}}) if resultNOC.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultNOC.Err.Error()}) return @@ -108,8 +108,21 @@ func Add(c *gin.Context) { return } - if !(*resultService.Service[0].AddAllow) { - c.JSON(http.StatusBadRequest, common.Error{Error: "error: You are not allowed to add any connection information."}) + // check service enable + if !*resultService.Service[0].Enable { + c.JSON(http.StatusBadRequest, common.Error{Error: "You don't allow this operation. [enable]"}) + return + } + + // check service pass + if !*resultService.Service[0].Pass { + c.JSON(http.StatusBadRequest, common.Error{Error: "You don't allow this operation. [pass]"}) + return + } + + // check add_allow + if !*resultService.Service[0].AddAllow { + c.JSON(http.StatusBadRequest, common.Error{Error: "You don't allow this operation. [add_allow]"}) return } @@ -119,6 +132,38 @@ func Add(c *gin.Context) { return } + // if need_route is true + if *resultService.Service[0].ServiceTemplate.NeedRoute { + ipv4Enable := false + ipv6Enable := false + + for _, tmpServiceIP := range resultService.Service[0].IP { + if tmpServiceIP.Version == 4 { + ipv4Enable = true + break + } + if tmpServiceIP.Version == 6 { + ipv6Enable = true + break + } + } + + if ipv4Enable { + _, err = dbIPv4RouteTemplate.Get(input.IPv4RouteTemplateID) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "error: invalid ipv4 route template."}) + return + } + } + if ipv6Enable { + _, err = dbIPv6RouteTemplate.Get(input.IPv6RouteTemplateID) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "error: invalid ipv4 route template."}) + return + } + } + } + resultConnection := dbConnection.Get(connection.ServiceID, &core.Connection{ServiceID: uint(id)}) if resultConnection.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultConnection.Err.Error()}) @@ -136,20 +181,57 @@ func Add(c *gin.Context) { return } + var connectonTemplateID *uint + if input.ConnectionTemplateID == 0 { + connectonTemplateID = nil + } else { + connectonTemplateID = &[]uint{input.ConnectionTemplateID}[0] + } + + var IPv4RouteTemplateID *uint + if input.IPv4RouteTemplateID == 0 { + IPv4RouteTemplateID = nil + } else { + IPv4RouteTemplateID = &[]uint{input.IPv4RouteTemplateID}[0] + } + + var IPv6RouteTemplateID *uint + if input.IPv6RouteTemplateID == 0 { + IPv6RouteTemplateID = nil + } else { + IPv6RouteTemplateID = &[]uint{input.IPv6RouteTemplateID}[0] + } + + var NTTTemplateID *uint + if input.NTTTemplateID == 0 { + NTTTemplateID = nil + } else { + NTTTemplateID = &[]uint{input.NTTTemplateID}[0] + } + + var NOCID *uint + if input.NOCID == 0 { + NOCID = nil + } else { + NOCID = &[]uint{input.NOCID}[0] + } + _, err = dbConnection.Create(&core.Connection{ ServiceID: resultService.Service[0].ID, - ConnectionTemplateID: input.ConnectionTemplateID, + ConnectionTemplateID: connectonTemplateID, ConnectionComment: input.ConnectionComment, ConnectionNumber: number, - NTTTemplateID: input.NTTTemplateID, - NOCID: input.NOCID, - BGPRouterID: &[]uint{0}[0], - TunnelEndPointRouterIPID: &[]uint{0}[0], + IPv4RouteTemplateID: IPv4RouteTemplateID, + IPv6RouteTemplateID: IPv6RouteTemplateID, + NTTTemplateID: NTTTemplateID, + NOCID: NOCID, + BGPRouterID: nil, + TunnelEndPointRouterIPID: nil, TermIP: input.TermIP, Address: input.Address, - Monitor: input.Monitor, + Monitor: &[]bool{input.Monitor}[0], + Enable: &[]bool{true}[0], Open: &[]bool{false}[0], - Lock: &[]bool{true}[0], }) if err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) @@ -167,15 +249,15 @@ func Add(c *gin.Context) { AddField(slack.Field{Title: "接続コード(補足情報)", Value: input.ConnectionComment}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) - if err = dbGroup.Update(group.UpdateStatus, core.Group{ - Model: gorm.Model{ID: result.User.Group.ID}, - Status: &[]uint{4}[0], - }); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } + //if err = dbGroup.Update(group.UpdateStatus, core.Group{ + // Model: gorm.Model{ID: result.User.Group.ID}, + // Status: &[]uint{4}[0], + //}); err != nil { + // c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + // return + //} - if err = dbService.Update(service.UpdateStatus, core.Service{ + if err = dbService.Update(service.UpdateAll, core.Service{ Model: gorm.Model{ID: resultService.Service[0].ID}, AddAllow: &[]bool{false}[0], }); err != nil { diff --git a/pkg/api/core/group/connection/v0/slack.go b/pkg/api/core/group/connection/v0/slack.go index 5ec357b2..753e4564 100644 --- a/pkg/api/core/group/connection/v0/slack.go +++ b/pkg/api/core/group/connection/v0/slack.go @@ -14,11 +14,11 @@ import ( dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" dbConnectionTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/connection/v0" dbNTTTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ntt/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "strconv" ) -func noticeSlackAdmin(before, after core.Connection) { +func noticeSlackByAdmin(before, after core.Connection) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} @@ -41,16 +41,6 @@ func changeText(before, after core.Connection) string { } } - if after.Lock != nil { - if *before.Lock != *after.Lock { - if !*after.Lock { - data += "ユーザ変更: 禁止 => 許可\n" - } else { - data += "ユーザ変更: 許可 => 禁止\n" - } - } - } - if after.ConnectionTemplateID != nil { if *before.ConnectionTemplateID != *after.ConnectionTemplateID { data += "接続ID: " + before.ConnectionTemplate.Type + " => " + diff --git a/pkg/api/core/group/info/interface.go b/pkg/api/core/group/info/interface.go index 90b50aef..32f2b658 100644 --- a/pkg/api/core/group/info/interface.go +++ b/pkg/api/core/group/info/interface.go @@ -1,23 +1,194 @@ package info +import ( + "time" +) + +type User struct { + ID uint `json:"id"` + GroupID uint `json:"group_id"` + StripeCustomerID string `json:"stripe_customer_id"` + Name string `json:"name"` + NameEn string `json:"name_en"` + Email string `json:"email"` + Status uint `json:"status"` + Level uint `json:"level"` + MailVerify *bool `json:"mail_verify"` +} + +type Group struct { + ID uint `json:"id"` + PaymentMembershipTemplate string `json:"payment_membership_template"` + Agree *bool `json:"agree"` + Question string `json:"question"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + Tel string `json:"tel"` + Country string `json:"country"` + Contract string `json:"contract"` + Paid *bool `json:"paid"` + AutomaticUpdate bool `json:"automatic_update"` + DiscountRate uint `json:"discount_rate"` + MemberInfo string `json:"member_info"` + MemberExpired *time.Time `json:"member_expired"` + Student *bool `json:"student"` + StudentExpired *time.Time `json:"student_expired"` + Pass *bool `json:"pass"` + Lock *bool `json:"lock"` + ExpiredStatus *uint `json:"expired_status"` + AddAllow *bool `json:"add_allow"` +} + +type Notice struct { + StartTime time.Time `json:"start_time"` + EndTime time.Time `json:"end_time"` + Everyone bool `json:"everyone"` + Important bool `json:"important"` + Fault bool `json:"fault"` + Info bool `json:"info"` + Title string `json:"title"` + Data string `json:"data"` +} + +type Ticket struct { + ID uint `json:"id"` + CreatedAt time.Time `json:"created_at"` + GroupID uint `json:"group_id"` + UserID uint `json:"user_id"` + Title string `json:"title"` + Admin *bool `json:"admin"` + Chat []Chat `json:"chat"` + Solved *bool `json:"solved"` +} + +type Chat struct { + CreatedAt time.Time `json:"created_at"` + TicketID uint `json:"ticket_id"` + UserID uint `json:"user_id"` + Admin bool `json:"admin"` + Data string `json:"data" gorm:"size:65535"` +} + type Info struct { - ServiceID string `json:"service_id"` - Service string `json:"service"` - Assign bool `json:"assign"` - ASN uint `json:"asn"` - V4 []string `json:"v4"` - V6 []string `json:"v6"` - UserID uint `json:"user_id"` - NOC string `json:"noc"` - NOCIP string `json:"noc_ip"` - TermIP string `json:"term_ip"` - LinkV4Our string `json:"link_v4_our"` - LinkV4Your string `json:"link_v4_your"` - LinkV6Our string `json:"link_v6_our"` - LinkV6Your string `json:"link_v6_your"` - Fee string `json:"fee"` + ServiceID string `json:"service_id"` + Service string `json:"service"` + Assign bool `json:"assign"` + ASN uint `json:"asn"` + V4 []string `json:"v4"` + V6 []string `json:"v6"` + NOC string `json:"noc"` + NOCIP string `json:"noc_ip"` + TermIP string `json:"term_ip"` + LinkV4Our string `json:"link_v4_our"` + LinkV4Your string `json:"link_v4_your"` + LinkV6Our string `json:"link_v6_our"` + LinkV6Your string `json:"link_v6_your"` + Fee string `json:"fee"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + JPNICAdmin JPNIC `json:"jpnic_admin"` + JPNICTech []JPNIC `json:"jpnic_tech"` + AveUpstream uint `json:"avg_upstream"` + MaxUpstream uint `json:"max_upstream"` + AveDownstream uint `json:"avg_downstream"` + MaxDownstream uint `json:"max_downstream"` + MaxBandWidthAS string `json:"max_bandwidth_as"` + BGPRouteV4 string `json:"bgp_route_v4"` + BGPRouteV6 string `json:"bgp_route_v6"` +} + +type JPNIC struct { + ID uint `json:"id"` + Name string `json:"name"` + NameEn string `json:"name_en"` + Mail string `json:"mail"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + Dept string `json:"dept"` + DeptEn string `json:"dept_en"` + Tel string `json:"tel"` + Fax string `json:"fax"` + Country string `json:"country"` +} + +type IP struct { + ID uint `json:"id"` + Version uint `json:"version"` + Name string `json:"name"` + IP string `json:"ip"` + Plan []Plan `json:"plan" ` + PlanJPNIC string `json:"" gorm:"size:65535"` + UseCase string `json:"use_case"` +} + +type Plan struct { + ID uint `json:"id"` + IPID uint `json:"ip_id"` + Name string `json:"name"` + After uint `json:"after"` + HalfYear uint `json:"half_year"` + OneYear uint `json:"one_year"` +} + +type Service struct { + ID uint `json:"id"` + ServiceID string `json:"service_id"` + ServiceType string `json:"service_type"` + NeedRoute bool `json:"need_route"` + NeedJPNIC bool `json:"need_jpnic"` + AddAllow bool `json:"add_allow"` + Pass bool `json:"pass"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + ASN *uint `json:"asn"` + AveUpstream uint `json:"avg_upstream"` + MaxUpstream uint `json:"max_upstream"` + AveDownstream uint `json:"avg_downstream"` + MaxDownstream uint `json:"max_downstream"` + MaxBandWidthAS string `json:"max_bandwidth_as"` + JPNICAdmin JPNIC `json:"jpnic_admin"` + JPNICTech []JPNIC `json:"jpnic_tech"` + IP []IP `json:"ip"` +} + +type Connection struct { + ID uint `json:"id"` + ServiceID string `json:"service_id"` + Open bool `json:"open"` +} + +type Request struct { + ID uint `json:"id"` + CreatedAt time.Time `json:"created_at"` + GroupID uint `json:"group_id"` + UserID uint `json:"user_id"` + Title string `json:"title"` + Admin *bool `json:"admin"` + Chat []Chat `json:"chat"` + Solved *bool `json:"solved"` + Reject *bool `json:"reject"` } type Result struct { - Info []Info `json:"info"` + User User `json:"user"` + Group Group `json:"group"` + UserList []User `json:"user_list"` + Notice []Notice `json:"notice"` + Ticket []Ticket `json:"ticket"` + Service []Service `json:"service"` + Connection []Connection `json:"connection"` + Request []Request `json:"request"` + Info []Info `json:"info"` } diff --git a/pkg/api/core/group/info/v0/info.go b/pkg/api/core/group/info/v0/info.go index 74c8e643..60bc75ff 100644 --- a/pkg/api/core/group/info/v0/info.go +++ b/pkg/api/core/group/info/v0/info.go @@ -7,83 +7,396 @@ import ( auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/group/info" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" - dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/notice" + "github.com/homenoc/dsbd-backend/pkg/api/core/user" + dbNotice "github.com/homenoc/dsbd-backend/pkg/api/store/notice/v0" + dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" + "gorm.io/gorm" "net/http" + "sort" "strconv" + "time" ) func Get(c *gin.Context) { userToken := c.Request.Header.Get("USER_TOKEN") accessToken := c.Request.Header.Get("ACCESS_TOKEN") - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + authResult := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) + if authResult.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: authResult.Err.Error()}) return } - if !(0 < result.User.Level && result.User.Level <= 3) { - c.JSON(http.StatusForbidden, common.Error{Error: "error: access is not permitted"}) + // User + var resultUser info.User + dbUserResult := dbUser.Get(user.IDDetail, &core.User{Model: gorm.Model{ID: authResult.User.ID}}) + if dbUserResult.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: dbUserResult.Err.Error()}) return } - resultService := dbService.Get(service.Open, &core.Service{GroupID: result.User.GroupID}) - if resultService.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: resultService.Err.Error()}) - return + var groupID uint = 0 + if authResult.User.GroupID != nil { + groupID = *authResult.User.GroupID + } + + resultUser = info.User{ + ID: authResult.User.ID, + GroupID: groupID, + Name: authResult.User.Name, + NameEn: authResult.User.NameEn, + Email: authResult.User.Email, + Level: authResult.User.Level, + MailVerify: authResult.User.MailVerify, + } + + //log.Println(*authResult.User.Group.PaymentCouponTemplateID) + //log.Println(*authResult.User.Group.PaymentMembershipTemplateID) + + // Group and UserList + var resultGroup info.Group + var resultUserList []info.User + + if authResult.User.GroupID != nil { + // Membership Info + membershipInfo := "一般会員" + membershipPlan := "未設定" + paid := false + automaticUpdate := false + var discountRate uint = 0 + if authResult.User.Group.PaymentCouponTemplateID != nil && *authResult.User.Group.PaymentCouponTemplateID != 0 { + membershipInfo = dbUserResult.User[0].Group.PaymentCouponTemplate.Title + discountRate = dbUserResult.User[0].Group.PaymentCouponTemplate.DiscountRate + } + if authResult.User.Group.PaymentMembershipTemplateID != nil && *authResult.User.Group.PaymentMembershipTemplateID != 0 { + membershipPlan = dbUserResult.User[0].Group.PaymentMembershipTemplate.Plan + automaticUpdate = true + } + if dbUserResult.User[0].Group.MemberExpired != nil && dbUserResult.User[0].Group.MemberExpired.Unix() > time.Now().Unix() { + paid = true + } + + resultGroup = info.Group{ + ID: authResult.User.Group.ID, + Student: authResult.User.Group.Student, + Pass: authResult.User.Group.Pass, + ExpiredStatus: authResult.User.Group.ExpiredStatus, + MemberInfo: membershipInfo, + AutomaticUpdate: automaticUpdate, + Paid: &paid, + DiscountRate: discountRate, + PaymentMembershipTemplate: membershipPlan, + MemberExpired: authResult.User.Group.MemberExpired, + } + if authResult.User.Level < 3 { + resultGroup.Agree = dbUserResult.User[0].Group.Agree + resultGroup.Question = dbUserResult.User[0].Group.Question + resultGroup.Org = dbUserResult.User[0].Group.Org + resultGroup.OrgEn = dbUserResult.User[0].Group.OrgEn + resultGroup.PostCode = dbUserResult.User[0].Group.PostCode + resultGroup.Address = dbUserResult.User[0].Group.Address + resultGroup.AddressEn = dbUserResult.User[0].Group.AddressEn + resultGroup.Tel = dbUserResult.User[0].Group.Tel + resultGroup.Country = dbUserResult.User[0].Group.Country + resultGroup.Contract = dbUserResult.User[0].Group.Contract + resultGroup.AddAllow = dbUserResult.User[0].Group.AddAllow + } + + if 0 < authResult.User.Level && authResult.User.Level <= 3 { + for _, tmpUser := range dbUserResult.User[0].Group.Users { + resultUserList = append(resultUserList, info.User{ + ID: tmpUser.ID, + GroupID: *tmpUser.GroupID, + Name: tmpUser.Name, + NameEn: tmpUser.NameEn, + Email: tmpUser.Email, + Level: tmpUser.Level, + MailVerify: tmpUser.MailVerify, + }) + } + } } - if len(resultService.Service) == 0 { - c.JSON(http.StatusNoContent, common.Error{Error: "error: No service information available."}) + // Notice + var resultNotice []info.Notice + noticeResult := dbNotice.Get(notice.UIDOrAll, &core.Notice{User: []core.User{{Model: gorm.Model{ID: authResult.User.ID}}}}) + if noticeResult.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: noticeResult.Err.Error()}) return } + for _, tmpNotice := range noticeResult.Notice { + resultNotice = append(resultNotice, info.Notice{ + StartTime: tmpNotice.StartTime, + EndTime: tmpNotice.EndTime, + Everyone: *tmpNotice.Everyone, + Important: *tmpNotice.Important, + Fault: *tmpNotice.Fault, + Info: *tmpNotice.Info, + Title: tmpNotice.Title, + Data: tmpNotice.Data, + }) + } - var infoInterface []info.Info + // Ticket/Request + var resultTicket []info.Ticket + var resultRequest []info.Request - for _, tmpService := range resultService.Service { - if *tmpService.Open { - for _, tmpConnection := range tmpService.Connection { - var fee string - var v4, v6 []string - if *tmpService.Fee == 0 { - fee = "Free" - } else { - fee = strconv.Itoa(int(*tmpService.Fee)) + "円" + if dbUserResult.User[0].GroupID != nil { + for _, tmpTicket := range dbUserResult.User[0].Group.Tickets { + var resultChat []info.Chat + for _, tmpChat := range tmpTicket.Chat { + var userID uint = 0 + if tmpChat.UserID != nil { + userID = *tmpChat.UserID } - serviceID := strconv.Itoa(int(tmpService.GroupID)) + "-" + tmpService.ServiceTemplate.Type + - fmt.Sprintf("%03d", tmpService.ServiceNumber) + "-" + tmpConnection.ConnectionTemplate.Type + - fmt.Sprintf("%03d", tmpConnection.ConnectionNumber) + resultChat = append(resultChat, info.Chat{ + CreatedAt: tmpChat.CreatedAt, + TicketID: tmpChat.TicketID, + UserID: userID, + Admin: tmpChat.Admin, + Data: tmpChat.Data, + }) + } + + if !*tmpTicket.Request { + var groupIDTicket uint = 0 + if tmpTicket.GroupID != nil { + groupIDTicket = *tmpTicket.GroupID + } + + // Ticket + resultTicket = append(resultTicket, info.Ticket{ + ID: tmpTicket.ID, + CreatedAt: tmpTicket.CreatedAt, + GroupID: groupIDTicket, + UserID: *tmpTicket.UserID, + Chat: resultChat, + Solved: tmpTicket.Solved, + Admin: tmpTicket.Admin, + Title: tmpTicket.Title, + }) + } else { + // Request + resultRequest = append(resultRequest, info.Request{ + ID: tmpTicket.ID, + CreatedAt: tmpTicket.CreatedAt, + GroupID: *tmpTicket.GroupID, + UserID: *tmpTicket.UserID, + Chat: resultChat, + Reject: tmpTicket.RequestReject, + Solved: tmpTicket.Solved, + Admin: tmpTicket.Admin, + Title: tmpTicket.Title, + }) + } + } + for _, tmpTicket := range dbUserResult.User[0].Ticket { + var resultChat []info.Chat + if tmpTicket.GroupID == nil { + for _, tmpChat := range tmpTicket.Chat { + + var userID uint = 0 + if tmpChat.UserID != nil { + userID = *tmpChat.UserID + } + + resultChat = append(resultChat, info.Chat{ + CreatedAt: tmpChat.CreatedAt, + TicketID: tmpChat.TicketID, + UserID: userID, + Admin: tmpChat.Admin, + Data: tmpChat.Data, + }) + } + + resultTicket = append(resultTicket, info.Ticket{ + ID: tmpTicket.ID, + CreatedAt: tmpTicket.CreatedAt, + GroupID: 0, + UserID: authResult.User.ID, + Chat: resultChat, + Solved: tmpTicket.Solved, + Title: tmpTicket.Title, + }) + } + } + sort.Slice(resultTicket, func(i, j int) bool { + if resultTicket[i].ID < resultTicket[j].ID { + return true + } + return false + }) + } + + // Info + var resultInfo []info.Info + var resultService []info.Service + var resultConnection []info.Connection + + if authResult.User.GroupID != nil { + + if !(0 < authResult.User.Level && authResult.User.Level <= 3) { + c.JSON(http.StatusForbidden, common.Error{Error: "error: access is not permitted"}) + return + } + + for _, tmpService := range dbUserResult.User[0].Group.Services { + // Service + if *tmpService.Enable { + var resultServiceJPNICAdmin info.JPNIC + var resultServiceJPNICTech []info.JPNIC + var resultServiceIP []info.IP + + // JPNIC Admin + resultServiceJPNICAdmin.ID = tmpService.JPNICAdmin.ID + resultServiceJPNICAdmin.Org = tmpService.JPNICAdmin.Org + resultServiceJPNICAdmin.OrgEn = tmpService.JPNICAdmin.OrgEn + resultServiceJPNICAdmin.PostCode = tmpService.JPNICAdmin.PostCode + resultServiceJPNICAdmin.Name = tmpService.JPNICAdmin.Name + resultServiceJPNICAdmin.NameEn = tmpService.JPNICAdmin.NameEn + resultServiceJPNICAdmin.Dept = tmpService.JPNICAdmin.Dept + resultServiceJPNICAdmin.DeptEn = tmpService.JPNICAdmin.DeptEn + resultServiceJPNICAdmin.Tel = tmpService.JPNICAdmin.Tel + resultServiceJPNICAdmin.Fax = tmpService.JPNICAdmin.Fax + resultServiceJPNICAdmin.Mail = tmpService.JPNICAdmin.Mail + resultServiceJPNICAdmin.Country = tmpService.JPNICAdmin.Country + + // JPNIC Tech + for _, tmpJPNICTech := range tmpService.JPNICTech { + resultServiceJPNICTech = append(resultServiceJPNICTech, info.JPNIC{ + ID: tmpJPNICTech.ID, + Name: tmpJPNICTech.Name, + NameEn: tmpJPNICTech.NameEn, + Org: tmpJPNICTech.Org, + OrgEn: tmpJPNICTech.OrgEn, + PostCode: tmpJPNICTech.PostCode, + Address: tmpJPNICTech.Address, + AddressEn: tmpJPNICTech.AddressEn, + Dept: tmpJPNICTech.Dept, + DeptEn: tmpJPNICTech.DeptEn, + Tel: tmpJPNICTech.Tel, + Fax: tmpJPNICTech.Fax, + Mail: tmpJPNICTech.Mail, + Country: tmpJPNICTech.Country, + }) + } + + // IP for _, tmpIP := range tmpService.IP { - if tmpIP.Version == 4 { - v4 = append(v4, tmpIP.IP) - } else if tmpIP.Version == 6 { - v6 = append(v6, tmpIP.IP) + if *tmpIP.Open { + var resultIPPlan []info.Plan = nil + if tmpIP.Plan != nil { + for _, tmpIPPlan := range tmpIP.Plan { + resultIPPlan = append(resultIPPlan, info.Plan{ + ID: tmpIPPlan.ID, + IPID: tmpIPPlan.IPID, + Name: tmpIPPlan.Name, + After: tmpIPPlan.After, + HalfYear: tmpIPPlan.HalfYear, + OneYear: tmpIPPlan.OneYear, + }) + } + } + + resultServiceIP = append(resultServiceIP, info.IP{ + ID: tmpIP.ID, + Version: tmpIP.Version, + Name: tmpIP.Name, + IP: tmpIP.IP, + Plan: resultIPPlan, + PlanJPNIC: "", + UseCase: tmpIP.UseCase, + }) } } - if *tmpConnection.Open { - infoInterface = append(infoInterface, info.Info{ - ServiceID: serviceID, - Service: tmpService.ServiceTemplate.Name, - Assign: *tmpService.ServiceTemplate.NeedJPNIC, - ASN: *tmpService.ASN, - V4: v4, - V6: v6, - NOC: tmpConnection.NOC.Name, - NOCIP: tmpConnection.TunnelEndPointRouterIP.IP, - TermIP: tmpConnection.TermIP, - LinkV4Our: tmpConnection.LinkV4Our, - LinkV4Your: tmpConnection.LinkV4Your, - LinkV6Our: tmpConnection.LinkV6Our, - LinkV6Your: tmpConnection.LinkV6Your, - Fee: fee, + resultService = append(resultService, info.Service{ + ID: tmpService.ID, + ServiceID: strconv.Itoa(int(tmpService.GroupID)) + "-" + tmpService.ServiceTemplate.Type + + fmt.Sprintf("%03d", tmpService.ServiceNumber), + ServiceType: tmpService.ServiceTemplate.Type, + NeedRoute: *tmpService.ServiceTemplate.NeedRoute, + NeedJPNIC: *tmpService.ServiceTemplate.NeedJPNIC, + AddAllow: *tmpService.AddAllow, + Pass: *tmpService.Pass, + Org: tmpService.Org, + OrgEn: tmpService.OrgEn, + PostCode: tmpService.PostCode, + Address: tmpService.Address, + AddressEn: tmpService.AddressEn, + ASN: tmpService.ASN, + AveUpstream: tmpService.AveUpstream, + MaxUpstream: tmpService.MaxUpstream, + AveDownstream: tmpService.AveDownstream, + MaxDownstream: tmpService.MaxDownstream, + MaxBandWidthAS: tmpService.MaxBandWidthAS, + IP: resultServiceIP, + JPNICAdmin: resultServiceJPNICAdmin, + JPNICTech: resultServiceJPNICTech, + }) + } + for _, tmpConnection := range tmpService.Connection { + serviceID := strconv.Itoa(int(tmpService.GroupID)) + "-" + tmpService.ServiceTemplate.Type + + fmt.Sprintf("%03d", tmpService.ServiceNumber) + "-" + tmpConnection.ConnectionTemplate.Type + + fmt.Sprintf("%03d", tmpConnection.ConnectionNumber) + + // Connection + if *tmpConnection.Enable { + resultConnection = append(resultConnection, info.Connection{ + ID: tmpConnection.ID, + ServiceID: serviceID, + Open: *tmpConnection.Open, }) } + + if *tmpService.Pass && *tmpService.Enable { + var v4, v6 []string + + for _, tmpIP := range tmpService.IP { + if *tmpIP.Open { + if tmpIP.Version == 4 { + v4 = append(v4, tmpIP.IP) + } else if tmpIP.Version == 6 { + v6 = append(v6, tmpIP.IP) + } + } + } + + if *tmpConnection.Open && *tmpConnection.Enable { + resultInfo = append(resultInfo, info.Info{ + ServiceID: serviceID, + Service: tmpService.ServiceTemplate.Name, + Assign: *tmpService.ServiceTemplate.NeedJPNIC, + ASN: *tmpService.ASN, + V4: v4, + V6: v6, + Fee: "Free", + NOC: tmpConnection.NOC.Name, + NOCIP: tmpConnection.TunnelEndPointRouterIP.IP, + TermIP: tmpConnection.TermIP, + LinkV4Our: tmpConnection.LinkV4Our, + LinkV4Your: tmpConnection.LinkV4Your, + LinkV6Our: tmpConnection.LinkV6Our, + LinkV6Your: tmpConnection.LinkV6Your, + }) + } + } } + } } - c.JSON(http.StatusOK, info.Result{Info: infoInterface}) + c.JSON(http.StatusOK, info.Result{ + User: resultUser, + Group: resultGroup, + UserList: resultUserList, + Service: resultService, + Connection: resultConnection, + Notice: resultNotice, + Ticket: resultTicket, + Request: resultRequest, + Info: resultInfo, + }) } diff --git a/pkg/api/core/group/interface.go b/pkg/api/core/group/interface.go index e2aca5a6..2645cef4 100644 --- a/pkg/api/core/group/interface.go +++ b/pkg/api/core/group/interface.go @@ -7,16 +7,16 @@ import ( ) const ( - ID = 0 - OrgJa = 1 - Org = 2 - Email = 3 - UpdateID = 100 - UpdateOrg = 101 - UpdateStatus = 102 - UpdateTechID = 103 - UpdateInfo = 104 - UpdateAll = 150 + ID = 0 + OrgJa = 1 + Org = 2 + Email = 3 + UpdateID = 100 + UpdateOrg = 101 + UpdateStatus = 102 + UpdateTechID = 103 + UpdateMembership = 105 + UpdateAll = 150 ) type Input struct { diff --git a/pkg/api/core/group/memo/v0/admin.go b/pkg/api/core/group/memo/v0/admin.go new file mode 100644 index 00000000..8b6d97c2 --- /dev/null +++ b/pkg/api/core/group/memo/v0/admin.go @@ -0,0 +1,67 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + dbMemo "github.com/homenoc/dsbd-backend/pkg/api/store/group/memo/v0" + "gorm.io/gorm" + "log" + "net/http" + "strconv" +) + +func AddByAdmin(c *gin.Context) { + var input core.Memo + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + err := c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = check(input); err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + result, err := dbMemo.Create(&input) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + noticeSlackAdd(result) + + c.JSON(http.StatusOK, common.Result{}) +} + +func DeleteByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbMemo.Delete(&core.Memo{Model: gorm.Model{ID: uint(id)}}); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + noticeSlackDelete(id) + + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/group/memo/v0/check.go b/pkg/api/core/group/memo/v0/check.go new file mode 100644 index 00000000..dab9c7f0 --- /dev/null +++ b/pkg/api/core/group/memo/v0/check.go @@ -0,0 +1,20 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" +) + +func check(input core.Memo) error { + if input.GroupID == 0 { + return fmt.Errorf("GroupID is wrong... ") + } + if !(1 <= input.Type && input.Type <= 3) { + return fmt.Errorf("type is wrong... ") + } + if input.Message == "" { + return fmt.Errorf("message is wrong... ") + } + + return nil +} diff --git a/pkg/api/core/group/memo/v0/slack.go b/pkg/api/core/group/memo/v0/slack.go new file mode 100644 index 00000000..5f2af857 --- /dev/null +++ b/pkg/api/core/group/memo/v0/slack.go @@ -0,0 +1,31 @@ +package v0 + +import ( + "github.com/ashwanthkumar/slack-go-webhook" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" + "strconv" +) + +func noticeSlackAdd(memo *core.Memo) { + // 審査ステータスのSlack通知 + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "Memoの登録"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "GroupID", Value: strconv.Itoa(int(memo.GroupID))}). + AddField(slack.Field{Title: "Type", Value: strconv.Itoa(int(memo.Type))}). + AddField(slack.Field{Title: "Title", Value: memo.Title}). + AddField(slack.Field{Title: "Message", Value: memo.Message}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackDelete(id int) { + // 審査ステータスのSlack通知 + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "Memoの削除"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "ID", Value: strconv.Itoa(id)}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} diff --git a/pkg/api/core/group/service/interface.go b/pkg/api/core/group/service/interface.go index d959e94a..3e3c217b 100644 --- a/pkg/api/core/group/service/interface.go +++ b/pkg/api/core/group/service/interface.go @@ -43,13 +43,11 @@ type Input struct { Postcode string `json:"postcode"` Address string `json:"address"` AddressEn string `json:"address_en"` - RouteV4 string `json:"route_v4"` - RouteV6 string `json:"route_v6"` AveUpstream uint `json:"avg_upstream"` MaxUpstream uint `json:"max_upstream"` AveDownstream uint `json:"avg_downstream"` MaxDownstream uint `json:"max_downstream"` - MaxBandWidthAS uint `json:"max_bandwidth_as"` + MaxBandWidthAS string `json:"max_bandwidth_as"` ASN uint `json:"asn"` IP []IPInput `json:"ip"` Lock bool `json:"lock"` @@ -93,7 +91,7 @@ type Service struct { MaxUpstream uint `json:"max_upstream"` AveDownstream uint `json:"avg_downstream"` MaxDownstream uint `json:"max_downstream"` - MaxBandWidthAS uint `json:"max_bandwidth_as"` + MaxBandWidthAS string `json:"max_bandwidth_as"` Fee *uint `json:"fee"` IP []core.IP `json:"ip"` Connections *[]connection.Connection `json:"connections"` diff --git a/pkg/api/core/group/service/ip/v0/admin.go b/pkg/api/core/group/service/ip/v0/admin.go index fc6d28b8..4418e584 100644 --- a/pkg/api/core/group/service/ip/v0/admin.go +++ b/pkg/api/core/group/service/ip/v0/admin.go @@ -13,7 +13,7 @@ import ( "strconv" ) -//func DeleteAdmin(c *gin.Context) { +//func DeleteByAdmin(c *gin.Context) { // resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) // if resultAdmin.Err != nil { // c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -33,7 +33,7 @@ import ( // c.JSON(http.StatusOK, service.Result{}) //} -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.IP id, err := strconv.Atoi(c.Param("id")) diff --git a/pkg/api/core/group/service/jpnicAdmin/v0/admin.go b/pkg/api/core/group/service/jpnicAdmin/v0/admin.go index 14fda6d6..f4dc1b45 100644 --- a/pkg/api/core/group/service/jpnicAdmin/v0/admin.go +++ b/pkg/api/core/group/service/jpnicAdmin/v0/admin.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicAdmin" dbJPNICAdmin "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicAdmin/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.JPNICAdmin resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -36,7 +36,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicAdmin.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -56,7 +56,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicAdmin.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.JPNICAdmin resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -79,7 +79,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicAdmin.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -99,7 +99,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicAdmin.Result{Admins: result.Admins}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/group/service/jpnicAdmin/v0/jpnicAdmin.go b/pkg/api/core/group/service/jpnicAdmin/v0/jpnicAdmin.go index 1ccc1c2f..6a27c3b2 100644 --- a/pkg/api/core/group/service/jpnicAdmin/v0/jpnicAdmin.go +++ b/pkg/api/core/group/service/jpnicAdmin/v0/jpnicAdmin.go @@ -11,7 +11,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicTech" dbJPNICAdmin "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicAdmin/v0" dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" diff --git a/pkg/api/core/group/service/jpnicAdmin/v0/slack.go b/pkg/api/core/group/service/jpnicAdmin/v0/slack.go index 99dd5c34..a91377e1 100644 --- a/pkg/api/core/group/service/jpnicAdmin/v0/slack.go +++ b/pkg/api/core/group/service/jpnicAdmin/v0/slack.go @@ -8,25 +8,25 @@ import ( "strconv" ) -func noticeSlackAddAdmin(before, after core.Group) { +func noticeSlackAddByAdmin(before, after core.Group) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} attachment.AddField(slack.Field{Title: "Title", Value: "Group情報の更新"}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + ":" + before.Org}). - AddField(slack.Field{Title: "更新状況", Value: changeTextAdmin(before, after)}) + AddField(slack.Field{Title: "更新状況", Value: changeTextByAdmin(before, after)}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } -func noticeSlackUpdateAdmin(before, after core.Group) { +func noticeSlackUpdateByAdmin(before, after core.Group) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} attachment.AddField(slack.Field{Title: "Title", Value: "Group情報の更新"}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + ":" + before.Org}). - AddField(slack.Field{Title: "更新状況", Value: changeTextAdmin(before, after)}) + AddField(slack.Field{Title: "更新状況", Value: changeTextByAdmin(before, after)}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } @@ -64,7 +64,7 @@ func addText(before core.Group, after group.Input) string { return data } -func changeTextAdmin(before, after core.Group) string { +func changeTextByAdmin(before, after core.Group) string { data := "" if after.Org != "" && after.Org != before.Org { diff --git a/pkg/api/core/group/service/jpnicTech/v0/admin.go b/pkg/api/core/group/service/jpnicTech/v0/admin.go index 3e4131bc..c29827bb 100644 --- a/pkg/api/core/group/service/jpnicTech/v0/admin.go +++ b/pkg/api/core/group/service/jpnicTech/v0/admin.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicTech" dbJPNICTech "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicTech/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.JPNICTech resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -36,7 +36,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicTech.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -56,7 +56,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicTech.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.JPNICTech resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -79,7 +79,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicTech.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: resultAdmin.Err.Error()}) @@ -99,7 +99,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, jpnicTech.Result{Tech: result.Tech}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/group/service/jpnicTech/v0/jpnicTech.go b/pkg/api/core/group/service/jpnicTech/v0/jpnicTech.go index 52b00c7b..c1dd571e 100644 --- a/pkg/api/core/group/service/jpnicTech/v0/jpnicTech.go +++ b/pkg/api/core/group/service/jpnicTech/v0/jpnicTech.go @@ -10,7 +10,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicTech" dbJPNICTech "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicTech/v0" dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" diff --git a/pkg/api/core/group/service/jpnicTech/v0/slack.go b/pkg/api/core/group/service/jpnicTech/v0/slack.go index bb9301ac..07bfbf5f 100644 --- a/pkg/api/core/group/service/jpnicTech/v0/slack.go +++ b/pkg/api/core/group/service/jpnicTech/v0/slack.go @@ -5,28 +5,29 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/group" "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" + slackTool "github.com/homenoc/dsbd-backend/pkg/api/core/tool/slack" "strconv" ) -func noticeSlack(loginUser core.User, before core.Group, after group.Input) { +func noticeSlack(genre uint, loginUser core.User, before core.Group, after group.Input) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} - attachment.AddField(slack.Field{Title: "Title", Value: "Group情報の更新"}). + attachment.AddField(slack.Field{Title: "Title", Value: "JPNIC技術連絡担当者の" + slackTool.NoticeSlackType(genre)}). AddField(slack.Field{Title: "申請者", Value: strconv.Itoa(int(loginUser.ID)) + "-" + loginUser.Name}). AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + ":" + before.Org}). AddField(slack.Field{Title: "更新状況", Value: changeText(before, after)}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } -func noticeSlackAdmin(before, after core.Group) { +func noticeSlackByAdmin(genre uint, before, after core.Group) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} - attachment.AddField(slack.Field{Title: "Title", Value: "Group情報の更新"}). + attachment.AddField(slack.Field{Title: "Title", Value: "JPNIC技術連絡担当者の" + slackTool.NoticeSlackType(genre)}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + ":" + before.Org}). - AddField(slack.Field{Title: "更新状況", Value: changeTextAdmin(before, after)}) + AddField(slack.Field{Title: "更新状況", Value: changeTextByAdmin(before, after)}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } @@ -64,7 +65,7 @@ func changeText(before core.Group, after group.Input) string { return data } -func changeTextAdmin(before, after core.Group) string { +func changeTextByAdmin(before, after core.Group) string { data := "" if after.Open != nil { if *before.Open != *after.Open { diff --git a/pkg/api/core/group/service/v0/admin.go b/pkg/api/core/group/service/v0/admin.go index 565cacba..f4ceed48 100644 --- a/pkg/api/core/group/service/v0/admin.go +++ b/pkg/api/core/group/service/v0/admin.go @@ -2,28 +2,21 @@ package v0 import ( "fmt" - "github.com/ashwanthkumar/slack-go-webhook" "github.com/gin-gonic/gin" "github.com/homenoc/dsbd-backend/pkg/api/core" auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/ip" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicTech" serviceTemplate "github.com/homenoc/dsbd-backend/pkg/api/core/template/service" - "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" - dbPlan "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/ip/plan/v0" - dbIP "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/ip/v0" - dbJPNICTech "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicTech/v0" dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" dbServiceTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/service/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { // ID取得 id, err := strconv.Atoi(c.Param("id")) if err != nil { @@ -61,6 +54,7 @@ func AddAdmin(c *gin.Context) { var grpIP []core.IP = nil + // get service template resultServiceTemplate := dbServiceTemplate.Get(serviceTemplate.ID, &core.ServiceTemplate{Model: gorm.Model{ID: input.ServiceTemplateID}}) if resultServiceTemplate.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultServiceTemplate.Err.Error()}) @@ -78,6 +72,7 @@ func AddAdmin(c *gin.Context) { return } + // 0 < jpnic_tech count < 3 if len(input.JPNICTech) == 0 || len(input.JPNICTech) > 2 { c.JSON(http.StatusBadRequest, common.Error{Error: "error: user tech count"}) return @@ -115,11 +110,6 @@ func AddAdmin(c *gin.Context) { } } - if *resultServiceTemplate.Services[0].NeedRoute && input.RouteV4 == "" && input.RouteV6 == "" { - c.JSON(http.StatusBadRequest, common.Error{Error: "no data: Route Information"}) - return - } - resultNetwork := dbService.Get(service.SearchNewNumber, &core.Service{GroupID: uint(id)}) if resultNetwork.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultNetwork.Err.Error()}) @@ -148,155 +138,28 @@ func AddAdmin(c *gin.Context) { PostCode: input.Postcode, Address: input.Address, AddressEn: input.AddressEn, - RouteV4: input.RouteV4, - RouteV6: input.RouteV6, AveUpstream: input.AveUpstream, MaxUpstream: input.MaxUpstream, AveDownstream: input.AveDownstream, MaxDownstream: input.MaxDownstream, + MaxBandWidthAS: input.MaxBandWidthAS, ASN: &[]uint{input.ASN}[0], - Fee: &[]uint{0}[0], IP: grpIP, JPNICAdmin: input.JPNICAdmin, JPNICTech: input.JPNICTech, - Open: &[]bool{false}[0], - Lock: &[]bool{true}[0], + Enable: &[]bool{true}[0], + Pass: &[]bool{false}[0], AddAllow: &[]bool{false}[0], }) if err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } - - attachment := slack.Attachment{} - attachment.AddField(slack.Field{Title: "Title", Value: "ネットワーク情報登録(管理者実行)"}). - AddField(slack.Field{Title: "申請者", Value: "管理者"}). - AddField(slack.Field{Title: "GroupID", Value: strconv.Itoa(id)}). - AddField(slack.Field{Title: "サービスコード(新規発番)", Value: resultServiceTemplate.Services[0].Type + fmt.Sprintf("%03d", number)}). - AddField(slack.Field{Title: "サービスコード(補足情報)", Value: input.ServiceComment}) - notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) - - c.JSON(http.StatusOK, service.Result{}) -} - -func AddIPAdmin(c *gin.Context) { - var input service.IPInput - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - resultIP, err := ipProcess(true, false, []service.IPInput{input}) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.JoinIP(uint(id), resultIP[0]); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } + noticeSlackAdd(id, resultServiceTemplate.Services[0].Type+fmt.Sprintf("%03d", number), input.ServiceComment) c.JSON(http.StatusOK, service.Result{}) } -func AddPlanAdmin(c *gin.Context) { - var input core.Plan - - err := c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - if _, err = dbPlan.Create(&input); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, service.Result{}) -} - -func AddJPNICAdminAdmin(c *gin.Context) { - var input core.JPNICAdmin - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.JoinJPNICAdmin(uint(id), input); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func AddJPNICTechAdmin(c *gin.Context) { - var input core.JPNICTech - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.JoinJPNICTech(uint(id), input); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -309,112 +172,15 @@ func DeleteAdmin(c *gin.Context) { return } - if err := dbService.Delete(&core.Service{Model: gorm.Model{ID: uint(id)}}); err != nil { + if err = dbService.Delete(&core.Service{Model: gorm.Model{ID: uint(id)}}); err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } + noticeSlackDelete("Service情報", uint(id)) c.JSON(http.StatusOK, service.Result{}) } -func DeleteIPAdmin(c *gin.Context) { - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - ipID, err := strconv.Atoi(c.Param("ip_id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.DeleteIP(uint(id), uint(ipID)); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func DeletePlanAdmin(c *gin.Context) { - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - planID, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbPlan.Delete(&core.Plan{Model: gorm.Model{ID: uint(planID)}}); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func DeleteJPNICAdminAdmin(c *gin.Context) { - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - jpnicID, err := strconv.Atoi(c.Param("jpnic_id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.DeleteJPNICAdmin(uint(id), uint(jpnicID)); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func DeleteJPNICTechAdmin(c *gin.Context) { - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - jpnicID, err := strconv.Atoi(c.Param("jpnic_id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.DeleteJPNICTech(uint(id), uint(jpnicID)); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.Service id, err := strconv.Atoi(c.Param("id")) @@ -436,183 +202,23 @@ func UpdateAdmin(c *gin.Context) { return } - resultService := dbService.Get(service.ID, &core.Service{Model: gorm.Model{ID: uint(id)}}) - if resultService.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultService.Err.Error()}) + before := dbService.Get(service.ID, &core.Service{Model: gorm.Model{ID: uint(id)}}) + if before.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: before.Err.Error()}) return } - noticeSlackAdmin(resultService.Service[0], input) - input.ID = uint(id) if err = dbService.Update(service.UpdateAll, input); err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } + noticeSlackUpdate(before.Service[0], input) c.JSON(http.StatusOK, service.Result{}) } -func UpdateIPAdmin(c *gin.Context) { - var input service.IPInput - - _, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - ipID, err := strconv.Atoi(c.Param("ip_id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - resultIP, err := ipProcess(true, false, []service.IPInput{input}) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - resultIP[0].ID = uint(ipID) - log.Println(input) - - if err = dbIP.Update(ip.UpdateAll, resultIP[0]); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, service.Result{}) -} - -func UpdatePlanAdmin(c *gin.Context) { - var input core.Plan - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - input.ID = uint(id) - - if err = dbPlan.Update(input); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func UpdateJPNICAdminAdmin(c *gin.Context) { - var input core.JPNICAdmin - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - if err = dbService.UpdateJPNICAdmin(uint(id), input); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) -} - -func UpdateJPNICTechAdmin(c *gin.Context) { - var input core.JPNICTech - - resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) - if resultAdmin.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - jpnicID, err := strconv.Atoi(c.Param("jpnic_id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - err = c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - ok := false - - resultJPNICTech := dbService.Get(service.ID, &core.Service{Model: gorm.Model{ID: uint(id)}}) - if resultJPNICTech.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: resultJPNICTech.Err.Error()}) - return - } - - for _, tmp := range resultJPNICTech.Service[0].JPNICTech { - if tmp.ID == uint(jpnicID) { - ok = true - input.Model = tmp.Model - break - } - } - - if ok { - if err = dbJPNICTech.Update(jpnicTech.UpdateAll, input); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - c.JSON(http.StatusOK, common.Result{}) - } else { - c.JSON(http.StatusBadRequest, common.Error{Error: "Not Found GroupID"}) - } -} - -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -633,7 +239,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, service.Result{Service: result.Service}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/group/service/v0/admin_ip.go b/pkg/api/core/group/service/v0/admin_ip.go new file mode 100644 index 00000000..501b9a65 --- /dev/null +++ b/pkg/api/core/group/service/v0/admin_ip.go @@ -0,0 +1,116 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/ip" + dbIP "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/ip/v0" + dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" + "gorm.io/gorm" + "log" + "net/http" + "strconv" +) + +func AddIPByAdmin(c *gin.Context) { + var input service.IPInput + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + resultIP, err := ipProcess(true, false, []service.IPInput{input}) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + resultIP[0].ServiceID = uint(id) + + if err = dbService.JoinIP(resultIP[0]); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackAddIP(id, input.Name) + c.JSON(http.StatusOK, service.Result{}) +} + +func DeleteIPByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbService.DeleteIP(uint(id)); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + noticeSlackDelete("IP情報", uint(id)) + + c.JSON(http.StatusOK, common.Result{}) +} + +func UpdateIPByAdmin(c *gin.Context) { + var input core.IP + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + before := dbIP.Get(ip.ID, &core.IP{Model: gorm.Model{ID: uint(id)}}) + if before.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: before.Err.Error()}) + return + } + + input.ID = uint(id) + + if err = dbService.UpdateIP(input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackUpdateIP(before.IP[0], input) + c.JSON(http.StatusOK, service.Result{}) +} diff --git a/pkg/api/core/group/service/v0/admin_jpnic_admin.go b/pkg/api/core/group/service/v0/admin_jpnic_admin.go new file mode 100644 index 00000000..8d9d2650 --- /dev/null +++ b/pkg/api/core/group/service/v0/admin_jpnic_admin.go @@ -0,0 +1,104 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicAdmin" + dbJPNICAdmin "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicAdmin/v0" + dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" + "gorm.io/gorm" + "log" + "net/http" + "strconv" +) + +func AddJPNICAdminByAdmin(c *gin.Context) { + var input core.JPNICAdmin + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbService.JoinJPNICByAdmin(uint(id), input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackAddJPNICByAdmin(id, input) + c.JSON(http.StatusOK, common.Result{}) +} + +func DeleteJPNICAdminByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbService.DeleteJPNICByAdmin(uint(id)); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackDelete("JPNIC管理者連絡窓口", uint(id)) + c.JSON(http.StatusOK, common.Result{}) +} + +func UpdateJPNICAdminByAdmin(c *gin.Context) { + var input core.JPNICAdmin + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + before := dbJPNICAdmin.Get(jpnicAdmin.ID, &core.JPNICAdmin{Model: gorm.Model{ID: uint(id)}}) + if before.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: before.Err.Error()}) + return + } + + input.ID = uint(id) + + if err = dbService.UpdateJPNICByAdmin(input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackUpdateJPNICByAdmin(before.Admins[0], input) + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/group/service/v0/admin_jpnic_tech.go b/pkg/api/core/group/service/v0/admin_jpnic_tech.go new file mode 100644 index 00000000..6b9dd525 --- /dev/null +++ b/pkg/api/core/group/service/v0/admin_jpnic_tech.go @@ -0,0 +1,107 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicTech" + dbJPNICTech "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/jpnicTech/v0" + dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" + "gorm.io/gorm" + "log" + "net/http" + "strconv" +) + +func AddJPNICTechByAdmin(c *gin.Context) { + var input core.JPNICTech + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + input.ID = 0 + input.ServiceID = uint(id) + + if err = dbService.JoinJPNICTech(input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackAddJPNICTech(id, input) + c.JSON(http.StatusOK, common.Result{}) +} + +func DeleteJPNICTechByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbService.DeleteJPNICTech(uint(id)); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackDelete("JPNIC技術連絡担当者", uint(id)) + c.JSON(http.StatusOK, common.Result{}) +} + +func UpdateJPNICTechByAdmin(c *gin.Context) { + var input core.JPNICTech + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + before := dbJPNICTech.Get(jpnicTech.ID, &core.JPNICTech{Model: gorm.Model{ID: uint(id)}}) + if before.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: before.Err.Error()}) + return + } + + input.ID = uint(id) + + if err = dbJPNICTech.Update(jpnicTech.UpdateAll, input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackUpdateJPNICTech(before.Tech[0], input) + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/group/service/v0/admin_plan.go b/pkg/api/core/group/service/v0/admin_plan.go new file mode 100644 index 00000000..7acd49e0 --- /dev/null +++ b/pkg/api/core/group/service/v0/admin_plan.go @@ -0,0 +1,104 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" + "gorm.io/gorm" + "log" + "net/http" + "strconv" +) + +func AddPlanByAdmin(c *gin.Context) { + var input core.Plan + + err := c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + input.IPID = uint(id) + + if err = dbService.JoinPlan(uint(id), input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackAddPlan(id, input) + c.JSON(http.StatusOK, common.Result{}) +} + +func DeletePlanByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbService.DeletePlan(uint(id)); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackDelete("Plan情報", uint(id)) + c.JSON(http.StatusOK, common.Result{}) +} + +func UpdatePlanByAdmin(c *gin.Context) { + var input core.Plan + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + err = c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + before, err := dbService.GetPlan(&core.Plan{Model: gorm.Model{ID: uint(id)}}) + if err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: err.Error()}) + return + } + + input.ID = uint(id) + + if err = dbService.UpdatePlan(input); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + noticeSlackUpdatePlan(before, input) + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/group/service/v0/check.go b/pkg/api/core/group/service/v0/check.go index cbdc41a5..0a351377 100644 --- a/pkg/api/core/group/service/v0/check.go +++ b/pkg/api/core/group/service/v0/check.go @@ -58,6 +58,12 @@ func checkJPNICAdminUser(input core.JPNICAdmin) error { if input.OrgEn == "" { return fmt.Errorf("failed data: org(english)") } + if input.Name == "" { + return fmt.Errorf("failed data: [jpnic admin] name") + } + if input.NameEn == "" { + return fmt.Errorf("failed data: [jpnic admin] name(english)") + } if input.Mail == "" || !strings.Contains(input.Mail, "@") { return fmt.Errorf("failed data: mail") } @@ -84,6 +90,12 @@ func checkJPNICTechUser(input core.JPNICTech) error { if input.OrgEn == "" { return fmt.Errorf("failed data: org(english)") } + if input.Name == "" { + return fmt.Errorf("failed data: [jpnic tech] name") + } + if input.NameEn == "" { + return fmt.Errorf("failed data: [jpnic tech] name(english)") + } if input.Mail == "" || !strings.Contains(input.Mail, "@") { return fmt.Errorf("failed data: mail") } diff --git a/pkg/api/core/group/service/v0/service.go b/pkg/api/core/group/service/v0/service.go index 2bef7ef1..6001cca3 100644 --- a/pkg/api/core/group/service/v0/service.go +++ b/pkg/api/core/group/service/v0/service.go @@ -14,7 +14,7 @@ import ( dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" dbServiceTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/service/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" @@ -52,11 +52,17 @@ func Add(c *gin.Context) { } // status check for group - if !(*result.User.Group.Status == 1 && *result.User.Group.ExpiredStatus == 0 && *result.User.Group.Pass) { + if !(*result.User.Group.ExpiredStatus == 0 && *result.User.Group.Pass) { c.JSON(http.StatusUnauthorized, common.Error{Error: "error: failed group status"}) return } + // add_allow check for group + if !(*result.User.Group.AddAllow) { + c.JSON(http.StatusForbidden, common.Error{Error: "error: failed group add_allow status"}) + return + } + var grpIP []core.IP = nil resultServiceTemplate := dbServiceTemplate.Get(serviceTemplate.ID, &core.ServiceTemplate{Model: gorm.Model{ID: input.ServiceTemplateID}}) @@ -113,11 +119,6 @@ func Add(c *gin.Context) { } } - if *resultServiceTemplate.Services[0].NeedRoute && input.RouteV4 == "" && input.RouteV6 == "" { - c.JSON(http.StatusBadRequest, common.Error{Error: "no data: Route Information"}) - return - } - resultNetwork := dbService.Get(service.SearchNewNumber, &core.Service{GroupID: result.User.Group.ID}) if resultNetwork.Err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: resultNetwork.Err.Error()}) @@ -146,19 +147,16 @@ func Add(c *gin.Context) { PostCode: input.Postcode, Address: input.Address, AddressEn: input.AddressEn, - RouteV4: input.RouteV4, - RouteV6: input.RouteV6, AveUpstream: input.AveUpstream, MaxUpstream: input.MaxUpstream, AveDownstream: input.AveDownstream, MaxDownstream: input.MaxDownstream, ASN: &[]uint{input.ASN}[0], - Fee: &[]uint{0}[0], IP: grpIP, JPNICAdmin: input.JPNICAdmin, JPNICTech: input.JPNICTech, - Open: &[]bool{false}[0], - Lock: &[]bool{true}[0], + Enable: &[]bool{true}[0], + Pass: &[]bool{false}[0], AddAllow: &[]bool{true}[0], }) if err != nil { @@ -176,8 +174,10 @@ func Add(c *gin.Context) { // ---------ここまで処理が通っている場合、DBへの書き込みにすべて成功している // GroupのStatusをAfterStatusにする - if err = dbGroup.Update(group.UpdateStatus, core.Group{Model: gorm.Model{ID: result.User.Group.ID}, - Status: &[]uint{2}[0]}); err != nil { + if err = dbGroup.Update(group.UpdateAll, core.Group{ + Model: gorm.Model{ID: result.User.Group.ID}, + AddAllow: &[]bool{false}[0], + }); err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } @@ -231,10 +231,6 @@ func Update(c *gin.Context) { c.JSON(http.StatusInternalServerError, common.Error{Error: "Authentication failure"}) return } - if *resultNetwork.Service[0].Lock { - c.JSON(http.StatusInternalServerError, common.Error{Error: "this network is locked..."}) - return - } replace := replaceService(resultNetwork.Service[0], input) diff --git a/pkg/api/core/group/service/v0/slack.go b/pkg/api/core/group/service/v0/slack.go index d24df806..ba11b714 100644 --- a/pkg/api/core/group/service/v0/slack.go +++ b/pkg/api/core/group/service/v0/slack.go @@ -3,39 +3,90 @@ package v0 import ( "github.com/ashwanthkumar/slack-go-webhook" "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/group" serviceTemplate "github.com/homenoc/dsbd-backend/pkg/api/core/template/service" "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" + dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" dbServiceTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/service/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "strconv" ) -func noticeSlackAdmin(before, after core.Service) { - // 審査ステータスのSlack通知 +func getGroupInfo(groupID uint) core.Group { + result := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: groupID}}) + return result.Group[0] +} + +func noticeSlackAdd(groupID int, serviceCode, serviceCodeComment string) { + grpInfo := getGroupInfo(uint(groupID)) attachment := slack.Attachment{} - attachment.AddField(slack.Field{Title: "Title", Value: "Service情報の更新"}). + attachment.AddField(slack.Field{Title: "Title", Value: "Service情報登録(管理者実行)"}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). - AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + "-" + before.Group.Org}). - AddField(slack.Field{Title: "更新状況", Value: changeText(before, after)}) + AddField(slack.Field{Title: "Group", Value: strconv.Itoa(groupID) + "-" + grpInfo.Org}). + AddField(slack.Field{Title: "サービスコード(新規発番)", Value: serviceCode}). + AddField(slack.Field{Title: "サービスコード(補足情報)", Value: serviceCodeComment}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } -func noticeSlackJPNICAdminAdmin(before, after core.Service) { - // 審査ステータスのSlack通知 +func noticeSlackAddJPNICByAdmin(serviceID int, input core.JPNICAdmin) { attachment := slack.Attachment{} - attachment.AddField(slack.Field{Title: "Title", Value: "Service情報の更新"}). + attachment.AddField(slack.Field{Title: "Title", Value: "JPNIC管理者連絡窓口の追加"}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). - AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + "-" + before.Group.Org}). - AddField(slack.Field{Title: "更新状況", Value: changeText(before, after)}) + AddField(slack.Field{Title: "Service", Value: strconv.Itoa(serviceID)}). + AddField(slack.Field{Title: "Name", Value: input.Name + " (" + input.NameEn + ")"}). + AddField(slack.Field{Title: "Org", Value: input.Org + " (" + input.OrgEn + ")"}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } -func noticeSlackJPNICTechAdmin(before, after core.Service) { +func noticeSlackAddJPNICTech(serviceID int, input core.JPNICTech) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "JPNIC技術連絡担当者の追加"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "Service", Value: strconv.Itoa(serviceID)}). + AddField(slack.Field{Title: "Name", Value: input.Name + " (" + input.NameEn + ")"}). + AddField(slack.Field{Title: "Org", Value: input.Org + " (" + input.OrgEn + ")"}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackAddIP(serviceID int, inputName string) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} + attachment.AddField(slack.Field{Title: "Title", Value: "IPの追加"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "Service", Value: strconv.Itoa(serviceID)}). + AddField(slack.Field{Title: "Name", Value: inputName}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackAddPlan(ipID int, input core.Plan) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "Planの追加"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "IP", Value: strconv.Itoa(ipID)}). + AddField(slack.Field{Title: "Name", Value: input.Name}). + AddField(slack.Field{Title: "Plan", Value: strconv.Itoa(int(input.After)) + "/" + + strconv.Itoa(int(input.HalfYear)) + "/" + strconv.Itoa(int(input.OneYear))}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackDelete(str string, id uint) { + color := "warning" + attachment := slack.Attachment{Color: &color} + + attachment.AddField(slack.Field{Title: "Title", Value: str + "の削除"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "削除処理", Value: "ID: " + strconv.Itoa(int(id))}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackUpdate(before, after core.Service) { + attachment := slack.Attachment{} + attachment.AddField(slack.Field{Title: "Title", Value: "Service情報の更新"}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + "-" + before.Group.Org}). @@ -43,11 +94,51 @@ func noticeSlackJPNICTechAdmin(before, after core.Service) { notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } +func noticeSlackUpdateJPNICByAdmin(before, after core.JPNICAdmin) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "JPNIC管理者連絡窓口の更新"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "JPNICAdmin", Value: strconv.Itoa(int(before.ID))}). + AddField(slack.Field{Title: "更新状況", Value: changeTextJPNICByAdmin(before, after)}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackUpdateJPNICTech(before, after core.JPNICTech) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "JPNIC技術連絡担当者の更新"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "JPNICTech", Value: strconv.Itoa(int(before.ID))}). + AddField(slack.Field{Title: "更新状況", Value: changeTextJPNICTech(before, after)}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackUpdateIP(before, after core.IP) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "IPの更新"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "IP", Value: strconv.Itoa(int(before.ID))}). + AddField(slack.Field{Title: "更新状況", Value: changeTextIP(before, after)}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackUpdatePlan(before, after core.Plan) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "Planの更新"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "Plan", Value: strconv.Itoa(int(before.ID))}). + AddField(slack.Field{Title: "更新状況", Value: changeTextPlan(before, after)}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + func changeText(before, after core.Service) string { data := "" - if after.Open != nil { - if *before.Open != *after.Open { - if *after.Open { + if after.Pass != nil { + if *before.Pass != *after.Pass { + if *after.Pass { data += "開通: 未開通 => 開通済み\n" } else { data += "開通: 開通 => 未開通\n" @@ -55,16 +146,6 @@ func changeText(before, after core.Service) string { } } - if after.Lock != nil { - if *before.Lock != *after.Lock { - if !*after.Lock { - data += "ユーザ変更: 禁止 => 許可\n" - } else { - data += "ユーザ変更: 許可 => 禁止\n" - } - } - } - if after.AddAllow != nil { if *before.AddAllow != *after.AddAllow { if *after.AddAllow { @@ -82,28 +163,22 @@ func changeText(before, after core.Service) string { } } - if after.Fee != nil { - if *before.Fee != *after.Fee { - data += "Fee: " + strconv.Itoa(int(*before.Fee)) + " => " + strconv.Itoa(int(*after.Fee)) + "\n" - } - } - - if before.AveDownstream != after.AveDownstream && after.AveDownstream != 0 { + if before.AveDownstream != after.AveDownstream { data += "平均ダウンロード帯域: " + strconv.Itoa(int(before.AveDownstream)) + "Kbps => " + strconv.Itoa(int(after.AveDownstream)) + "Kbps\n" } - if before.MaxDownstream != after.MaxDownstream && after.MaxDownstream != 0 { + if before.MaxDownstream != after.MaxDownstream { data += "最大ダウンロード帯域: " + strconv.Itoa(int(before.MaxDownstream)) + "Kbps => " + strconv.Itoa(int(after.MaxDownstream)) + "Kbps\n" } - if before.AveUpstream != after.AveUpstream && after.AveUpstream != 0 { + if before.AveUpstream != after.AveUpstream { data += "平均アップロード帯域: " + strconv.Itoa(int(before.AveUpstream)) + "Kbps => " + strconv.Itoa(int(after.AveUpstream)) + "Kbps\n" } - if before.MaxUpstream != after.MaxUpstream && after.MaxUpstream != 0 { + if before.MaxUpstream != after.MaxUpstream { data += "最大アップロード帯域: " + strconv.Itoa(int(before.MaxUpstream)) + "Kbps => " + strconv.Itoa(int(after.MaxUpstream)) + "Kbps\n" } @@ -114,42 +189,206 @@ func changeText(before, after core.Service) string { } } - if after.RouteV4 != "" && after.RouteV4 != before.RouteV4 { - data += "広報方法(v4): " + before.RouteV4 + "=>" + after.RouteV4 + "\n" + if before.V4Name != after.V4Name { + data += "ネットワーク名(v4): " + before.V4Name + "=>" + after.V4Name + "\n" } - if after.RouteV6 != "" && after.RouteV6 != before.RouteV6 { - data += "広報方法(v6): " + before.RouteV6 + "=>" + after.RouteV6 + "\n" + if before.V6Name != after.V6Name { + data += "ネットワーク名(v6): " + before.V6Name + "=>" + after.V6Name + "\n" } - if after.V4Name != "" && after.V4Name != before.V4Name { - data += "ネットワーク名(v4): " + before.V4Name + "=>" + after.V4Name + "\n" + if before.Org != after.Org { + data += "Org: " + before.Org + "=>" + after.Org + "\n" } - if after.V6Name != "" && after.V6Name != before.V6Name { - data += "ネットワーク名(v6): " + before.V6Name + "=>" + after.V6Name + "\n" + if before.OrgEn != after.OrgEn { + data += "Org(En): " + before.OrgEn + "=>" + after.OrgEn + "\n" + } + + if before.PostCode != after.PostCode { + data += "PostCode: " + before.PostCode + "=>" + after.PostCode + "\n" + } + + if before.Address != after.Address { + data += "Address: " + before.Address + "=>" + after.Address + "\n" + } + + if before.AddressEn != after.AddressEn { + data += "Address(En): " + before.AddressEn + "=>" + after.AddressEn + "\n" + } + + return data +} + +func changeTextJPNICByAdmin(before, after core.JPNICAdmin) string { + data := "" + + if before.JPNICHandle != after.JPNICHandle { + data += "JPNICHandle: " + before.JPNICHandle + "=>" + after.JPNICHandle + "\n" + } + + if before.Name != after.Name { + data += "Name: " + before.Name + "=>" + after.Name + "\n" + } + + if before.NameEn != after.NameEn { + data += "Name(En): " + before.NameEn + "=>" + after.NameEn + "\n" + } + + if before.Mail != after.Mail { + data += "Mail: " + before.Mail + "=>" + after.Mail + "\n" + } + + if before.Org != after.Org { + data += "Org: " + before.Org + "=>" + after.Org + "\n" + } + + if before.OrgEn != after.OrgEn { + data += "Org(En): " + before.OrgEn + "=>" + after.OrgEn + "\n" + } + + if before.PostCode != after.PostCode { + data += "PostCode: " + before.PostCode + "=>" + after.PostCode + "\n" + } + + if before.Address != after.Address { + data += "Address: " + before.Address + "=>" + after.Address + "\n" + } + + if before.AddressEn != after.AddressEn { + data += "Address(En): " + before.AddressEn + "=>" + after.AddressEn + "\n" + } + + if before.Dept != after.Dept { + data += "Dept: " + before.Dept + "=>" + after.Dept + "\n" + } + + if before.DeptEn != after.DeptEn { + data += "Dept(En): " + before.DeptEn + "=>" + after.DeptEn + "\n" + } + + if before.Tel != after.Tel { + data += "Tel: " + before.Tel + "=>" + after.Tel + "\n" + } + + if before.Fax != after.Fax { + data += "Fax: " + before.Fax + "=>" + after.Fax + "\n" + } + + if before.Country != after.Country { + data += "Country: " + before.Country + "=>" + after.Country + "\n" + } + + return data +} + +func changeTextJPNICTech(before, after core.JPNICTech) string { + data := "" + + if before.JPNICHandle != after.JPNICHandle { + data += "JPNICHandle: " + before.JPNICHandle + "=>" + after.JPNICHandle + "\n" + } + + if before.Name != after.Name { + data += "Name: " + before.Name + "=>" + after.Name + "\n" + } + + if before.NameEn != after.NameEn { + data += "Name(En): " + before.NameEn + "=>" + after.NameEn + "\n" } - if after.Org != "" && after.Org != before.Org { + if before.Mail != after.Mail { + data += "Mail: " + before.Mail + "=>" + after.Mail + "\n" + } + + if before.Org != after.Org { data += "Org: " + before.Org + "=>" + after.Org + "\n" } - if after.OrgEn != "" && after.OrgEn != before.OrgEn { + if before.OrgEn != after.OrgEn { data += "Org(En): " + before.OrgEn + "=>" + after.OrgEn + "\n" } - if after.PostCode != "" && after.PostCode != before.PostCode { + if before.PostCode != after.PostCode { data += "PostCode: " + before.PostCode + "=>" + after.PostCode + "\n" } - if after.Address != "" && after.Address != before.Address { + if before.Address != after.Address { data += "Address: " + before.Address + "=>" + after.Address + "\n" } - if after.AddressEn != "" && after.AddressEn != before.AddressEn { + if before.AddressEn != after.AddressEn { data += "Address(En): " + before.AddressEn + "=>" + after.AddressEn + "\n" } + if before.Dept != after.Dept { + data += "Dept: " + before.Dept + "=>" + after.Dept + "\n" + } + + if before.DeptEn != after.DeptEn { + data += "Dept(En): " + before.DeptEn + "=>" + after.DeptEn + "\n" + } + + if before.Tel != after.Tel { + data += "Tel: " + before.Tel + "=>" + after.Tel + "\n" + } + + if before.Fax != after.Fax { + data += "Fax: " + before.Fax + "=>" + after.Fax + "\n" + } + + if before.Country != after.Country { + data += "Country: " + before.Country + "=>" + after.Country + "\n" + } + + return data +} + +func changeTextIP(before, after core.IP) string { + data := "" + + if before.Name != after.Name { + data += "Name: " + before.Name + "=>" + after.Name + "\n" + } + + if before.IP != after.IP { + data += "IP: " + before.IP + "=>" + after.IP + "\n" + } + + if before.UseCase != after.UseCase { + data += "UseCase: " + before.UseCase + "=>" + after.UseCase + "\n" + } + + if *before.Open != *after.Open { + if *after.Open { + data += "Open: 未開通 => 開通\n" + } else { + data += "Open: 開通 => 未開通\n" + } + } + + return data +} + +func changeTextPlan(before, after core.Plan) string { + data := "" + + if before.Name != after.Name { + data += "Name: " + before.Name + "=>" + after.Name + "\n" + } + + if before.After != after.After { + data += "直後: " + strconv.Itoa(int(before.After)) + "=>" + strconv.Itoa(int(after.After)) + "\n" + } + + if before.HalfYear != after.HalfYear { + data += "半年後: " + strconv.Itoa(int(before.HalfYear)) + "=>" + strconv.Itoa(int(after.HalfYear)) + "\n" + } + + if before.OneYear != after.OneYear { + data += "1年後: " + strconv.Itoa(int(before.OneYear)) + "=>" + strconv.Itoa(int(after.OneYear)) + "\n" + } + return data } diff --git a/pkg/api/core/group/service/v0/update.go b/pkg/api/core/group/service/v0/update.go index 492afc24..993e37b2 100644 --- a/pkg/api/core/group/service/v0/update.go +++ b/pkg/api/core/group/service/v0/update.go @@ -30,19 +30,9 @@ func replaceService(replace, input core.Service) core.Service { replace.AddressEn = input.AddressEn } - //Route(V4) - if input.RouteV4 != "" { - replace.RouteV4 = input.RouteV4 - } - - //Route(V4) - if input.RouteV6 != "" { - replace.RouteV6 = input.RouteV6 - } - - //Lock - if input.Lock != replace.Lock { - replace.Lock = input.Lock + //Open + if input.Pass != replace.Pass { + replace.Pass = input.Pass } ////V4 diff --git a/pkg/api/core/group/v0/admin.go b/pkg/api/core/group/v0/admin.go index 3be2de5d..f62e84f6 100644 --- a/pkg/api/core/group/v0/admin.go +++ b/pkg/api/core/group/v0/admin.go @@ -7,14 +7,17 @@ import ( auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/group" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" - "github.com/jinzhu/gorm" + "github.com/stripe/stripe-go/v72" + "github.com/stripe/stripe-go/v72/sub" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.Group resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -37,7 +40,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, group.ResultAdmin{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -57,7 +60,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, group.ResultAdmin{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { // ID取得 id, err := strconv.Atoi(c.Param("id")) if err != nil { @@ -92,9 +95,15 @@ func UpdateAdmin(c *gin.Context) { return } - noticeSlackAdmin(tmp.Group[0], input) + noticeSlackByAdmin(tmp.Group[0], input) input.ID = uint(id) + if input.PaymentCouponTemplateID != nil && *input.PaymentCouponTemplateID == 0 { + input.PaymentCouponTemplateID = nil + } + if input.PaymentMembershipTemplateID != nil && *input.PaymentMembershipTemplateID == 0 { + input.PaymentMembershipTemplateID = nil + } if err = dbGroup.Update(group.UpdateAll, input); err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) @@ -103,7 +112,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, group.ResultAdmin{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -126,7 +135,7 @@ func GetAdmin(c *gin.Context) { }) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -139,3 +148,58 @@ func GetAllAdmin(c *gin.Context) { c.JSON(http.StatusOK, group.ResultAdminAll{Group: result.Group}) } } + +func CancelSubscription(c *gin.Context) { + // ID取得 + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + // serviceIDが0の時エラー処理 + if id == 0 { + c.JSON(http.StatusBadRequest, common.Error{Error: fmt.Sprintf("This id is wrong... ")}) + return + } + + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + resultGroup := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: uint(id)}}) + if resultGroup.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: resultGroup.Err.Error()}) + return + } + + if resultGroup.Group[0].StripeSubscriptionID == nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "Subscription ID is not exists."}) + return + } + + noticeSlackCancelSubscriptionByAdmin(resultGroup.Group[0]) + + stripe.Key = config.Conf.Stripe.SecretKey + + _, err = sub.Cancel(*resultGroup.Group[0].StripeSubscriptionID, nil) + if err != nil { + log.Printf("pi.New: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + err = dbGroup.Update(group.UpdateAll, core.Group{ + StripeSubscriptionID: &[]string{""}[0], + PaymentMembershipTemplateID: &[]uint{0}[0], + }) + if err != nil { + log.Printf("Error: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/group/v0/group.go b/pkg/api/core/group/v0/group.go index b8fd7e5f..baf9ced6 100644 --- a/pkg/api/core/group/v0/group.go +++ b/pkg/api/core/group/v0/group.go @@ -7,13 +7,14 @@ import ( auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/group" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" "github.com/homenoc/dsbd-backend/pkg/api/core/user" dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" - "github.com/jinzhu/gorm" + "github.com/stripe/stripe-go/v72" + "github.com/stripe/stripe-go/v72/customer" + "gorm.io/gorm" "log" "net/http" "strconv" @@ -45,7 +46,7 @@ func Add(c *gin.Context) { return } - if userResult.User.GroupID != 0 { + if userResult.User.GroupID != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: "error: You can't create new group"}) return } @@ -61,29 +62,43 @@ func Add(c *gin.Context) { studentExpired = &tmpStudentExpired } - result, err := dbGroup.Create(&core.Group{ - Agree: &[]bool{*input.Agree}[0], - Question: input.Question, - Org: input.Org, - OrgEn: input.OrgEn, - PostCode: input.PostCode, - Address: input.Address, - AddressEn: input.AddressEn, - Tel: input.Tel, - Country: input.Country, - Status: &[]uint{1}[0], - ExpiredStatus: &[]uint{0}[0], - Contract: input.Contract, - Student: input.Student, - StudentExpired: studentExpired, - Open: &[]bool{false}[0], - Pass: &[]bool{false}[0], - Lock: &[]bool{true}[0], - }) + // added customer (stripe) + stripe.Key = config.Conf.Stripe.SecretKey + + params := &stripe.CustomerParams{ + Description: stripe.String("Org: " + input.Org + "(" + input.OrgEn + ")"), + } + cus, err := customer.New(params) + if err != nil { + log.Println("Error: " + err.Error()) + } + + groupData := core.Group{ + Agree: &[]bool{*input.Agree}[0], + StripeCustomerID: &cus.ID, + Question: input.Question, + Org: input.Org, + OrgEn: input.OrgEn, + PostCode: input.PostCode, + Address: input.Address, + AddressEn: input.AddressEn, + Tel: input.Tel, + Country: input.Country, + ExpiredStatus: &[]uint{0}[0], + Contract: input.Contract, + Student: input.Student, + MemberExpired: studentExpired, + Open: &[]bool{false}[0], + Pass: &[]bool{false}[0], + AddAllow: &[]bool{true}[0], + } + + _, err = dbGroup.Create(&groupData) if err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } + attachment := slack.Attachment{} attachment.AddField(slack.Field{Title: "Title", Value: "グループ登録"}). AddField(slack.Field{Title: "Question", Value: input.Question}). @@ -94,275 +109,10 @@ func Add(c *gin.Context) { notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) - if err = dbUser.Update(user.UpdateGID, &core.User{Model: gorm.Model{ID: userResult.User.ID}, GroupID: result.Model.ID}); err != nil { - log.Println(dbGroup.Delete(&core.Group{Model: gorm.Model{ID: result.ID}})) + if err = dbUser.Update(user.UpdateGID, &core.User{Model: gorm.Model{ID: userResult.User.ID}, GroupID: &groupData.ID}); err != nil { + log.Println(dbGroup.Delete(&core.Group{Model: gorm.Model{ID: groupData.ID}})) c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) } else { c.JSON(http.StatusOK, common.Result{}) } } - -func Update(c *gin.Context) { - var input group.Input - - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - err := c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - authResult := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) - if authResult.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: authResult.Err.Error()}) - return - } - - if authResult.User.Level > 2 { - c.JSON(http.StatusUnauthorized, common.Error{Error: "error: failed user level"}) - return - } - if *authResult.User.Group.Lock { - c.JSON(http.StatusUnauthorized, common.Error{Error: "error: This group is locked"}) - return - } - - noticeSlack(authResult.User, *authResult.User.Group, input) - - if err = dbGroup.Update(group.UpdateAll, *replace(authResult.User.Group, input)); err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: authResult.Err.Error()}) - return - } - - c.JSON(http.StatusOK, common.Result{}) - -} - -func Get(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - result := auth.GroupAuthentication(1, core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) - return - } - - resultUser := dbUser.Get(user.ID, &core.User{Model: gorm.Model{ID: result.User.ID}}) - if resultUser.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultUser.Err.Error()}) - return - } - - var responseUser []user.User - if result.User.Level == 1 || result.User.Level == 2 { - for _, tmpUser := range resultUser.User { - responseUser = append(responseUser, user.User{ - ID: tmpUser.ID, - Name: tmpUser.Name, - NameEn: tmpUser.NameEn, - Email: tmpUser.Email, - Level: tmpUser.Level, - ExpiredStatus: *tmpUser.ExpiredStatus, - MailVerify: tmpUser.MailVerify, - }) - } - } else { - responseUser = []user.User{ - { - ID: result.User.ID, - Name: result.User.Name, - NameEn: result.User.NameEn, - Email: result.User.Email, - Level: result.User.Level, - ExpiredStatus: *result.User.ExpiredStatus, - MailVerify: result.User.MailVerify, - }, - } - } - - c.JSON(http.StatusOK, group.Result{Group: group.Group{ - ID: result.User.Group.ID, - Agree: result.User.Group.Agree, - Question: result.User.Group.Question, - Org: result.User.Group.Org, - OrgEn: result.User.Group.OrgEn, - PostCode: result.User.Group.PostCode, - Address: result.User.Group.Address, - AddressEn: result.User.Group.AddressEn, - Tel: result.User.Group.Tel, - Country: result.User.Group.Country, - Status: *result.User.Group.Status, - Contract: result.User.Group.Contract, - Student: result.User.Group.Student, - Open: result.User.Group.Open, - Pass: result.User.Group.Pass, - Lock: result.User.Group.Lock, - ExpiredStatus: *result.User.Group.ExpiredStatus, - //User: users, - }}) -} - -func GetAll(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) - return - } - - if result.User.Level > 2 { - c.JSON(http.StatusUnauthorized, common.Error{Error: "You don't have authority this operation"}) - return - } - - resultGroup := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: result.User.GroupID}}) - if resultGroup.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: result.Err.Error()}) - return - } - - var users []user.User - var services []service.Service - - for _, tmpUser := range resultGroup.Group[0].Users { - users = append(users, user.User{ - ID: tmpUser.ID, - Name: tmpUser.Name, - NameEn: tmpUser.NameEn, - Email: tmpUser.Email, - Level: tmpUser.Level, - ExpiredStatus: *tmpUser.ExpiredStatus, - MailVerify: tmpUser.MailVerify, - }) - } - - for _, tmpService := range resultGroup.Group[0].Services { - var tmpConnections *[]connection.Connection = nil - var tmpJPNICAdmin *service.JPNIC = nil - var tmpJPNICTech *[]service.JPNIC = nil - - if tmpService.JPNICAdmin.ID == 0 { - tmpJPNICAdmin = &service.JPNIC{ - ID: tmpService.JPNICAdmin.ID, - JPNICHandle: tmpService.JPNICAdmin.JPNICHandle, - Name: tmpService.JPNICAdmin.Name, - NameEn: tmpService.JPNICAdmin.NameEn, - Org: tmpService.JPNICAdmin.Org, - OrgEn: tmpService.JPNICAdmin.OrgEn, - PostCode: tmpService.JPNICAdmin.PostCode, - Address: tmpService.JPNICAdmin.Address, - AddressEn: tmpService.JPNICAdmin.AddressEn, - Dept: tmpService.JPNICAdmin.Dept, - DeptEn: tmpService.JPNICAdmin.DeptEn, - Tel: tmpService.JPNICAdmin.Tel, - Fax: tmpService.JPNICAdmin.Fax, - Country: tmpService.JPNICAdmin.Country, - } - } - - if tmpService.JPNICTech != nil || len(tmpService.JPNICTech) != 0 { - for _, tmpServiceJPNICTech := range tmpService.JPNICTech { - *tmpJPNICTech = append(*tmpJPNICTech, service.JPNIC{ - ID: tmpServiceJPNICTech.ID, - JPNICHandle: tmpServiceJPNICTech.JPNICHandle, - Name: tmpServiceJPNICTech.Name, - NameEn: tmpServiceJPNICTech.NameEn, - Org: tmpServiceJPNICTech.Org, - OrgEn: tmpServiceJPNICTech.OrgEn, - PostCode: tmpServiceJPNICTech.PostCode, - Address: tmpServiceJPNICTech.Address, - AddressEn: tmpServiceJPNICTech.AddressEn, - Dept: tmpServiceJPNICTech.Dept, - DeptEn: tmpServiceJPNICTech.DeptEn, - Tel: tmpServiceJPNICTech.Tel, - Fax: tmpServiceJPNICTech.Fax, - Country: tmpServiceJPNICTech.Country, - }) - } - } - - if tmpConnections != nil { - for _, tmpConnection := range tmpService.Connection { - *tmpConnections = append(*tmpConnections, connection.Connection{ - ID: tmpConnection.ID, - BGPRouterID: tmpConnection.BGPRouterID, - BGPRouterName: tmpConnection.BGPRouter.HostName, - TunnelEndPointRouterIPID: tmpConnection.TunnelEndPointRouterIPID, - TunnelEndPointRouterIPIDName: tmpConnection.TunnelEndPointRouterIP.TunnelEndPointRouter.HostName, - ConnectionTemplateID: tmpConnection.ConnectionTemplateID, - ConnectionTemplateName: tmpConnection.ConnectionTemplate.Name, - ConnectionComment: tmpConnection.ConnectionComment, - ConnectionNumber: tmpConnection.ConnectionNumber, - NTTTemplateID: tmpConnection.NTTTemplateID, - NTTTemplateName: tmpConnection.NTTTemplate.Name, - NOCID: tmpConnection.NOCID, - NOCName: tmpConnection.NOC.Name, - TermIP: tmpConnection.TermIP, - Monitor: tmpConnection.Monitor, - Address: tmpConnection.Address, - LinkV4Our: tmpConnection.LinkV4Our, - LinkV4Your: tmpConnection.LinkV4Your, - LinkV6Our: tmpConnection.LinkV6Our, - LinkV6Your: tmpConnection.LinkV6Your, - Open: tmpConnection.Open, - Lock: tmpConnection.Lock, - }) - } - } - - services = append(services, service.Service{ - ID: tmpService.ID, - GroupID: tmpService.ID, - ServiceTemplateID: tmpService.ServiceTemplateID, - ServiceTemplateName: tmpService.ServiceTemplate.Name, - ServiceComment: tmpService.ServiceComment, - ServiceNumber: tmpService.ServiceNumber, - Org: tmpService.Org, - OrgEn: tmpService.OrgEn, - PostCode: tmpService.PostCode, - Address: tmpService.Address, - AddressEn: tmpService.AddressEn, - ASN: tmpService.ASN, - RouteV4: tmpService.RouteV4, - RouteV6: tmpService.RouteV6, - V4Name: tmpService.V4Name, - V6Name: tmpService.V6Name, - AveUpstream: tmpService.AveUpstream, - MaxUpstream: tmpService.MaxUpstream, - AveDownstream: tmpService.AveDownstream, - MaxDownstream: tmpService.MaxDownstream, - MaxBandWidthAS: tmpService.MaxBandWidthAS, - Fee: tmpService.Fee, - IP: tmpService.IP, - Connections: tmpConnections, - JPNICAdminID: tmpService.JPNICAdminID, - JPNICAdmin: tmpJPNICAdmin, - JPNICTech: tmpJPNICTech, - Open: tmpService.Open, - AddAllow: tmpService.AddAllow, - Lock: tmpService.Lock, - }) - } - - c.JSON(http.StatusOK, group.Result{Group: group.Group{ - ID: resultGroup.Group[0].ID, - Agree: resultGroup.Group[0].Agree, - Question: resultGroup.Group[0].Question, - Org: resultGroup.Group[0].Org, - Status: *resultGroup.Group[0].Status, - Contract: resultGroup.Group[0].Contract, - Student: resultGroup.Group[0].Student, - Open: resultGroup.Group[0].Open, - Pass: resultGroup.Group[0].Pass, - Lock: resultGroup.Group[0].Lock, - ExpiredStatus: *resultGroup.Group[0].ExpiredStatus, - User: users, - Service: &services, - }}) -} diff --git a/pkg/api/core/group/v0/slack.go b/pkg/api/core/group/v0/slack.go index bb9301ac..92eff430 100644 --- a/pkg/api/core/group/v0/slack.go +++ b/pkg/api/core/group/v0/slack.go @@ -19,17 +19,28 @@ func noticeSlack(loginUser core.User, before core.Group, after group.Input) { notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } -func noticeSlackAdmin(before, after core.Group) { +func noticeSlackByAdmin(before, after core.Group) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} attachment.AddField(slack.Field{Title: "Title", Value: "Group情報の更新"}). AddField(slack.Field{Title: "申請者", Value: "管理者"}). AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(before.ID)) + ":" + before.Org}). - AddField(slack.Field{Title: "更新状況", Value: changeTextAdmin(before, after)}) + AddField(slack.Field{Title: "更新状況", Value: changeTextByAdmin(before, after)}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } +func noticeSlackCancelSubscriptionByAdmin(group core.Group) { + // 審査ステータスのSlack通知 + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "Cancel Subscription"}). + AddField(slack.Field{Title: "申請者", Value: "管理者"}). + AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(group.ID)) + ":" + group.Org}) + + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: false}) +} + func changeText(before core.Group, after group.Input) string { data := "" @@ -64,7 +75,7 @@ func changeText(before core.Group, after group.Input) string { return data } -func changeTextAdmin(before, after core.Group) string { +func changeTextByAdmin(before, after core.Group) string { data := "" if after.Open != nil { if *before.Open != *after.Open { @@ -86,16 +97,6 @@ func changeTextAdmin(before, after core.Group) string { } } - if after.Lock != nil { - if !*before.Lock != *after.Lock { - if *after.Lock { - data += "ユーザ変更: 禁止 => 許可\n" - } else { - data += "ユーザ変更: 許可 => 禁止\n" - } - } - } - if after.ExpiredStatus != nil { if *before.ExpiredStatus != *after.ExpiredStatus { data += "ExpiredStatus: " + expiredStatusText(*before.ExpiredStatus) + " => " + @@ -103,12 +104,6 @@ func changeTextAdmin(before, after core.Group) string { } } - if after.Status != nil { - if *before.Status != *after.Status { - data += "ExpiredStatus: " + statusText(*before.Status) + " => " + statusText(*after.Status) + "\n" - } - } - if after.Org != "" && after.Org != before.Org { data += "Org: " + before.Org + "=>" + after.Org + "\n" } diff --git a/pkg/api/core/group/v0/update.go b/pkg/api/core/group/v0/update.go index 3a20693a..4a7caa72 100644 --- a/pkg/api/core/group/v0/update.go +++ b/pkg/api/core/group/v0/update.go @@ -35,19 +35,10 @@ func updateAdminGroup(input, replace core.Group) (core.Group, error) { replace.Country = input.Country } - // uint boolean - // Lock - if input.Lock != replace.Lock { - replace.Lock = input.Lock - } // Pass if input.Pass != replace.Pass { replace.Pass = input.Pass } - // Status - if input.Status != replace.Status { - replace.Status = input.Status - } // ExpiredStatus if input.ExpiredStatus != replace.ExpiredStatus { replace.ExpiredStatus = input.ExpiredStatus diff --git a/pkg/api/core/interface.go b/pkg/api/core/interface.go index d9e5ee5c..18924840 100644 --- a/pkg/api/core/interface.go +++ b/pkg/api/core/interface.go @@ -1,16 +1,18 @@ package core import ( - "github.com/jinzhu/gorm" + "gorm.io/gorm" "time" ) type User struct { gorm.Model Tokens []*Token `json:"tokens"` - Notice []*Notice `json:"notice"` + Notice []*Notice `json:"notice" gorm:"many2many:user_notice;"` + Ticket []Ticket `json:"tickets"` Group *Group `json:"group"` - GroupID uint `json:"group_id"` + Payment []Payment `json:"payment_membership"` + GroupID *uint `json:"group_id"` Name string `json:"name"` NameEn string `json:"name_en"` Email string `json:"email"` @@ -21,33 +23,59 @@ type User struct { MailToken string `json:"mail_token"` } +type Payment struct { + gorm.Model + User *User `json:"user"` + Group *Group `json:"group"` + UserID uint `json:"user_id"` + GroupID *uint `json:"group_id"` + PaymentIntentID string `json:"payment_intent_id"` + IsMembership *bool `json:"is_membership"` + Paid *bool `json:"paid"` + Refund *bool `json:"refund"` + Fee uint `json:"fee"` + Comment string `json:"comment"` +} + type Group struct { gorm.Model - Users []User `json:"users"` - Services []Service `json:"services"` - Tickets []Ticket `json:"tickets"` - Notice []*Notice `json:"notice"` - JPNICAdmin []*JPNICAdmin `json:"jpnic_admin"` - JPNICTech []*JPNICTech `json:"jpnic_tech"` - Agree *bool `json:"agree"` - Question string `json:"question" gorm:"size:65535"` - Org string `json:"org"` - OrgEn string `json:"org_en"` - PostCode string `json:"postcode"` - Address string `json:"address"` - AddressEn string `json:"address_en"` - Tel string `json:"tel"` - Country string `json:"country"` - Status *uint `json:"status"` - Contract string `json:"contract"` - Student *bool `json:"student"` - StudentExpired *time.Time `json:"student_expired"` - Fee *uint `json:"fee"` - Comment string `json:"comment"` - Open *bool `json:"open"` - Pass *bool `json:"pass"` - Lock *bool `json:"lock"` - ExpiredStatus *uint `json:"expired_status"` + Users []User `json:"users"` + Payment []Payment `json:"payment_membership"` + Services []Service `json:"services"` + Tickets []Ticket `json:"tickets"` + Memos []Memo `json:"memos"` + PaymentMembershipTemplateID *uint `json:"payment_membership_template_id"` + PaymentCouponTemplateID *uint `json:"payment_coupon_template_id"` + PaymentMembershipTemplate PaymentMembershipTemplate `json:"payment_membership_template"` + PaymentCouponTemplate PaymentCouponTemplate `json:"payment_coupon_template"` + StripeCustomerID *string `json:"stripe_customer_id"` + StripeSubscriptionID *string `json:"stripe_subscription_id"` + Agree *bool `json:"agree"` + Question string `json:"question" gorm:"size:10000"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + Tel string `json:"tel"` + Country string `json:"country"` + Contract string `json:"contract"` + MemberExpired *time.Time `json:"member_expired"` + Student *bool `json:"student"` + Comment string `json:"comment"` + Open *bool `json:"open"` + Pass *bool `json:"pass"` + ExpiredStatus *uint `json:"expired_status"` + AddAllow *bool `json:"add_allow"` +} + +// Memo Type 1:Important(Red) 2:Comment1(Blue) 3:Comment2(Gray) +type Memo struct { + gorm.Model + GroupID uint `json:"group_id"` + Type uint `json:"type"` + Title string `json:"title" gorm:"size:10"` + Message string `json:"message"` } type Service struct { @@ -63,23 +91,21 @@ type Service struct { Address string `json:"address"` AddressEn string `json:"address_en"` ASN *uint `json:"asn"` - RouteV4 string `json:"route_v4"` - RouteV6 string `json:"route_v6"` V4Name string `json:"v4_name"` V6Name string `json:"v6_name"` AveUpstream uint `json:"avg_upstream"` MaxUpstream uint `json:"max_upstream"` AveDownstream uint `json:"avg_downstream"` MaxDownstream uint `json:"max_downstream"` - MaxBandWidthAS uint `json:"max_bandwidth_as"` - Fee *uint `json:"fee"` + MaxBandWidthAS string `json:"max_bandwidth_as"` IP []IP `json:"ip"` Connection []*Connection `json:"connections"` - JPNICAdminID uint `json:"jpnic_admin_id"` JPNICAdmin JPNICAdmin `json:"jpnic_admin"` - JPNICTech []JPNICTech `json:"jpnic_tech" gorm:"many2many:service_jpnic_tech;"` - Open *bool `json:"open"` - Lock *bool `json:"lock"` + JPNICTech []JPNICTech `json:"jpnic_tech"` + StartDate time.Time `json:"start_date"` + EndDate *time.Time `json:"end_date"` + Pass *bool `json:"pass"` + Enable *bool `json:"enable"` AddAllow *bool `json:"add_allow"` Group Group `json:"group"` } @@ -94,6 +120,8 @@ type Connection struct { ConnectionComment string `json:"connection_comment"` // ServiceがETCの時や補足説明で必要 ConnectionNumber uint `json:"connection_number"` NTTTemplateID *uint `json:"ntt_template_id"` + IPv4RouteTemplateID *uint `json:"ipv4_route_template_id"` + IPv6RouteTemplateID *uint `json:"ipv6_route_template_id"` NOCID *uint `json:"noc_id"` TermIP string `json:"term_ip"` Monitor *bool `json:"monitor"` @@ -103,8 +131,10 @@ type Connection struct { LinkV6Our string `json:"link_v6_our"` LinkV6Your string `json:"link_v6_your"` Open *bool `json:"open"` - Lock *bool `json:"lock"` + Enable *bool `json:"enable"` Comment string `json:"comment"` + IPv4RouteTemplate *IPv4RouteTemplate `json:"ipv4_route_template"` + IPv6RouteTemplate *IPv6RouteTemplate `json:"ipv6_route_template"` NTTTemplate *NTTTemplate `json:"ntt_template"` NOC *NOC `json:"noc"` BGPRouter BGPRouter `json:"bgp_router"` @@ -114,7 +144,6 @@ type Connection struct { type NOC struct { gorm.Model - Notice []*Notice `json:"notice"` BGPRouter []*BGPRouter `json:"bgp_router"` TunnelEndPointRouter []*TunnelEndPointRouter `json:"tunnel_endpoint_router"` Name string `json:"name"` @@ -126,19 +155,17 @@ type NOC struct { type BGPRouter struct { gorm.Model - NOCID uint `json:"noc_id"` - NOC NOC `json:"noc"` - Connection []Connection `json:"connection"` - HostName string `json:"hostname"` - Address string `json:"address"` - TunnelRouter []*TunnelEndPointRouter `json:"tunnel_endpoint_router"` - Enable *bool `json:"enable"` - Comment string `json:"comment"` + NOCID uint `json:"noc_id"` + NOC NOC `json:"noc"` + HostName string `json:"hostname"` + Address string `json:"address"` + Enable *bool `json:"enable"` + Comment string `json:"comment"` } type TunnelEndPointRouter struct { gorm.Model - NOCID uint `json:"noc_id"` + NOCID *uint `json:"noc_id"` TunnelEndPointRouterIP []*TunnelEndPointRouterIP `json:"tunnel_endpoint_router_ip"` HostName string `json:"hostname"` Capacity uint `json:"capacity"` @@ -149,7 +176,7 @@ type TunnelEndPointRouter struct { type TunnelEndPointRouterIP struct { gorm.Model TunnelEndPointRouter TunnelEndPointRouter `json:"tunnel_endpoint_router"` - TunnelEndPointRouterID uint `json:"tunnel_endpoint_router_id"` + TunnelEndPointRouterID *uint `json:"tunnel_endpoint_router_id"` IP string `json:"ip"` Enable *bool `json:"enable"` Comment string `json:"comment"` @@ -162,7 +189,7 @@ type IP struct { Name string `json:"name"` IP string `json:"ip"` Plan []*Plan `json:"plan" ` - PlanJPNIC *string `json:"" gorm:"size:65535"` + PlanJPNIC *string `json:"" gorm:"size:15000"` //いらんかも StartDate time.Time `json:"start_date"` EndDate *time.Time `json:"end_date"` UseCase string `json:"use_case"` @@ -180,42 +207,66 @@ type Plan struct { type JPNICAdmin struct { gorm.Model - Service []Service `gorm:"foreignkey:JPNICAdminID"` - JPNICHandle string `json:"jpnic_handle"` - Name string `json:"name"` - NameEn string `json:"name_en"` - Mail string `json:"mail"` - Org string `json:"org"` - OrgEn string `json:"org_en"` - PostCode string `json:"postcode"` - Address string `json:"address"` - AddressEn string `json:"address_en"` - Dept string `json:"dept"` - DeptEn string `json:"dept_en"` - Tel string `json:"tel"` - Fax string `json:"fax"` - Country string `json:"country"` - Lock *bool `json:"lock"` + ServiceID uint `json:"service_id"` + JPNICHandle string `json:"jpnic_handle"` + Name string `json:"name"` + NameEn string `json:"name_en"` + Mail string `json:"mail"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + Dept string `json:"dept"` + DeptEn string `json:"dept_en"` + Tel string `json:"tel"` + Fax string `json:"fax"` + Country string `json:"country"` } type JPNICTech struct { gorm.Model - Service []Service `json:"service" gorm:"many2many:service_jpnic_tech;"` - JPNICHandle string `json:"jpnic_handle"` - Name string `json:"name"` - NameEn string `json:"name_en"` - Mail string `json:"mail"` - Org string `json:"org"` - OrgEn string `json:"org_en"` - PostCode string `json:"postcode"` - Address string `json:"address"` - AddressEn string `json:"address_en"` - Dept string `json:"dept"` - DeptEn string `json:"dept_en"` - Tel string `json:"tel"` - Fax string `json:"fax"` - Country string `json:"country"` - Lock *bool `json:"lock"` + ServiceID uint `json:"service_id"` + JPNICHandle string `json:"jpnic_handle"` + Name string `json:"name"` + NameEn string `json:"name_en"` + Mail string `json:"mail"` + Org string `json:"org"` + OrgEn string `json:"org_en"` + PostCode string `json:"postcode"` + Address string `json:"address"` + AddressEn string `json:"address_en"` + Dept string `json:"dept"` + DeptEn string `json:"dept_en"` + Tel string `json:"tel"` + Fax string `json:"fax"` + Country string `json:"country"` +} + +type PaymentMembershipTemplate struct { + gorm.Model + PriceID string `json:"price_id"` + Title string `json:"title"` + Plan string `json:"plan"` + Monthly bool `json:"monthly"` + Yearly bool `json:"yearly"` + Fee uint `json:"fee"` + Comment string `json:"comment"` +} + +type PaymentCouponTemplate struct { + gorm.Model + StripeCouponID string `json:"stripe_coupon_id"` + Title string `json:"title"` + DiscountRate uint `json:"discount_rate"` + Comment string `json:"comment"` +} + +type PaymentDonateTemplate struct { + gorm.Model + Name string `json:"name"` + Fee uint `json:"fee"` + Comment string `json:"comment"` } type ServiceTemplate struct { @@ -230,6 +281,16 @@ type ServiceTemplate struct { NeedRoute *bool `json:"need_route"` } +type IPv4RouteTemplate struct { + gorm.Model + Name string `json:"name"` +} + +type IPv6RouteTemplate struct { + gorm.Model + Name string `json:"name"` +} + type ConnectionTemplate struct { gorm.Model Hidden bool `json:"hidden"` @@ -239,6 +300,8 @@ type ConnectionTemplate struct { NeedInternet *bool `json:"need_internet"` NeedComment *bool `json:"need_comment"` NeedCrossConnect *bool `json:"need_cross_connect"` + L2 *bool `json:"l2"` + L3 *bool `json:"l3"` } type NTTTemplate struct { @@ -248,30 +311,34 @@ type NTTTemplate struct { Comment string `json:"comment"` } +// 申請中/承諾済み/却下 type Ticket struct { gorm.Model - GroupID uint `json:"group_id"` - UserID uint `json:"user_id"` - Chat []Chat `json:"chat"` - Solved *bool `json:"solved"` - Title string `json:"title"` - Group Group `json:"group"` - User User `json:"user"` + GroupID *uint `json:"group_id"` + UserID *uint `json:"user_id"` + Chat []Chat `json:"chat"` + Request *bool `json:"request"` + RequestReject *bool `json:"request_reject"` + Solved *bool `json:"solved"` + Admin *bool `json:"admin"` + Title string `json:"title"` + Group Group `json:"group"` + User User `json:"user"` } type Chat struct { gorm.Model TicketID uint `json:"ticket_id"` - UserID uint `json:"user_id"` + UserID *uint `json:"user_id"` Admin bool `json:"admin"` - Data string `json:"data" gorm:"size:65535"` + Data string `json:"data" gorm:"size:10000"` User User `json:"user"` } type Token struct { gorm.Model ExpiredAt time.Time `json:"expired_at"` - UserID uint `json:"user_id"` + UserID *uint `json:"user_id"` User User `json:"user"` Status uint `json:"status"` //0: initToken(30m) 1: 30m 2:6h 3: 12h 10: 30d 11:180d Admin *bool `json:"admin"` @@ -283,9 +350,7 @@ type Token struct { type Notice struct { gorm.Model - UserID uint `json:"user_id"` - GroupID uint `json:"group_id"` - NOCID uint `json:"noc_id"` + User []User `json:"user" gorm:"many2many:notice_user;"` Everyone *bool `json:"everyone"` StartTime time.Time `json:"start_time"` EndTime time.Time `json:"end_time"` @@ -293,7 +358,7 @@ type Notice struct { Fault *bool `json:"fault"` Info *bool `json:"info"` Title string `json:"title"` - Data string `json:"data" gorm:"size:65535"` + Data string `json:"data" gorm:"size:15000"` } type Request struct { diff --git a/pkg/api/core/mail/v0/admin.go b/pkg/api/core/mail/v0/admin.go index 138ee04f..0b16a6fa 100644 --- a/pkg/api/core/mail/v0/admin.go +++ b/pkg/api/core/mail/v0/admin.go @@ -8,7 +8,7 @@ import ( "net/http" ) -func SendAdmin(c *gin.Context) { +func SendByAdmin(c *gin.Context) { var input mail.Mail resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) diff --git a/pkg/api/core/mail/v0/slack.go b/pkg/api/core/mail/v0/slack.go index 2a8a7aa2..0057f06f 100644 --- a/pkg/api/core/mail/v0/slack.go +++ b/pkg/api/core/mail/v0/slack.go @@ -18,10 +18,10 @@ func noticeSlack(err error, input mail.Mail) { AddField(slack.Field{Title: "Error", Value: err.Error()}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: false}) } else { - attachment.AddField(slack.Field{Title: "Title", Value: "メール送信"}). - AddField(slack.Field{Title: "To", Value: input.ToMail}). - AddField(slack.Field{Title: "Subject", Value: input.Subject}). - AddField(slack.Field{Title: "Content", Value: input.Content}) - notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) + //attachment.AddField(slack.Field{Title: "Title", Value: "メール送信"}). + // AddField(slack.Field{Title: "To", Value: input.ToMail}). + // AddField(slack.Field{Title: "Subject", Value: input.Subject}). + // AddField(slack.Field{Title: "Content", Value: input.Content}) + //notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } } diff --git a/pkg/api/core/noc/bgpRouter/v0/bgpRouter.go b/pkg/api/core/noc/bgpRouter/v0/bgpRouter.go index c0beabc7..24e42ba6 100644 --- a/pkg/api/core/noc/bgpRouter/v0/bgpRouter.go +++ b/pkg/api/core/noc/bgpRouter/v0/bgpRouter.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" router "github.com/homenoc/dsbd-backend/pkg/api/core/noc/bgpRouter" dbBGPRouter "github.com/homenoc/dsbd-backend/pkg/api/store/noc/bgpRouter/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.BGPRouter resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -35,7 +35,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, router.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -55,7 +55,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, router.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.BGPRouter resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -90,7 +90,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, router.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -111,7 +111,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, router.Result{BGPRouter: result.BGPRouter}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go b/pkg/api/core/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go index 4043868d..b73ab7a3 100644 --- a/pkg/api/core/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go +++ b/pkg/api/core/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/noc/tunnelEndPointRouter" dbGateway "github.com/homenoc/dsbd-backend/pkg/api/store/noc/tunnelEndPointRouter/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.TunnelEndPointRouter resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -35,7 +35,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, tunnelEndPointRouter.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -55,7 +55,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, tunnelEndPointRouter.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.TunnelEndPointRouter resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -90,7 +90,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, tunnelEndPointRouter.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -111,7 +111,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, tunnelEndPointRouter.Result{TunnelEndPointRouters: result.TunnelEndPointRouter}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/noc/tunnelEndPointRouter/v0/update.go b/pkg/api/core/noc/tunnelEndPointRouter/v0/update.go index b345468b..50d28abd 100644 --- a/pkg/api/core/noc/tunnelEndPointRouter/v0/update.go +++ b/pkg/api/core/noc/tunnelEndPointRouter/v0/update.go @@ -18,7 +18,7 @@ func replace(input, replace core.TunnelEndPointRouter) core.TunnelEndPointRouter // uint boolean //NOCID - if input.NOCID != 0 { + if *input.NOCID != 0 { replace.NOCID = input.NOCID } //Capacity diff --git a/pkg/api/core/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go b/pkg/api/core/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go index e40cca3e..fb970a25 100644 --- a/pkg/api/core/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go +++ b/pkg/api/core/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/noc/tunnelEndPointRouterIP" dbTunnelEndPointRouterIP "github.com/homenoc/dsbd-backend/pkg/api/store/noc/tunnelEndPointRouterIP/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.TunnelEndPointRouterIP resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -35,7 +35,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, common.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -55,7 +55,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, common.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.TunnelEndPointRouterIP resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -90,7 +90,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, common.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -111,7 +111,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, tunnelEndPointRouterIP.Result{TunnelEndPointRouterIP: result.TunnelEndPointRouterIP}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/noc/v0/admin.go b/pkg/api/core/noc/v0/admin.go index 74902f08..7b4beca9 100644 --- a/pkg/api/core/noc/v0/admin.go +++ b/pkg/api/core/noc/v0/admin.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/noc" dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.NOC resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -35,7 +35,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, noc.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -55,7 +55,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, noc.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.NOC resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -90,7 +90,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, noc.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -111,7 +111,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, noc.Result{NOC: result.NOC}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/noc/v0/noc.go b/pkg/api/core/noc/v0/noc.go deleted file mode 100644 index 0e36244f..00000000 --- a/pkg/api/core/noc/v0/noc.go +++ /dev/null @@ -1,42 +0,0 @@ -package v0 - -import ( - "github.com/gin-gonic/gin" - "github.com/homenoc/dsbd-backend/pkg/api/core" - auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" - "github.com/homenoc/dsbd-backend/pkg/api/core/common" - "github.com/homenoc/dsbd-backend/pkg/api/core/noc" - dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" - "net/http" -) - -func GetAll(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - userResult := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) - if userResult.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: userResult.Err.Error()}) - return - } - - result := dbNOC.GetAll() - if result.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: result.Err.Error()}) - return - } - - var nocTmp noc.ResultAllUser - - for _, tmp := range result.NOC { - if *tmp.Enable { - nocTmp.NOC = append(nocTmp.NOC, noc.ResultOneUser{ - ID: tmp.ID, - Name: tmp.Name, - Location: tmp.Location, - }) - } - } - - c.JSON(http.StatusOK, nocTmp) -} diff --git a/pkg/api/core/notice/interface.go b/pkg/api/core/notice/interface.go index c48d58aa..36cf0902 100644 --- a/pkg/api/core/notice/interface.go +++ b/pkg/api/core/notice/interface.go @@ -17,9 +17,9 @@ const ( ) type Input struct { - UserID uint `json:"user_id"` - GroupID uint `json:"group_id"` - NOCID uint `json:"noc_id"` + UserID []uint `json:"user_id"` + GroupID []uint `json:"group_id"` + NOCID []uint `json:"noc_id"` Everyone *bool `json:"everyone"` StartTime string `json:"start_time"` EndTime *string `json:"end_time"` diff --git a/pkg/api/core/notice/v0/admin.go b/pkg/api/core/notice/v0/admin.go index b32a0ba9..c5ceb214 100644 --- a/pkg/api/core/notice/v0/admin.go +++ b/pkg/api/core/notice/v0/admin.go @@ -6,15 +6,17 @@ import ( auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/notice" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" dbNotice "github.com/homenoc/dsbd-backend/pkg/api/store/notice/v0" - "github.com/jinzhu/gorm" + dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" + "gorm.io/gorm" "log" "net/http" "strconv" "time" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input notice.Input resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -35,7 +37,7 @@ func AddAdmin(c *gin.Context) { } // 時間はJST基準 - jst, _ := time.LoadLocation("Asia/Tokyo") + jst, _ := time.LoadLocation(config.Conf.Controller.TimeZone) // 9999年12月31日 23:59:59.59 var endTime = time.Date(9999, time.December, 31, 23, 59, 59, 59, jst) @@ -45,12 +47,21 @@ func AddAdmin(c *gin.Context) { endTime, _ = time.ParseInLocation("2006-01-02 15:04:05", *input.EndTime, jst) } - noticeSlackAddAdmin(input) + var userIDArray []uint + + for _, tmpID := range userExtraction(input.UserID, input.GroupID, input.NOCID) { + userIDArray = append(userIDArray, tmpID) + } + + resultUser := dbUser.GetArray(userIDArray) + if resultUser.Err != nil { + log.Println(resultUser.Err.Error()) + c.JSON(http.StatusInternalServerError, common.Error{Error: resultUser.Err.Error()}) + return + } if _, err = dbNotice.Create(&core.Notice{ - UserID: input.UserID, - GroupID: input.GroupID, - NOCID: input.NOCID, + User: resultUser.User, Everyone: input.Everyone, StartTime: startTime, EndTime: endTime, @@ -63,10 +74,11 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } + noticeSlackAddByAdmin(input) c.JSON(http.StatusOK, notice.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -86,7 +98,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input notice.Input resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -108,7 +120,7 @@ func UpdateAdmin(c *gin.Context) { } // 時間はJST基準 - jst, _ := time.LoadLocation("Asia/Tokyo") + jst, _ := time.LoadLocation(config.Conf.Controller.TimeZone) startTime, _ := time.ParseInLocation(layoutInput, input.StartTime, jst) endTime, _ := time.ParseInLocation(layoutInput, *input.EndTime, jst) @@ -122,16 +134,12 @@ func UpdateAdmin(c *gin.Context) { log.Println(startTime) log.Println(endTime) - noticeSlackReplaceAdmin(tmp.Notice[0], input) + noticeSlackReplaceByAdmin(tmp.Notice[0], input) if err = dbNotice.Update(notice.UpdateAll, core.Notice{ Model: gorm.Model{ID: uint(id)}, - UserID: input.UserID, - GroupID: input.GroupID, - NOCID: input.NOCID, StartTime: startTime, EndTime: endTime, - Everyone: input.Everyone, Important: input.Important, Fault: input.Fault, Info: input.Info, @@ -145,7 +153,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.ResultAdmin{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -165,7 +173,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.ResultAdmin{Notice: result.Notice}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/notice/v0/notice.go b/pkg/api/core/notice/v0/notice.go deleted file mode 100644 index 3c465f25..00000000 --- a/pkg/api/core/notice/v0/notice.go +++ /dev/null @@ -1,115 +0,0 @@ -package v0 - -import ( - "github.com/gin-gonic/gin" - "github.com/homenoc/dsbd-backend/pkg/api/core" - auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" - "github.com/homenoc/dsbd-backend/pkg/api/core/common" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" - "github.com/homenoc/dsbd-backend/pkg/api/core/notice" - dbService "github.com/homenoc/dsbd-backend/pkg/api/store/group/service/v0" - dbNotice "github.com/homenoc/dsbd-backend/pkg/api/store/notice/v0" - "net/http" - "strconv" -) - -type noticeHandler struct { - notice []notice.Notice -} - -const layout = "2006-01-02T15:04:05" - -// -// DBに入っている情報はUTCベースなので注意が必要 -// - -func Get(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - // Group authentication - result := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) - return - } - - var noticeResult notice.ResultDatabase - var responseNotice []notice.Notice - - h := noticeHandler{notice: responseNotice} - - if result.User.GroupID != 0 { - - serviceResult := dbService.Get(service.Open, &core.Service{GroupID: result.User.GroupID}) - if serviceResult.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: result.Err.Error()}) - return - } - - var nocIDs []string - - for _, tmpService := range serviceResult.Service { - for _, tmpConnection := range tmpService.Connection { - if tmpConnection.BGPRouter.NOCID != 0 { - if !arrayContains(nocIDs, strconv.Itoa(int(tmpConnection.BGPRouter.NOCID))) { - nocIDs = append(nocIDs, strconv.Itoa(int(tmpConnection.BGPRouter.NOCID))) - } - } - } - } - - noticeResult = dbNotice.GetArray(notice.UIDOrGIDOrNOCAllOrAll, &core.Notice{ - UserID: result.User.ID, - GroupID: result.User.GroupID, - }, nocIDs) - if noticeResult.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: result.Err.Error()}) - return - } - - for _, tmpNotice := range noticeResult.Notice { - h.appendNotice(tmpNotice, tmpNotice.StartTime.Format(layout), tmpNotice.EndTime.Format(layout)) - } - - } else { - noticeResult = dbNotice.Get(notice.UIDOrAll, &core.Notice{ - UserID: result.User.ID, - }) - if noticeResult.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: result.Err.Error()}) - return - } - for _, tmpNotice := range noticeResult.Notice { - h.appendNotice(tmpNotice, tmpNotice.StartTime.Format(layout), tmpNotice.EndTime.Format(layout)) - } - } - - c.JSON(http.StatusOK, notice.Result{Notice: h.notice}) -} - -func arrayContains(arr []string, str string) bool { - for _, v := range arr { - if v == str { - return true - } - } - return false -} - -func (h *noticeHandler) appendNotice(data core.Notice, startTime, endTime string) { - h.notice = append(h.notice, notice.Notice{ - ID: data.ID, - UserID: data.UserID, - GroupID: data.GroupID, - NOCID: data.NOCID, - Everyone: *data.Everyone, - StartTime: startTime, - EndTime: endTime, - Important: *data.Important, - Fault: *data.Fault, - Info: *data.Info, - Title: data.Title, - Data: data.Data, - }) -} diff --git a/pkg/api/core/notice/v0/slack.go b/pkg/api/core/notice/v0/slack.go index e48f30f8..526fe369 100644 --- a/pkg/api/core/notice/v0/slack.go +++ b/pkg/api/core/notice/v0/slack.go @@ -11,7 +11,7 @@ import ( const layoutInput = "2006-01-02 15:04:05" -func noticeSlackAddAdmin(input notice.Input) { +func noticeSlackAddByAdmin(input notice.Input) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} @@ -28,7 +28,7 @@ func noticeSlackAddAdmin(input notice.Input) { notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) } -func noticeSlackReplaceAdmin(before core.Notice, after notice.Input) { +func noticeSlackReplaceByAdmin(before core.Notice, after notice.Input) { // 審査ステータスのSlack通知 attachment := slack.Attachment{} @@ -50,17 +50,17 @@ func changeText(before core.Notice, after notice.Input) string { data += "Contents: " + before.Data + " => " + after.Data + "\n" } - if after.UserID != before.UserID { - data += "UserID: " + strconv.Itoa(int(before.UserID)) + " => " + strconv.Itoa(int(after.UserID)) + "\n" - } - - if after.GroupID != before.GroupID { - data += "GroupID: " + strconv.Itoa(int(before.UserID)) + " => " + strconv.Itoa(int(after.UserID)) + "\n" - } - - if after.NOCID != before.NOCID { - data += "NOCID: " + strconv.Itoa(int(before.NOCID)) + " => " + strconv.Itoa(int(after.NOCID)) + "\n" - } + //if after.UserID != before.UserID { + // data += "UserID: " + strconv.Itoa(int(before.UserID)) + " => " + strconv.Itoa(int(after.UserID)) + "\n" + //} + // + //if after.GroupID != before.GroupID { + // data += "GroupID: " + strconv.Itoa(int(before.UserID)) + " => " + strconv.Itoa(int(after.UserID)) + "\n" + //} + // + //if after.NOCID != before.NOCID { + // data += "NOCID: " + strconv.Itoa(int(before.NOCID)) + " => " + strconv.Itoa(int(after.NOCID)) + "\n" + //} if after.StartTime != before.StartTime.Add(9*time.Hour).Format(layoutInput) { data += "Start Time: " + before.StartTime.Add(9*time.Hour).Format(layoutInput) + " => " + after.StartTime + "\n" diff --git a/pkg/api/core/notice/v0/user.go b/pkg/api/core/notice/v0/user.go new file mode 100644 index 00000000..8a9d7dc8 --- /dev/null +++ b/pkg/api/core/notice/v0/user.go @@ -0,0 +1,68 @@ +package v0 + +import ( + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/group" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection" + dbConnection "github.com/homenoc/dsbd-backend/pkg/api/store/group/connection/v0" + dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" + "gorm.io/gorm" +) + +func userExtraction(inputUser, inputGroup, inputNOC []uint) []uint { + var userArray []uint + var groupArray []uint + + // if noc length isn't zero value + if len(inputNOC) != 0 { + for _, tmpNOC := range inputNOC { + result := dbConnection.Get(connection.NOCID, &core.Connection{NOCID: &tmpNOC}) + if result.Err != nil { + for _, tmpConnection := range result.Connection { + for _, tmpUser := range tmpConnection.Service.Group.Users { + userArray = append(userArray, tmpUser.ID) + } + } + } + } + } + + // if group length isn't zero value + if len(inputGroup) != 0 { + //I should implement check function + for _, tmpGroup := range inputGroup { + result := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: tmpGroup}}) + if result.Err != nil { + for _, tmpResultGroup := range result.Group { + for _, tmpUser := range tmpResultGroup.Users { + userArray = append(userArray, tmpUser.ID) + } + } + } + } + groupArray = removeDuplicate(groupArray) + } + + // if user length isn't zero value + if len(inputUser) != 0 { + //I should implement check function + for _, tmpUser := range inputUser { + userArray = append(userArray, tmpUser) + } + userArray = removeDuplicate(userArray) + } + + return userArray +} + +func removeDuplicate(args []uint) []uint { + results := make([]uint, 0, len(args)) + encountered := map[uint]bool{} + for i := 0; i < len(args); i++ { + if !encountered[args[i]] { + encountered[args[i]] = true + results = append(results, args[i]) + } + } + return results +} diff --git a/pkg/api/core/payment/interface.go b/pkg/api/core/payment/interface.go new file mode 100644 index 00000000..4e8dcda5 --- /dev/null +++ b/pkg/api/core/payment/interface.go @@ -0,0 +1,26 @@ +package payment + +import "github.com/homenoc/dsbd-backend/pkg/api/core" + +const ( + ID = 0 + PaymentIntentID = 1 + UpdatePaid = 140 + UpdateAll = 150 +) + +type Input struct { + ItemID uint `json:"item_id"` +} + +type ChangeCardPaymentInit struct { + PaymentMethodID string `json:"payment_method_id"` +} + +type ResultByAdmin struct { + Payment []core.Payment `json:"payment"` +} + +type ResultByUser struct { + ClientSecret string `json:"client_secret"` +} diff --git a/pkg/api/core/payment/v0/admin.go b/pkg/api/core/payment/v0/admin.go new file mode 100644 index 00000000..d6ed25dd --- /dev/null +++ b/pkg/api/core/payment/v0/admin.go @@ -0,0 +1,164 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + "github.com/homenoc/dsbd-backend/pkg/api/core/notice" + "github.com/homenoc/dsbd-backend/pkg/api/core/payment" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" + dbPayment "github.com/homenoc/dsbd-backend/pkg/api/store/payment/v0" + "github.com/stripe/stripe-go/v72" + "github.com/stripe/stripe-go/v72/refund" + "gorm.io/gorm" + "net/http" + "strconv" +) + +func AddByAdmin(c *gin.Context) { + //var input notice.Input + // + //resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + //if resultAdmin.Err != nil { + // c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + // return + //} + //err := c.BindJSON(&input) + //if err != nil { + // log.Println(err) + // c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + // return + //} + // + //if err = check(input); err != nil { + // c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + // return + //} + // + //// 時間はJST基準 + //jst, _ := time.LoadLocation(config.Conf.Controller.TimeZone) + // + //// 9999年12月31日 23:59:59.59 + //var endTime = time.Date(9999, time.December, 31, 23, 59, 59, 59, jst) + // + //startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", input.StartTime, jst) + //if input.EndTime != nil { + // endTime, _ = time.ParseInLocation("2006-01-02 15:04:05", *input.EndTime, jst) + //} + // + //var userIDArray []uint + // + //for _, tmpID := range userExtraction(input.UserID, input.GroupID, input.NOCID) { + // userIDArray = append(userIDArray, tmpID) + //} + // + //resultUser := dbUser.GetArray(userIDArray) + //if resultUser.Err != nil { + // log.Println(resultUser.Err.Error()) + // c.JSON(http.StatusInternalServerError, common.Error{Error: resultUser.Err.Error()}) + // return + //} + // + //if _, err = dbNotice.Create(&core.Notice{ + // User: resultUser.User, + // Everyone: input.Everyone, + // StartTime: startTime, + // EndTime: endTime, + // Important: input.Important, + // Fault: input.Fault, + // Info: input.Info, + // Title: input.Title, + // Data: input.Data, + //}); err != nil { + // c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + // return + //} + //noticeSlackAddByAdmin(input) + //c.JSON(http.StatusOK, notice.Result{}) +} + +func DeleteByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + if err = dbPayment.Delete(&core.Payment{Model: gorm.Model{ID: uint(id)}}); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + c.JSON(http.StatusOK, notice.Result{}) +} + +func GetByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + result, err := dbPayment.Get(payment.ID, core.Payment{Model: gorm.Model{ID: uint(id)}}) + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + c.JSON(http.StatusOK, payment.ResultByAdmin{Payment: result}) +} + +func GetAllByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + if result, err := dbPayment.GetAll(); err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + } else { + c.JSON(http.StatusOK, payment.ResultByAdmin{Payment: result}) + } +} + +func RefundByAdmin(c *gin.Context) { + resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) + if resultAdmin.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + result, err := dbPayment.Get(payment.ID, core.Payment{Model: gorm.Model{ID: uint(id)}}) + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + stripe.Key = config.Conf.Stripe.SecretKey + + _, err = refund.New(&stripe.RefundParams{ + PaymentIntent: stripe.String(result[0].PaymentIntentID), + }) + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/payment/v0/payment.go b/pkg/api/core/payment/v0/payment.go new file mode 100644 index 00000000..debab6bb --- /dev/null +++ b/pkg/api/core/payment/v0/payment.go @@ -0,0 +1,261 @@ +package v0 + +import ( + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + "github.com/homenoc/dsbd-backend/pkg/api/core/group" + "github.com/homenoc/dsbd-backend/pkg/api/core/payment" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" + dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" + dbPayment "github.com/homenoc/dsbd-backend/pkg/api/store/payment/v0" + dbPaymentDonateTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_donate/v0" + dbPaymentMembershipTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_membership/v0" + "github.com/stripe/stripe-go/v72" + "github.com/stripe/stripe-go/v72/customer" + "github.com/stripe/stripe-go/v72/paymentintent" + "github.com/stripe/stripe-go/v72/paymentmethod" + "github.com/stripe/stripe-go/v72/setupintent" + "github.com/stripe/stripe-go/v72/sub" + "gorm.io/gorm" + "log" + "net/http" +) + +func MembershipPayment(c *gin.Context) { + var input payment.Input + userToken := c.Request.Header.Get("USER_TOKEN") + accessToken := c.Request.Header.Get("ACCESS_TOKEN") + + err := c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + + if result.User.Group.StripeSubscriptionID != nil && *result.User.Group.StripeSubscriptionID != "" { + c.JSON(http.StatusBadRequest, common.Error{Error: "Error: Subscription."}) + return + } + + if *result.User.Group.Student { + c.JSON(http.StatusBadRequest, common.Error{Error: "Error: You are student."}) + return + } + + resultTemplate, err := dbPaymentMembershipTemplate.Get(input.ItemID) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "template is not found..."}) + return + } + + if result.User.Group.StripeCustomerID == nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: "stripe customerID is not exists."}) + return + } + + stripe.Key = config.Conf.Stripe.SecretKey + + params := &stripe.SubscriptionParams{ + Items: []*stripe.SubscriptionItemsParams{ + { + Price: stripe.String(resultTemplate.PriceID), + }, + }, + PaymentBehavior: stripe.String("default_incomplete"), + Customer: stripe.String(*result.User.Group.StripeCustomerID), + } + params.AddExpand("latest_invoice.payment_intent") + + pi, err := sub.New(params) + log.Printf("pi.New: %v\n", pi.LatestInvoice.PaymentIntent.ClientSecret) + if err != nil { + log.Printf("pi.New: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"}) + return + } + + dbPayment.Create(&core.Payment{ + UserID: result.User.ID, + GroupID: result.User.GroupID, + PaymentIntentID: pi.LatestInvoice.PaymentIntent.ID, + IsMembership: &[]bool{true}[0], + Paid: &[]bool{false}[0], + Fee: resultTemplate.Fee, + }) + + dbGroup.Update(group.UpdateMembership, core.Group{ + Model: gorm.Model{ID: *result.User.GroupID}, + StripeCustomerID: result.User.Group.StripeCustomerID, + StripeSubscriptionID: &pi.ID, + PaymentMembershipTemplateID: &resultTemplate.ID, + }) + + go noticeSlackPaymentMembershipPayment(*result.User.GroupID, resultTemplate.Plan, pi.LatestInvoice.PaymentIntent.ID) + + c.JSON(http.StatusOK, payment.ResultByUser{ + ClientSecret: pi.LatestInvoice.PaymentIntent.ClientSecret, + }) +} + +func DonatePayment(c *gin.Context) { + var input payment.Input + userToken := c.Request.Header.Get("USER_TOKEN") + accessToken := c.Request.Header.Get("ACCESS_TOKEN") + + err := c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + result := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + + resultTemplate, err := dbPaymentDonateTemplate.Get(input.ItemID) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "template is not found..."}) + return + } + + stripe.Key = config.Conf.Stripe.SecretKey + + params := &stripe.PaymentIntentParams{ + Amount: stripe.Int64(int64(resultTemplate.Fee)), + Currency: stripe.String(string(stripe.CurrencyJPY)), + } + + pi, err := paymentintent.New(params) + log.Printf("pi.New: %v\n", pi.ClientSecret) + if err != nil { + log.Printf("pi.New: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"}) + return + } + + dbPayment.Create(&core.Payment{ + UserID: result.User.ID, + PaymentIntentID: pi.ID, + IsMembership: &[]bool{false}[0], + Paid: &[]bool{false}[0], + Fee: resultTemplate.Fee, + }) + + go noticeSlackPaymentDonatePayment(result.User.ID, resultTemplate.Fee, pi.ID) + + c.JSON(http.StatusOK, payment.ResultByUser{ + ClientSecret: pi.ClientSecret, + }) +} + +func ChangeCardPayment(c *gin.Context) { + var input payment.ChangeCardPaymentInit + userToken := c.Request.Header.Get("USER_TOKEN") + accessToken := c.Request.Header.Get("ACCESS_TOKEN") + + err := c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + + stripe.Key = config.Conf.Stripe.SecretKey + + if result.User.Group.StripeCustomerID == nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: "stripe customerID is not exists."}) + return + } + + if result.User.Group.StripeSubscriptionID == nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: "stripe subscriptionID is not exists."}) + return + } + + //attach + pm, err := paymentmethod.Attach(input.PaymentMethodID, &stripe.PaymentMethodAttachParams{ + Customer: stripe.String(*result.User.Group.StripeCustomerID), + }) + if err != nil { + log.Printf("Error: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"}) + return + } + log.Println(pm) + + // change card on user + cus, err := customer.Update(*result.User.Group.StripeCustomerID, &stripe.CustomerParams{ + InvoiceSettings: &stripe.CustomerInvoiceSettingsParams{ + DefaultPaymentMethod: stripe.String(input.PaymentMethodID), + }, + }) + if err != nil { + log.Printf("Error: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"}) + return + } + + log.Printf(cus.ID) + + _, err = sub.Update(*result.User.Group.StripeSubscriptionID, &stripe.SubscriptionParams{ + DefaultPaymentMethod: stripe.String(input.PaymentMethodID), + }) + if err != nil { + log.Printf("Error: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"}) + return + } + go noticeSlackPaymentMembershipChangeCardPayment(result.User.Group.ID) + + c.JSON(http.StatusOK, common.Result{}) +} + +func ChangeCardPaymentInit(c *gin.Context) { + userToken := c.Request.Header.Get("USER_TOKEN") + accessToken := c.Request.Header.Get("ACCESS_TOKEN") + + result := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + + stripe.Key = config.Conf.Stripe.SecretKey + + // get subscription + params := &stripe.SetupIntentParams{ + PaymentMethodTypes: []*string{ + stripe.String("card"), + }, + } + + si, err := setupintent.New(params) + log.Printf("si.New: %v\n", si.ClientSecret) + if err != nil { + log.Printf("si.New: %v", err) + c.JSON(http.StatusInternalServerError, common.Error{Error: "payment_membership system error"}) + return + } + + c.JSON(http.StatusOK, payment.ResultByUser{ + ClientSecret: si.ClientSecret, + }) +} diff --git a/pkg/api/core/payment/v0/slack.go b/pkg/api/core/payment/v0/slack.go new file mode 100644 index 00000000..801d963e --- /dev/null +++ b/pkg/api/core/payment/v0/slack.go @@ -0,0 +1,55 @@ +package v0 + +import ( + "github.com/ashwanthkumar/slack-go-webhook" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/group" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" + "github.com/homenoc/dsbd-backend/pkg/api/core/user" + dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" + dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" + "gorm.io/gorm" + "strconv" +) + +func noticeSlackPaymentMembershipPayment(groupID uint, plan, paymentIntentID string) { + attachment := slack.Attachment{} + + result := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: groupID}}) + + attachment.AddField(slack.Field{Title: "Title", Value: "会費支払い"}). + AddField(slack.Field{Title: "申請者", Value: strconv.Itoa(int(groupID)) + ": " + result.Group[0].Org + "(" + result.Group[0].OrgEn + ")"}). + AddField(slack.Field{Title: "Plan", Value: plan}). + AddField(slack.Field{Title: "PaymentIntentID", Value: paymentIntentID}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackPaymentDonatePayment(userID, money uint, paymentIntentID string) { + attachment := slack.Attachment{} + + result := dbUser.Get(user.ID, &core.User{Model: gorm.Model{ID: userID}}) + + attachment.AddField(slack.Field{Title: "Title", Value: "寄付"}). + AddField(slack.Field{Title: "申請者", Value: strconv.Itoa(int(userID)) + ": " + result.User[0].Name + "(" + result.User[0].NameEn + ")"}). + AddField(slack.Field{Title: "金額", Value: strconv.Itoa(int(money)) + "円"}). + AddField(slack.Field{Title: "PaymentIntentID", Value: paymentIntentID}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackPaymentMembershipChangeCardPayment(groupID uint) { + attachment := slack.Attachment{} + + result := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: groupID}}) + + attachment.AddField(slack.Field{Title: "Title", Value: "会費支払い(カードの変更)"}). + AddField(slack.Field{Title: "申請者", Value: strconv.Itoa(int(groupID)) + ": " + result.Group[0].Org + "(" + result.Group[0].OrgEn + ")"}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} + +func noticeSlackPaymentPaid(paymentIntentID string) { + attachment := slack.Attachment{} + + attachment.AddField(slack.Field{Title: "Title", Value: "支払い完了"}). + AddField(slack.Field{Title: "PaymentIntentID", Value: paymentIntentID}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) +} diff --git a/pkg/api/core/payment/v0/websocket.go b/pkg/api/core/payment/v0/websocket.go new file mode 100644 index 00000000..c7b30b6b --- /dev/null +++ b/pkg/api/core/payment/v0/websocket.go @@ -0,0 +1,138 @@ +package v0 + +import ( + "encoding/json" + "fmt" + "github.com/gin-gonic/gin" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/common" + "github.com/homenoc/dsbd-backend/pkg/api/core/group" + "github.com/homenoc/dsbd-backend/pkg/api/core/payment" + "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" + dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" + dbPayment "github.com/homenoc/dsbd-backend/pkg/api/store/payment/v0" + "github.com/stripe/stripe-go/v72" + "github.com/stripe/stripe-go/v72/webhook" + "gorm.io/gorm" + "io/ioutil" + "log" + "net/http" + "os" + "time" +) + +func GetStripeWebHook(c *gin.Context) { + stripe.Key = config.Conf.Stripe.SecretKey + + const MaxBodyBytes = int64(65536) + body := http.MaxBytesReader(c.Writer, c.Request.Body, MaxBodyBytes) + + payload, err := ioutil.ReadAll(body) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err) + return + } + + event := stripe.Event{} + if err := json.Unmarshal(payload, &event); err != nil { + fmt.Fprintf(os.Stderr, "⚠️ Webhook error while parsing basic request. %v\n", err.Error()) + c.JSON(http.StatusBadRequest, err.Error()) + return + } + + endpointSecret := config.Conf.Stripe.WebhookSecretKey + + event, err = webhook.ConstructEvent(payload, c.Request.Header.Get("Stripe-Signature"), endpointSecret) + if err != nil { + log.Println("error: " + err.Error()) + return + } + + log.Println(event.Type) + + if event.Type == "checkout.session.completed" { + log.Println("user", event.Data.Object["metadata"].(map[string]interface{})["user"].(string)) + } else if event.Type == "customer.subscription.updated" { + log.Println("customer.subscription.updated: " + event.Data.Object["id"].(string)) + } else if event.Type == "invoice.paid" { + log.Println("invoice.paid: " + event.Data.Object["id"].(string)) + } else if event.Type == "invoice.updated" { + log.Println("invoice.updated: " + event.Data.Object["id"].(string)) + } else if event.Type == "invoice.payment_succeeded" { + log.Println("invoice.payment_succeeded: " + event.Data.Object["id"].(string)) + } else if event.Type == "payment_intent.created" { + log.Println("payment_intent.created: " + event.Data.Object["id"].(string)) + } else if event.Type == "payment_intent.succeeded" { + log.Println("payment_intent.successed: " + event.Data.Object["id"].(string)) + resultPayment, err := dbPayment.Get(payment.PaymentIntentID, core.Payment{PaymentIntentID: event.Data.Object["id"].(string)}) + if err != nil { + log.Println(err) + } + + if resultPayment[0].Group == nil { + log.Println("[paid] error: GroupID is not exists....") + return + } + + // Membership + if *resultPayment[0].IsMembership { + resultGroup := dbGroup.Get(group.ID, &core.Group{Model: gorm.Model{ID: *resultPayment[0].GroupID}}) + if resultGroup.Err != nil { + log.Println(resultGroup.Err) + return + } + + // now time + now := time.Now() + + if resultGroup.Group[0].MemberExpired != nil { + now = *resultGroup.Group[0].MemberExpired + } + + if resultGroup.Group[0].PaymentMembershipTemplate.Yearly { + // membership yearly + now = now.AddDate(1, 0, 0) + } else if resultGroup.Group[0].PaymentMembershipTemplate.Monthly { + // membership monthly + now = now.AddDate(0, 1, 0) + } else { + log.Println("error:") + return + } + + dbGroup.Update(group.UpdateMembership, core.Group{ + Model: gorm.Model{ID: *resultPayment[0].GroupID}, + MemberExpired: &now, + }) + } + + err = dbPayment.Update(payment.UpdatePaid, &core.Payment{ + PaymentIntentID: event.Data.Object["id"].(string), + Paid: &[]bool{true}[0], + }) + if err != nil { + log.Println(err) + } + + noticeSlackPaymentPaid(event.Data.Object["id"].(string)) + + } else if event.Type == "charge.succeeded" { + log.Printf("charge.succeeded: " + event.Data.Object["id"].(string)) + } else if event.Type == "charge.refunded" { + log.Printf("charge.succeeded: " + event.Data.Object["id"].(string) + "| " + event.Data.Object["payment_intent"].(string)) + result, err := dbPayment.Get(payment.PaymentIntentID, core.Payment{PaymentIntentID: event.Data.Object["payment_intent"].(string)}) + if err != nil { + log.Println(err) + } + err = dbPayment.Update(payment.UpdateAll, &core.Payment{ + Model: gorm.Model{ID: result[0].ID}, + Refund: &[]bool{true}[0], + }) + if err != nil { + log.Println(err) + } + + } + + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/support/chat/v0/chat.go b/pkg/api/core/support/chat/v0/chat.go deleted file mode 100644 index 652e94c6..00000000 --- a/pkg/api/core/support/chat/v0/chat.go +++ /dev/null @@ -1,90 +0,0 @@ -package v0 - -import ( - "fmt" - "github.com/gin-gonic/gin" - "github.com/homenoc/dsbd-backend/pkg/api/core" - auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" - "github.com/homenoc/dsbd-backend/pkg/api/core/common" - "github.com/homenoc/dsbd-backend/pkg/api/core/support" - "github.com/homenoc/dsbd-backend/pkg/api/core/support/ticket" - dbChat "github.com/homenoc/dsbd-backend/pkg/api/store/support/chat/v0" - dbTicket "github.com/homenoc/dsbd-backend/pkg/api/store/support/ticket/v0" - "github.com/jinzhu/gorm" - "log" - "net/http" - "strconv" -) - -func Add(c *gin.Context) { - var input support.FirstInput - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - err := c.BindJSON(&input) - if err != nil { - log.Println(err) - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: fmt.Sprintf("id error")}) - return - } - - // Group authentication - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) - return - } - - // input check - if err = check(input); err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) - return - } - if uint(id) == 0 { - c.JSON(http.StatusBadRequest, common.Error{Error: "valid id"}) - return - } - - // IDからDBからチケットを検索 - resultTicket := dbTicket.Get(ticket.ID, &core.Ticket{Model: gorm.Model{ID: uint(id)}}) - if resultTicket.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: resultTicket.Err.Error()}) - return - } - // 問題解決時はここでエラーを返す - if *resultTicket.Tickets[0].Solved { - c.JSON(http.StatusInternalServerError, common.Error{Error: "This problem is closed..."}) - return - } - // GroupIDが一致しない場合はここでエラーを返す - if resultTicket.Tickets[0].GroupID != result.User.GroupID { - c.JSON(http.StatusInternalServerError, common.Error{Error: "Auth Error: group id failed..."}) - return - } - - // Chat DBに登録 - resultChat, err := dbChat.Create(&core.Chat{ - TicketID: resultTicket.Tickets[0].ID, - UserID: result.User.ID, - Admin: false, - Data: input.Data, - }) - if err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) - return - } - - support.Broadcast <- support.WebSocketResult{ - ID: uint(id), - CreatedAt: resultChat.CreatedAt, - UserID: resultChat.UserID, - Message: resultChat.Data, - } - c.JSON(http.StatusOK, support.Result{}) -} diff --git a/pkg/api/core/support/chat/v0/check.go b/pkg/api/core/support/chat/v0/check.go deleted file mode 100644 index 349eec88..00000000 --- a/pkg/api/core/support/chat/v0/check.go +++ /dev/null @@ -1,17 +0,0 @@ -package v0 - -import ( - "fmt" - "github.com/homenoc/dsbd-backend/pkg/api/core/support" -) - -func check(input support.FirstInput) error { - if input.TicketID == 0 { - return fmt.Errorf("no data: TicketID") - } - if input.Data == "" { - return fmt.Errorf("no data: data") - } - - return nil -} diff --git a/pkg/api/core/support/interface.go b/pkg/api/core/support/interface.go index d7a71a58..979c637e 100644 --- a/pkg/api/core/support/interface.go +++ b/pkg/api/core/support/interface.go @@ -3,7 +3,7 @@ package support import ( "github.com/gorilla/websocket" "github.com/homenoc/dsbd-backend/pkg/api/core" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "time" ) @@ -16,6 +16,7 @@ type WebSocketResult struct { ID uint `json:"id"` Err string `json:"error"` CreatedAt time.Time `json:"created_at"` + TicketID uint `json:"ticket_id"` UserToken string `json:"user_token"` AccessToken string `json:"access_token"` UserID uint `json:"user_id"` @@ -45,9 +46,11 @@ type WebSocket struct { type FirstInput struct { gorm.Model + IsGroup bool `json:"is_group"` TicketID uint `json:"ticket_id"` Title string `json:"title"` Data string `json:"data"` + UserID uint `json:"user_id"` GroupID uint `json:"group_id"` } diff --git a/pkg/api/core/support/ticket/v0/admin.go b/pkg/api/core/support/ticket/v0/admin.go index ee91de18..bf0f8471 100644 --- a/pkg/api/core/support/ticket/v0/admin.go +++ b/pkg/api/core/support/ticket/v0/admin.go @@ -17,14 +17,14 @@ import ( dbChat "github.com/homenoc/dsbd-backend/pkg/api/store/support/chat/v0" dbTicket "github.com/homenoc/dsbd-backend/pkg/api/store/support/ticket/v0" dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" "time" ) -func CreateAdmin(c *gin.Context) { +func CreateByAdmin(c *gin.Context) { var input support.FirstInput // Admin authentication @@ -42,18 +42,39 @@ func CreateAdmin(c *gin.Context) { } // input check - if err = checkAdmin(input); err != nil { + if err = checkByAdmin(input); err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return } - - // Tickets DBに登録 - ticketResult, err := dbTicket.Create(&core.Ticket{ - GroupID: input.GroupID, - UserID: 0, + resultTicket := &core.Ticket{ Solved: &[]bool{false}[0], Title: input.Title, - }) + Admin: &[]bool{true}[0], + Request: &[]bool{false}[0], + } + + // isn't group + if !input.IsGroup { + if input.UserID == 0 { + c.JSON(http.StatusBadRequest, common.Error{Error: "UserID is wrong"}) + return + } + + resultTicket.GroupID = nil + resultTicket.UserID = &input.UserID + } else { + //is group + if input.UserID == 0 { + c.JSON(http.StatusBadRequest, common.Error{Error: "GroupID is wrong"}) + return + } + + resultTicket.GroupID = &input.GroupID + resultTicket.UserID = nil + } + + // Tickets DBに登録 + ticketResult, err := dbTicket.Create(resultTicket) if err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return @@ -61,7 +82,7 @@ func CreateAdmin(c *gin.Context) { // Chat DBに登録 chatResult, err := dbChat.Create(&core.Chat{ - UserID: 0, + UserID: nil, Admin: true, Data: input.Data, TicketID: ticketResult.ID, @@ -77,7 +98,7 @@ func CreateAdmin(c *gin.Context) { }) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.Ticket // Admin authentication resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -122,7 +143,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, support.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { // Admin authentication resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { @@ -145,7 +166,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, support.Result{Ticket: resultTicket.Tickets}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { // Admin authentication resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { @@ -198,12 +219,18 @@ func GetAdminWebSocket(c *gin.Context) { return } + var groupID uint = 0 + + if ticketResult.Tickets[0].GroupID != nil { + groupID = *ticketResult.Tickets[0].GroupID + } + // WebSocket送信 support.Clients[&support.WebSocket{ TicketID: uint(id), UserID: resultAdmin.AdminID, UserName: "HomeNOC", - GroupID: ticketResult.Tickets[0].GroupID, + GroupID: groupID, Socket: conn, }] = true @@ -217,7 +244,7 @@ func GetAdminWebSocket(c *gin.Context) { TicketID: uint(id), UserID: resultAdmin.AdminID, UserName: "HomeNOC(運営)", - GroupID: ticketResult.Tickets[0].GroupID, + GroupID: groupID, Socket: conn, }) break @@ -225,15 +252,16 @@ func GetAdminWebSocket(c *gin.Context) { _, err = dbChat.Create(&core.Chat{ TicketID: ticketResult.Tickets[0].ID, - UserID: resultAdmin.AdminID, + UserID: nil, Admin: true, Data: msg.Message, }) if err != nil { conn.WriteJSON(&support.WebSocketResult{Err: "db write error"}) } else { + msg.TicketID = uint(id) msg.UserID = resultAdmin.AdminID - msg.GroupID = ticketResult.Tickets[0].GroupID + msg.GroupID = groupID msg.UserName = "HomeNOC(運営)" msg.Admin = true // Token関連の初期化 @@ -241,12 +269,13 @@ func GetAdminWebSocket(c *gin.Context) { msg.UserToken = "" //Admin側に送信 - controller.SendChatAdmin(controllerInterface.Chat{ + controller.SendChatByAdmin(controllerInterface.Chat{ + TicketID: uint(id), CreatedAt: msg.CreatedAt, Admin: msg.Admin, UserID: resultAdmin.AdminID, UserName: msg.UserName, - GroupID: ticketResult.Tickets[0].GroupID, + GroupID: groupID, Message: msg.Message, }) @@ -280,30 +309,46 @@ func GetAdminWebSocket(c *gin.Context) { } } -func HandleMessagesAdmin() { +func HandleMessagesByAdmin() { for { msg := <-support.Broadcast + //登録されているクライアント宛にデータ送信する for client := range support.Clients { // ユーザのみの場合 - if client.GroupID == 0 { - return - } else if client.GroupID == msg.GroupID { - err := client.Socket.WriteJSON(support.WebSocketChatResponse{ - Time: time.Now().UTC().Add(9 * time.Hour).Format(timeLayout), - UserID: msg.UserID, - UserName: msg.UserName, - GroupID: msg.GroupID, - Admin: msg.Admin, - Message: msg.Message, - }) - if err != nil { - log.Printf("error: %v", err) - client.Socket.Close() - delete(support.Clients, client) + log.Println(msg) + if client.TicketID == msg.TicketID { + if msg.GroupID == 0 { + err := client.Socket.WriteJSON(support.WebSocketChatResponse{ + Time: time.Now().UTC().Add(9 * time.Hour).Format(timeLayout), + UserID: msg.UserID, + UserName: msg.UserName, + GroupID: 0, + Admin: msg.Admin, + Message: msg.Message, + }) + if err != nil { + log.Printf("error: %v", err) + client.Socket.Close() + delete(support.Clients, client) + } + } else if client.GroupID == msg.GroupID { + err := client.Socket.WriteJSON(support.WebSocketChatResponse{ + Time: time.Now().UTC().Add(9 * time.Hour).Format(timeLayout), + UserID: msg.UserID, + UserName: msg.UserName, + GroupID: msg.GroupID, + Admin: msg.Admin, + Message: msg.Message, + }) + if err != nil { + log.Printf("error: %v", err) + client.Socket.Close() + delete(support.Clients, client) + } + } else { + // 認証失敗時の処理 } - } else { - // 認証失敗時の処理 } } } diff --git a/pkg/api/core/support/ticket/v0/check.go b/pkg/api/core/support/ticket/v0/check.go index 9f72eabb..d8c2ea6f 100644 --- a/pkg/api/core/support/ticket/v0/check.go +++ b/pkg/api/core/support/ticket/v0/check.go @@ -17,16 +17,13 @@ func check(input support.FirstInput) error { return nil } -func checkAdmin(input support.FirstInput) error { +func checkByAdmin(input support.FirstInput) error { if input.Title == "" { return fmt.Errorf("no data: title") } if input.Data == "" { return fmt.Errorf("no data: data") } - if input.GroupID == 0 { - return fmt.Errorf("no data: data") - } return nil } diff --git a/pkg/api/core/support/ticket/v0/ticket.go b/pkg/api/core/support/ticket/v0/ticket.go index d276e483..fe401656 100644 --- a/pkg/api/core/support/ticket/v0/ticket.go +++ b/pkg/api/core/support/ticket/v0/ticket.go @@ -15,7 +15,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/tool/notification" dbChat "github.com/homenoc/dsbd-backend/pkg/api/store/support/chat/v0" dbTicket "github.com/homenoc/dsbd-backend/pkg/api/store/support/ticket/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" @@ -36,26 +36,46 @@ func Create(c *gin.Context) { return } - // Group authentication - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) - return - } - // input check - if err := check(input); err != nil { + if err = check(input); err != nil { c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) return } + resultTicket := &core.Ticket{ + Solved: &[]bool{false}[0], + Title: input.Title, + Admin: &[]bool{false}[0], + Request: &[]bool{false}[0], + RequestReject: &[]bool{false}[0], + } + var groupValue string + + // isn't group + if !input.IsGroup { + result := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + resultTicket.GroupID = nil + resultTicket.UserID = &result.User.ID + groupValue = "個人ユーザ" + } else { + //is group + // Group authentication + result := auth.GroupAuthentication(1, core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + resultTicket.GroupID = result.User.GroupID + resultTicket.UserID = &result.User.ID + groupValue = strconv.Itoa(int(*resultTicket.GroupID)) + "-" + result.User.Group.Org + } + // Tickets DBに登録 - ticketResult, err := dbTicket.Create(&core.Ticket{ - GroupID: result.User.GroupID, - UserID: result.User.ID, - Solved: &[]bool{false}[0], - Title: input.Title, - }) + ticketResult, err := dbTicket.Create(resultTicket) if err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) return @@ -63,7 +83,7 @@ func Create(c *gin.Context) { // Chat DBに登録 _, err = dbChat.Create(&core.Chat{ - UserID: result.User.ID, + UserID: resultTicket.UserID, Admin: false, Data: input.Data, TicketID: ticketResult.ID, @@ -76,116 +96,135 @@ func Create(c *gin.Context) { //HomeNOC Slackに送信 attachment := slack.Attachment{} attachment.AddField(slack.Field{Title: "Title", Value: "新規チケット作成"}). - AddField(slack.Field{Title: "発行者", Value: strconv.Itoa(int(result.User.ID))}). - AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(result.User.GroupID)) + "-" + result.User.Group.Org}). + AddField(slack.Field{Title: "発行者", Value: strconv.Itoa(int(*resultTicket.UserID))}). + AddField(slack.Field{Title: "Group", Value: groupValue}). AddField(slack.Field{Title: "Title", Value: input.Title}). AddField(slack.Field{Title: "Message", Value: input.Data}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) - c.JSON(http.StatusOK, common.Result{}) + c.JSON(http.StatusOK, ticket.Ticket{ID: ticketResult.ID}) } -func Get(c *gin.Context) { +func Request(c *gin.Context) { + var input support.FirstInput userToken := c.Request.Header.Get("USER_TOKEN") accessToken := c.Request.Header.Get("ACCESS_TOKEN") - id, err := strconv.Atoi(c.Param("id")) + err := c.BindJSON(&input) if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: fmt.Sprintf("id error")}) + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) return } // Group authentication - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) + result := auth.GroupAuthentication(1, core.Token{UserToken: userToken, AccessToken: accessToken}) if result.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) return } - // IDからDBからチケットを検索 - resultTicket := dbTicket.Get(ticket.ID, &core.Ticket{Model: gorm.Model{ID: uint(id)}}) - if resultTicket.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: resultTicket.Err.Error()}) + // input check + if err = check(input); err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) return } - // GroupIDが一致しない場合はここでエラーを返す - if resultTicket.Tickets[0].GroupID != result.User.GroupID { - c.JSON(http.StatusForbidden, common.Error{Error: "Auth Error: group id failed..."}) - return + resultTicket := &core.Ticket{ + GroupID: result.User.GroupID, + UserID: &result.User.ID, + Solved: &[]bool{false}[0], + Title: input.Title, + Admin: &[]bool{false}[0], + Request: &[]bool{true}[0], + RequestReject: &[]bool{false}[0], } - var response ticket.Ticket - - var resultChat []ticket.Chat - for _, tmpChat := range resultTicket.Tickets[0].Chat { - resultChat = append(resultChat, ticket.Chat{ - Time: tmpChat.CreatedAt.Add(9 * time.Hour).Format(timeLayout), - UserID: tmpChat.UserID, - UserName: tmpChat.User.Name, - Admin: tmpChat.Admin, - Data: tmpChat.Data, - }) + // Tickets DBに登録 + ticketResult, err := dbTicket.Create(resultTicket) + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return } - response = ticket.Ticket{ - ID: resultTicket.Tickets[0].ID, - Time: resultTicket.Tickets[0].CreatedAt.Add(9 * time.Hour).Format(timeLayout), - GroupID: resultTicket.Tickets[0].GroupID, - UserID: resultTicket.Tickets[0].UserID, - Solved: resultTicket.Tickets[0].Solved, - Chat: resultChat, - Title: resultTicket.Tickets[0].Title, - UserName: resultTicket.Tickets[0].User.Name, + // Chat DBに登録 + _, err = dbChat.Create(&core.Chat{ + UserID: resultTicket.UserID, + Admin: false, + Data: input.Data, + TicketID: ticketResult.ID, + }) + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return } - c.JSON(http.StatusOK, ticket.Result{Ticket: response}) + //HomeNOC Slackに送信 + attachment := slack.Attachment{} + attachment.AddField(slack.Field{Title: "Title", Value: "[新規] 追加・変更手続き"}). + AddField(slack.Field{Title: "発行者", Value: strconv.Itoa(int(*resultTicket.UserID))}). + AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(*resultTicket.GroupID)) + "-" + result.User.Group.Org}). + AddField(slack.Field{Title: "Title", Value: input.Title}). + AddField(slack.Field{Title: "Message", Value: input.Data}) + notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) + + c.JSON(http.StatusOK, ticket.Ticket{ID: ticketResult.ID}) } -func GetAll(c *gin.Context) { +func Update(c *gin.Context) { + var input core.Ticket + userToken := c.Request.Header.Get("USER_TOKEN") accessToken := c.Request.Header.Get("ACCESS_TOKEN") - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) - if result.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + err := c.BindJSON(&input) + if err != nil { + log.Println(err) + c.JSON(http.StatusBadRequest, common.Error{Error: err.Error()}) + return + } + + id, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(http.StatusBadRequest, common.Error{Error: fmt.Sprintf("id error")}) return } - // Tickets DBからGroup IDのTicketデータを抽出 - resultTicket := dbTicket.Get(ticket.GID, &core.Ticket{GroupID: result.User.GroupID}) - if resultTicket.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: resultTicket.Err.Error()}) + // Tickets DBからデータを取得 + ticketResult := dbTicket.Get(ticket.ID, &core.Ticket{Model: gorm.Model{ID: uint(id)}}) + if ticketResult.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: ticketResult.Err.Error()}) return } - var response []ticket.Ticket - - for _, tmp := range resultTicket.Tickets { - var resultChat []ticket.Chat - for _, tmpChat := range tmp.Chat { - resultChat = append(resultChat, ticket.Chat{ - Time: tmpChat.CreatedAt.Add(9 * time.Hour).Format(timeLayout), - UserID: tmpChat.UserID, - UserName: tmpChat.User.Name, - Admin: tmpChat.Admin, - Data: tmpChat.Data, - }) - } + updateTicketData := ticketResult.Tickets[0] - response = append(response, ticket.Ticket{ - ID: tmp.ID, - Time: tmp.CreatedAt.Add(9 * time.Hour).Format(timeLayout), - GroupID: tmp.GroupID, - UserID: tmp.UserID, - Solved: tmp.Solved, - Chat: resultChat, - Title: tmp.Title, - UserName: tmp.User.Name, - }) + // isn't group + if ticketResult.Tickets[0].GroupID == nil { + result := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + } else { + //is group + // Group authentication + result := auth.GroupAuthentication(1, core.Token{UserToken: userToken, AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } } - c.JSON(http.StatusOK, ticket.ResultAll{Tickets: response}) + updateTicketData.Solved = input.Solved + + // Ticketのアップデート + err = dbTicket.Update(ticket.UpdateAll, updateTicketData) + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + c.JSON(http.StatusOK, support.Result{}) } func GetWebSocket(c *gin.Context) { @@ -210,7 +249,7 @@ func GetWebSocket(c *gin.Context) { defer conn.Close() - result := auth.GroupAuthentication(0, core.Token{UserToken: userToken, AccessToken: accessToken}) + result := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) if result.Err != nil { log.Println("ws:// support error:Auth error") conn.WriteMessage(websocket.TextMessage, []byte("error: auth error")) @@ -224,8 +263,25 @@ func GetWebSocket(c *gin.Context) { return } - if ticketResult.Tickets[0].ID != uint(id) { - log.Println("ticketID not match.") + // [group ticket] check groupID + if ticketResult.Tickets[0].GroupID != nil { + // [group ticket] check groupID + if *ticketResult.Tickets[0].GroupID != *result.User.GroupID { + log.Println("groupID not match.") + return + } + } else { + // [user ticket] check userID + if ticketResult.Tickets[0].UserID != nil && *ticketResult.Tickets[0].UserID != result.User.ID { + log.Println("userID not match.") + return + } + } + + var groupID uint = 0 + + if ticketResult.Tickets[0].GroupID != nil { + groupID = *ticketResult.Tickets[0].GroupID } // WebSocket送信 @@ -234,7 +290,7 @@ func GetWebSocket(c *gin.Context) { Admin: false, UserID: result.User.ID, UserName: result.User.Name, - GroupID: result.User.GroupID, + GroupID: groupID, Socket: conn, }] = true @@ -249,46 +305,52 @@ func GetWebSocket(c *gin.Context) { Admin: false, UserID: result.User.ID, UserName: result.User.Name, - GroupID: result.User.GroupID, + GroupID: groupID, Socket: conn, }) break } // 入力されたデータをTokenにて認証 - resultGroup := auth.GroupAuthentication(0, core.Token{ + resultAuth := auth.UserAuthentication(core.Token{ UserToken: msg.UserToken, AccessToken: msg.AccessToken, }) - if resultGroup.Err != nil { - log.Println(resultGroup.Err) + if resultAuth.Err != nil { + log.Println(resultAuth.Err) + return + } + + if result.User.ID != resultAuth.User.ID { + log.Println("UserID is not match") return } if !*ticketResult.Tickets[0].Solved { _, err = dbChat.Create(&core.Chat{ TicketID: ticketResult.Tickets[0].ID, - UserID: result.User.ID, + UserID: &result.User.ID, Admin: false, Data: msg.Message, }) if err != nil { conn.WriteJSON(&support.WebSocketResult{Err: "db write error"}) } else { - + msg.TicketID = ticketResult.Tickets[0].ID msg.UserID = result.User.ID - msg.GroupID = resultGroup.User.GroupID + msg.GroupID = groupID msg.Admin = false msg.UserName = result.User.Name // Token関連の初期化 msg.AccessToken = "" msg.UserToken = "" - //ユーザ側に送信 + //管理側に送信 controller.SendChatUser(controllerInterface.Chat{ + TicketID: ticketResult.Tickets[0].ID, CreatedAt: msg.CreatedAt, UserID: result.User.ID, UserName: result.User.Name, - GroupID: resultGroup.User.GroupID, + GroupID: groupID, Admin: msg.Admin, Message: msg.Message, }) @@ -297,7 +359,7 @@ func GetWebSocket(c *gin.Context) { attachment := slack.Attachment{} attachment.AddField(slack.Field{Title: "Title", Value: "Support(新規メッセージ)"}). AddField(slack.Field{Title: "発行者", Value: strconv.Itoa(int(result.User.ID)) + "-" + result.User.Name}). - AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(result.User.GroupID)) + "-" + result.User.Group.Org}). + AddField(slack.Field{Title: "Group", Value: strconv.Itoa(int(*result.User.GroupID)) + "-" + result.User.Group.Org}). AddField(slack.Field{Title: "Title", Value: ticketResult.Tickets[0].Title}). AddField(slack.Field{Title: "Message", Value: msg.Message}) notification.SendSlack(notification.Slack{Attachment: attachment, ID: "main", Status: true}) @@ -315,24 +377,38 @@ func HandleMessages() { //登録されているクライアント宛にデータ送信する for client := range support.Clients { // ユーザのみの場合 - if client.GroupID == 0 { - return - } else if client.GroupID == msg.GroupID { - err := client.Socket.WriteJSON(support.WebSocketChatResponse{ - Time: time.Now().UTC().Add(9 * time.Hour).Format(timeLayout), - UserID: msg.UserID, - UserName: msg.UserName, - GroupID: msg.GroupID, - Admin: msg.Admin, - Message: msg.Message, - }) - if err != nil { - log.Printf("error: %v", err) - client.Socket.Close() - delete(support.Clients, client) + if client.TicketID == msg.TicketID { + if msg.GroupID == 0 && client.GroupID == 0 && client.UserID == msg.UserID { + err := client.Socket.WriteJSON(support.WebSocketChatResponse{ + Time: time.Now().UTC().Add(9 * time.Hour).Format(timeLayout), + UserID: msg.UserID, + UserName: msg.UserName, + GroupID: 0, + Admin: msg.Admin, + Message: msg.Message, + }) + if err != nil { + log.Printf("error: %v", err) + client.Socket.Close() + delete(support.Clients, client) + } + } else if client.GroupID == msg.GroupID { + err := client.Socket.WriteJSON(support.WebSocketChatResponse{ + Time: time.Now().UTC().Add(9 * time.Hour).Format(timeLayout), + UserID: msg.UserID, + UserName: msg.UserName, + GroupID: msg.GroupID, + Admin: msg.Admin, + Message: msg.Message, + }) + if err != nil { + log.Printf("error: %v", err) + client.Socket.Close() + delete(support.Clients, client) + } + } else { + // 認証失敗時の処理 } - } else { - // 認証失敗時の処理 } } } diff --git a/pkg/api/core/support/ticket/v0/update.go b/pkg/api/core/support/ticket/v0/update.go index 4b82fddd..c8f2b213 100644 --- a/pkg/api/core/support/ticket/v0/update.go +++ b/pkg/api/core/support/ticket/v0/update.go @@ -23,6 +23,10 @@ func updateAdminTicket(input, replace core.Ticket) (core.Ticket, error) { if input.GroupID != replace.GroupID { replace.GroupID = input.GroupID } + //RequestReject + if input.RequestReject != replace.RequestReject { + replace.RequestReject = input.RequestReject + } return replace, nil } diff --git a/pkg/api/core/template/connection/v0/admin.go b/pkg/api/core/template/connection/v0/admin.go index 8cd6915e..0cca1833 100644 --- a/pkg/api/core/template/connection/v0/admin.go +++ b/pkg/api/core/template/connection/v0/admin.go @@ -8,13 +8,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/notice" "github.com/homenoc/dsbd-backend/pkg/api/core/template/connection" dbConnectionTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/connection/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.ConnectionTemplate resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -41,7 +41,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -61,7 +61,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.ConnectionTemplate resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -85,7 +85,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -105,7 +105,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, connection.Result{Connections: result.Connections}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/template/interface.go b/pkg/api/core/template/interface.go index 76397674..3c59ae28 100644 --- a/pkg/api/core/template/interface.go +++ b/pkg/api/core/template/interface.go @@ -14,15 +14,39 @@ type Input struct { } type Result struct { - Services []core.ServiceTemplate `json:"services"` - Connections []core.ConnectionTemplate `json:"connections"` - NTTs []core.NTTTemplate `json:"ntts"` - NOC []core.NOC `json:"nocs"` - BGPRouter []core.BGPRouter `json:"bgp_router"` - TunnelEndPointRouter []core.TunnelEndPointRouter `json:"tunnel_endpoint_router"` - TunnelEndPointRouterIP []core.TunnelEndPointRouterIP `json:"tunnel_endpoint_router_ip"` - IPv4 []core.IPv4Template `json:"ipv4"` - IPv6 []core.IPv6Template `json:"ipv6"` + Services []core.ServiceTemplate `json:"services"` + Connections []core.ConnectionTemplate `json:"connections"` + NTTs []core.NTTTemplate `json:"ntts"` + NOC []core.NOC `json:"nocs"` + BGPRouter []core.BGPRouter `json:"bgp_router"` + TunnelEndPointRouter []core.TunnelEndPointRouter `json:"tunnel_endpoint_router"` + TunnelEndPointRouterIP []core.TunnelEndPointRouterIP `json:"tunnel_endpoint_router_ip"` + IPv4 []core.IPv4Template `json:"ipv4"` + IPv6 []core.IPv6Template `json:"ipv6"` + IPv4Route []core.IPv4RouteTemplate `json:"ipv4_route"` + IPv6Route []core.IPv6RouteTemplate `json:"ipv6_route"` + PaymentMembershipTemplate []core.PaymentMembershipTemplate `json:"payment_membership_template"` + PaymentDonateTemplate []core.PaymentDonateTemplate `json:"payment_donate_template"` + PaymentCouponTemplate []core.PaymentCouponTemplate `json:"payment_coupon_template"` +} + +type ResultAdmin struct { + Services []core.ServiceTemplate `json:"services"` + Connections []core.ConnectionTemplate `json:"connections"` + NTTs []core.NTTTemplate `json:"ntts"` + NOC []core.NOC `json:"nocs"` + BGPRouter []core.BGPRouter `json:"bgp_router"` + TunnelEndPointRouter []core.TunnelEndPointRouter `json:"tunnel_endpoint_router"` + TunnelEndPointRouterIP []core.TunnelEndPointRouterIP `json:"tunnel_endpoint_router_ip"` + IPv4 []core.IPv4Template `json:"ipv4"` + IPv6 []core.IPv6Template `json:"ipv6"` + IPv4Route []core.IPv4RouteTemplate `json:"ipv4_route"` + IPv6Route []core.IPv6RouteTemplate `json:"ipv6_route"` + User []core.User `json:"user"` + Group []core.Group `json:"group"` + PaymentMembershipTemplate []core.PaymentMembershipTemplate `json:"payment_membership_template"` + PaymentDonateTemplate []core.PaymentDonateTemplate `json:"payment_donate_template"` + PaymentCouponTemplate []core.PaymentCouponTemplate `json:"payment_coupon_template"` } type ResultDatabase struct { diff --git a/pkg/api/core/template/ipv4/v0/admin.go b/pkg/api/core/template/ipv4/v0/admin.go index a566b18c..8deda80a 100644 --- a/pkg/api/core/template/ipv4/v0/admin.go +++ b/pkg/api/core/template/ipv4/v0/admin.go @@ -8,13 +8,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/notice" ipv4 "github.com/homenoc/dsbd-backend/pkg/api/core/template/ipv4" dbIPv4Template "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.IPv4Template resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -41,7 +41,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -61,7 +61,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.IPv4Template resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -85,7 +85,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -105,7 +105,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, ipv4.Result{IPv4: result.IPv4}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/template/ipv6/v0/admin.go b/pkg/api/core/template/ipv6/v0/admin.go index b053bcd7..ac2c3da6 100644 --- a/pkg/api/core/template/ipv6/v0/admin.go +++ b/pkg/api/core/template/ipv6/v0/admin.go @@ -8,13 +8,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/notice" ipv6 "github.com/homenoc/dsbd-backend/pkg/api/core/template/ipv6" dbIPv6Template "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.IPv6Template resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -41,7 +41,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -61,7 +61,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.IPv6Template resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -85,7 +85,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, notice.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -105,7 +105,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, ipv6.Result{IPv6: result.IPv6}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/template/ntt/v0/admin.go b/pkg/api/core/template/ntt/v0/admin.go index b9e0ea5d..fcd68efc 100644 --- a/pkg/api/core/template/ntt/v0/admin.go +++ b/pkg/api/core/template/ntt/v0/admin.go @@ -8,13 +8,13 @@ import ( ntt "github.com/homenoc/dsbd-backend/pkg/api/core/template/ntt" "github.com/homenoc/dsbd-backend/pkg/api/core/template/service" dbNTTTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ntt/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.NTTTemplate resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -41,7 +41,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, ntt.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -61,7 +61,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, ntt.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.NTTTemplate resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -85,7 +85,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, ntt.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -105,7 +105,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, ntt.Result{NTTs: result.NTTs}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/template/service/v0/admin.go b/pkg/api/core/template/service/v0/admin.go index c0464295..4faf64d4 100644 --- a/pkg/api/core/template/service/v0/admin.go +++ b/pkg/api/core/template/service/v0/admin.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/template/service" dbServiceTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/service/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.ServiceTemplate resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -40,7 +40,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, service.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -60,7 +60,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, service.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.ServiceTemplate resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -84,7 +84,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, service.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -104,7 +104,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, service.Result{Services: result.Services}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/template/v0/admin.go b/pkg/api/core/template/v0/admin.go index cd13cd5c..bb57fd3a 100644 --- a/pkg/api/core/template/v0/admin.go +++ b/pkg/api/core/template/v0/admin.go @@ -5,18 +5,25 @@ import ( auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" template "github.com/homenoc/dsbd-backend/pkg/api/core/template" + dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" dbBGPRouter "github.com/homenoc/dsbd-backend/pkg/api/store/noc/bgpRouter/v0" dbTunnelEndPointRouterIP "github.com/homenoc/dsbd-backend/pkg/api/store/noc/tunnelEndPointRouterIP/v0" dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" dbConnectionTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/connection/v0" dbIPv4Template "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4/v0" + dbIPv4RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4_route/v0" dbIPv6Template "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6/v0" + dbIPv6RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6_route/v0" dbNTTTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ntt/v0" + dbPaymentCouponTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_coupon/v0" + dbPaymentDonateTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_donate/v0" + dbPaymentMembershipTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_membership/v0" dbServiceTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/service/v0" + dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" "net/http" ) -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -68,14 +75,60 @@ func GetAdmin(c *gin.Context) { return } - c.JSON(http.StatusOK, template.Result{ - Services: resultService.Services, - Connections: resultConnection.Connections, - NTTs: resultNTT.NTTs, - NOC: resultNOC.NOC, - BGPRouter: resultBGPRouter.BGPRouter, - TunnelEndPointRouterIP: resultTunnelEndPointRouterIP.TunnelEndPointRouterIP, - IPv4: resultIPv4.IPv4, - IPv6: resultIPv6.IPv6, + resultIPv4Route, err := dbIPv4RouteTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + resultIPv6Route, err := dbIPv6RouteTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + resultUser := dbUser.GetAll() + if resultUser.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: resultUser.Err.Error()}) + return + } + + resultGroup := dbGroup.GetAll() + if resultGroup.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: resultGroup.Err.Error()}) + return + } + + resultPaymentMembership, err := dbPaymentMembershipTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + resultDonateMembership, err := dbPaymentDonateTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + resultPaymentCoupon, err := dbPaymentCouponTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + c.JSON(http.StatusOK, template.ResultAdmin{ + Services: resultService.Services, + Connections: resultConnection.Connections, + NTTs: resultNTT.NTTs, + NOC: resultNOC.NOC, + BGPRouter: resultBGPRouter.BGPRouter, + TunnelEndPointRouterIP: resultTunnelEndPointRouterIP.TunnelEndPointRouterIP, + IPv4: resultIPv4.IPv4, + IPv6: resultIPv6.IPv6, + IPv4Route: resultIPv4Route, + IPv6Route: resultIPv6Route, + User: resultUser.User, + Group: resultGroup.Group, + PaymentMembershipTemplate: resultPaymentMembership, + PaymentDonateTemplate: resultDonateMembership, + PaymentCouponTemplate: resultPaymentCoupon, }) } diff --git a/pkg/api/core/template/v0/template.go b/pkg/api/core/template/v0/template.go index 18a96f23..b5c8266c 100644 --- a/pkg/api/core/template/v0/template.go +++ b/pkg/api/core/template/v0/template.go @@ -6,10 +6,16 @@ import ( auth "github.com/homenoc/dsbd-backend/pkg/api/core/auth/v0" "github.com/homenoc/dsbd-backend/pkg/api/core/common" template "github.com/homenoc/dsbd-backend/pkg/api/core/template" + dbNOC "github.com/homenoc/dsbd-backend/pkg/api/store/noc/v0" dbConnectionTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/connection/v0" dbIPv4Template "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4/v0" + dbIPv4RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv4_route/v0" dbIPv6Template "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6/v0" + dbIPv6RouteTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ipv6_route/v0" dbNTTTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/ntt/v0" + dbPaymentCouponTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_coupon/v0" + dbPaymentDonateTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_donate/v0" + dbPaymentMembershipTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/payment_membership/v0" dbServiceTemplate "github.com/homenoc/dsbd-backend/pkg/api/store/template/service/v0" "net/http" ) @@ -39,6 +45,12 @@ func Get(c *gin.Context) { c.JSON(http.StatusInternalServerError, common.Error{Error: resultNTT.Err.Error()}) return } + resultNOC := dbNOC.GetAll() + if resultNOC.Err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: resultNTT.Err.Error()}) + return + } + resultIPv4 := dbIPv4Template.GetAll() if resultIPv4.Err != nil { c.JSON(http.StatusInternalServerError, common.Error{Error: resultIPv4.Err.Error()}) @@ -50,11 +62,44 @@ func Get(c *gin.Context) { return } + resultIPv4Route, err := dbIPv4RouteTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + resultIPv6Route, err := dbIPv6RouteTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + + resultPaymentMembership, err := dbPaymentMembershipTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + resultDonateMembership, err := dbPaymentDonateTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + resultPaymentCoupon, err := dbPaymentCouponTemplate.GetAll() + if err != nil { + c.JSON(http.StatusInternalServerError, common.Error{Error: err.Error()}) + return + } + c.JSON(http.StatusOK, template.Result{ - Services: resultService.Services, - Connections: resultConnection.Connections, - NTTs: resultNTT.NTTs, - IPv4: resultIPv4.IPv4, - IPv6: resultIPv6.IPv6, + Services: resultService.Services, + Connections: resultConnection.Connections, + NTTs: resultNTT.NTTs, + NOC: resultNOC.NOC, + IPv4: resultIPv4.IPv4, + IPv6: resultIPv6.IPv6, + IPv4Route: resultIPv4Route, + IPv6Route: resultIPv6Route, + PaymentMembershipTemplate: resultPaymentMembership, + PaymentDonateTemplate: resultDonateMembership, + PaymentCouponTemplate: resultPaymentCoupon, }) } diff --git a/pkg/api/core/token/interface.go b/pkg/api/core/token/interface.go index 85151e7d..1f9f8bb3 100644 --- a/pkg/api/core/token/interface.go +++ b/pkg/api/core/token/interface.go @@ -8,7 +8,8 @@ const ( ID = 0 UserToken = 10 UserTokenAndAccessToken = 11 - ExpiredTime = 12 + AccessToken = 12 + ExpiredTime = 13 AdminToken = 20 AddToken = 100 UpdateToken = 101 diff --git a/pkg/api/core/token/v0/admin.go b/pkg/api/core/token/v0/admin.go index 1afc6d4e..5622da62 100644 --- a/pkg/api/core/token/v0/admin.go +++ b/pkg/api/core/token/v0/admin.go @@ -9,14 +9,14 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/token" toolToken "github.com/homenoc/dsbd-backend/pkg/api/core/tool/token" dbToken "github.com/homenoc/dsbd-backend/pkg/api/store/token/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" "time" ) -func GenerateAdmin(c *gin.Context) { +func GenerateByAdmin(c *gin.Context) { resultAuth := auth.AdminRadiusAuthentication(authInterface.AdminStruct{ User: c.Request.Header.Get("USER"), Pass: c.Request.Header.Get("PASS")}) if resultAuth.Err != nil { @@ -26,7 +26,7 @@ func GenerateAdmin(c *gin.Context) { accessToken, _ := toolToken.Generate(2) if err := dbToken.Create(&core.Token{ - UserID: 0, + UserID: nil, ExpiredAt: time.Now().Add(60 * time.Minute), Admin: &[]bool{true}[0], AccessToken: accessToken, @@ -38,7 +38,7 @@ func GenerateAdmin(c *gin.Context) { c.JSON(http.StatusOK, token.Result{Token: []core.Token{{AccessToken: accessToken}}}) } -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.Token resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -67,7 +67,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, token.ResultTmpToken{Token: accessToken}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -87,7 +87,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, token.Result{}) } -func DeleteAllAdmin(c *gin.Context) { +func DeleteAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -102,7 +102,7 @@ func DeleteAllAdmin(c *gin.Context) { c.JSON(http.StatusOK, token.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.Token resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -125,7 +125,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, token.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -145,7 +145,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, token.Result{Token: result.Token}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/token/v0/remove.go b/pkg/api/core/token/v0/remove.go index df235ab1..b2b862d5 100644 --- a/pkg/api/core/token/v0/remove.go +++ b/pkg/api/core/token/v0/remove.go @@ -4,7 +4,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/token" dbToken "github.com/homenoc/dsbd-backend/pkg/api/store/token/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) diff --git a/pkg/api/core/token/v0/token.go b/pkg/api/core/token/v0/token.go index 0766653a..52f3570c 100644 --- a/pkg/api/core/token/v0/token.go +++ b/pkg/api/core/token/v0/token.go @@ -12,7 +12,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/user" dbToken "github.com/homenoc/dsbd-backend/pkg/api/store/token/v0" dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" @@ -27,7 +27,7 @@ func GenerateInit(c *gin.Context) { tmpToken, _ := toolToken.Generate(2) err := dbToken.Create(&core.Token{ ExpiredAt: time.Now().Add(30 * time.Minute), - UserID: 0, + UserID: nil, Status: 0, UserToken: userToken, TmpToken: tmpToken, @@ -84,7 +84,7 @@ func Generate(c *gin.Context) { accessToken, _ := toolToken.Generate(2) err := dbToken.Update(token.AddToken, &core.Token{Model: gorm.Model{ID: tokenResult.Token[0].Model.ID}, ExpiredAt: time.Now().Add(30 * time.Minute), - UserID: userResult.User[0].ID, + UserID: &userResult.User[0].ID, Status: 1, AccessToken: accessToken, }) @@ -110,6 +110,11 @@ func Delete(c *gin.Context) { return } + if len(result.Token) == 0 { + c.JSON(http.StatusUnauthorized, common.Error{Error: "Error: Unauthorized..."}) + return + } + logging.WriteLog(strconv.Itoa(int(result.Token[0].User.ID))+"-"+result.Token[0].User.Name, "Logout") if err := dbToken.Delete(&core.Token{Model: gorm.Model{ID: result.Token[0].ID}}); err != nil { @@ -120,3 +125,21 @@ func Delete(c *gin.Context) { c.JSON(http.StatusOK, common.Result{}) } + +func DeleteAdminUser(c *gin.Context) { + accessToken := c.Request.Header.Get("ACCESS_TOKEN") + + result := dbToken.Get(token.AccessToken, &core.Token{AccessToken: accessToken}) + if result.Err != nil { + c.JSON(http.StatusUnauthorized, common.Error{Error: result.Err.Error()}) + return + } + + if err := dbToken.Delete(&core.Token{Model: gorm.Model{ID: result.Token[0].ID}}); err != nil { + //エラー時はTokenがすでに消えている状態なので、問題なし + c.JSON(http.StatusOK, common.Result{}) + return + } + + c.JSON(http.StatusOK, common.Result{}) +} diff --git a/pkg/api/core/tool/config/config.go b/pkg/api/core/tool/config/config.go index c49b36d3..40e54217 100644 --- a/pkg/api/core/tool/config/config.go +++ b/pkg/api/core/tool/config/config.go @@ -9,6 +9,7 @@ type Config struct { Controller Controller `json:"controller"` Web Web `json:"web"` DB DB `json:"db"` + Stripe Stripe `json:"stripe"` Mail Mail `json:"mail"` Radius Radius `json:"radius"` Slack []Slack `json:"slack"` @@ -16,9 +17,10 @@ type Config struct { } type Controller struct { - User User `json:"user"` - Admin Admin `json:"admin"` - Auth Auth `json:"auth"` + User User `json:"user"` + Admin Admin `json:"admin"` + Auth Auth `json:"auth"` + TimeZone string `json:"timezone"` } type User struct { @@ -37,6 +39,11 @@ type Web struct { URL string `json:"url"` } +type Stripe struct { + WebhookSecretKey string `json:"webhook_secret_key"` + SecretKey string `json:"secret_key"` +} + type AdminAuth struct { User string `json:"user"` Pass string `json:"pass"` diff --git a/pkg/api/core/tool/slack/slack.go b/pkg/api/core/tool/slack/slack.go new file mode 100644 index 00000000..9f42409b --- /dev/null +++ b/pkg/api/core/tool/slack/slack.go @@ -0,0 +1,13 @@ +package slack + +func NoticeSlackType(slackType uint) string { + if slackType == 0 { + return "追加" + } else if slackType == 1 { + return "削除" + } else if slackType == 1 { + return "更新" + } else { + return "" + } +} diff --git a/pkg/api/core/user/interface.go b/pkg/api/core/user/interface.go index d1f2f99e..d2912229 100644 --- a/pkg/api/core/user/interface.go +++ b/pkg/api/core/user/interface.go @@ -2,10 +2,12 @@ package user import ( "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/info" ) const ( ID = 0 + IDDetail = 10 GID = 1 Name = 2 Email = 3 @@ -48,15 +50,20 @@ type SimpleGroup struct { } type ResultOne struct { - ID uint `json:"id"` - GroupID uint `json:"group_id"` - Name string `json:"name"` - NameEn string `json:"name_en"` - Email string `json:"email"` - Status uint `json:"status"` - Level uint `json:"level"` - MailVerify *bool `json:"mail_verify"` - Group *SimpleGroup `json:"group"` + User SimpleUser `json:"user"` + Group SimpleGroup `json:"group"` + Info []info.Info `json:"info"` +} + +type SimpleUser struct { + ID uint `json:"id"` + GroupID uint `json:"group_id"` + Name string `json:"name"` + NameEn string `json:"name_en"` + Email string `json:"email"` + Status uint `json:"status"` + Level uint `json:"level"` + MailVerify *bool `json:"mail_verify"` } type Result struct { diff --git a/pkg/api/core/user/v0/admin.go b/pkg/api/core/user/v0/admin.go index bb4deed8..eccf1c4e 100644 --- a/pkg/api/core/user/v0/admin.go +++ b/pkg/api/core/user/v0/admin.go @@ -7,13 +7,13 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/common" "github.com/homenoc/dsbd-backend/pkg/api/core/user" dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" ) -func AddAdmin(c *gin.Context) { +func AddByAdmin(c *gin.Context) { var input core.User resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -47,7 +47,7 @@ func AddAdmin(c *gin.Context) { c.JSON(http.StatusOK, user.Result{}) } -func DeleteAdmin(c *gin.Context) { +func DeleteByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -67,7 +67,7 @@ func DeleteAdmin(c *gin.Context) { c.JSON(http.StatusOK, user.Result{}) } -func UpdateAdmin(c *gin.Context) { +func UpdateByAdmin(c *gin.Context) { var input core.User resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) @@ -102,7 +102,7 @@ func UpdateAdmin(c *gin.Context) { c.JSON(http.StatusOK, user.Result{}) } -func GetAdmin(c *gin.Context) { +func GetByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) @@ -122,7 +122,7 @@ func GetAdmin(c *gin.Context) { c.JSON(http.StatusOK, user.ResultAdmin{User: result.User}) } -func GetAllAdmin(c *gin.Context) { +func GetAllByAdmin(c *gin.Context) { resultAdmin := auth.AdminAuthentication(c.Request.Header.Get("ACCESS_TOKEN")) if resultAdmin.Err != nil { c.JSON(http.StatusUnauthorized, common.Error{Error: resultAdmin.Err.Error()}) diff --git a/pkg/api/core/user/v0/user.go b/pkg/api/core/user/v0/user.go index 75c156c1..dfa2e7bc 100644 --- a/pkg/api/core/user/v0/user.go +++ b/pkg/api/core/user/v0/user.go @@ -18,7 +18,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/user" dbGroup "github.com/homenoc/dsbd-backend/pkg/api/store/group/v0" dbUser "github.com/homenoc/dsbd-backend/pkg/api/store/user/v0" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "net/http" "strconv" @@ -50,7 +50,7 @@ func Add(c *gin.Context) { } data = core.User{ - GroupID: 0, + GroupID: nil, Name: input.Name, NameEn: input.NameEn, Email: input.Email, @@ -64,11 +64,10 @@ func Add(c *gin.Context) { //check exist for database result := dbUser.Get(user.Email, &core.User{Email: input.Email}) if result.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: result.Err.Error()}) - return + log.Println(result.Err) } - if len(result.User) != 0 { + if len(result.User) != 0 && result.Err == nil { c.JSON(http.StatusBadRequest, common.Error{Error: "this email is already registered: \" + u.Email"}) return } @@ -148,7 +147,12 @@ func AddGroup(c *gin.Context) { return } - if resultAuth.User.GroupID != uint(id) { + if resultAuth.User.GroupID == nil { + c.JSON(http.StatusBadRequest, common.Error{Error: "error: group is not found"}) + return + } + + if *resultAuth.User.GroupID != uint(id) { c.JSON(http.StatusBadRequest, common.Error{Error: "error: group id is invalid"}) return } @@ -310,7 +314,7 @@ func Update(c *gin.Context) { if authResult.User.ID == uint(id) || id == 0 { serverData = authResult.User } else { - if authResult.User.GroupID == 0 { + if authResult.User.GroupID == nil { c.JSON(http.StatusForbidden, common.Error{Error: "error: Group ID = 0"}) return } @@ -344,138 +348,3 @@ func Update(c *gin.Context) { c.JSON(http.StatusOK, user.Result{}) } } - -func Get(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - id, err := strconv.Atoi(c.Param("id")) - if err != nil { - c.JSON(http.StatusBadRequest, common.Error{Error: fmt.Sprintf("id error")}) - return - } - - authResult := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) - authResult.User.Pass = "" - authResult.User.MailToken = "" - if authResult.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: authResult.Err.Error()}) - return - } - - var tmpUser core.User - - if authResult.User.ID == uint(id) { - tmpUser = authResult.User - } else if authResult.User.GroupID != 0 { - if authResult.User.Level >= 3 { - c.JSON(http.StatusForbidden, common.Error{Error: "You don't have the authority."}) - return - } - - resultUser := dbUser.Get(user.ID, &core.User{Model: gorm.Model{ID: uint(id)}}) - if resultUser.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: resultUser.Err.Error()}) - return - } - - if resultUser.User[0].GroupID != authResult.User.GroupID { - c.JSON(http.StatusBadRequest, common.Error{Error: "GroupID is not match."}) - return - } - tmpUser = resultUser.User[0] - } - - c.JSON(http.StatusOK, user.ResultOne{ - ID: tmpUser.ID, - GroupID: tmpUser.GroupID, - Name: tmpUser.Name, - NameEn: tmpUser.NameEn, - Email: tmpUser.Email, - Level: tmpUser.Level, - MailVerify: tmpUser.MailVerify, - }) -} - -func GetOwn(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - authResult := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) - authResult.User.Pass = "" - authResult.User.MailToken = "" - - var simpleGroup *user.SimpleGroup = nil - - if authResult.User.Group != nil { - simpleGroup = &user.SimpleGroup{ - ID: authResult.User.Group.ID, - Student: authResult.User.Group.Student, - Pass: authResult.User.Group.Pass, - Lock: authResult.User.Group.Lock, - ExpiredStatus: authResult.User.Group.ExpiredStatus, - Status: authResult.User.Group.Status, - } - } - - if authResult.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: authResult.Err.Error()}) - } else { - c.JSON(http.StatusOK, user.ResultOne{ - ID: authResult.User.ID, - GroupID: authResult.User.GroupID, - Name: authResult.User.Name, - NameEn: authResult.User.NameEn, - Email: authResult.User.Email, - Level: authResult.User.Level, - MailVerify: authResult.User.MailVerify, - Group: simpleGroup, - }) - } -} - -func GetGroup(c *gin.Context) { - userToken := c.Request.Header.Get("USER_TOKEN") - accessToken := c.Request.Header.Get("ACCESS_TOKEN") - - authUserResult := auth.UserAuthentication(core.Token{UserToken: userToken, AccessToken: accessToken}) - if authUserResult.Err != nil { - c.JSON(http.StatusUnauthorized, common.Error{Error: authUserResult.Err.Error()}) - return - } - - var data user.Result - - if authUserResult.User.GroupID != 0 && authUserResult.User.Level < 3 { - resultGroupUser := dbUser.Get(user.GID, &core.User{GroupID: authUserResult.User.GroupID}) - if resultGroupUser.Err != nil { - c.JSON(http.StatusInternalServerError, common.Error{Error: resultGroupUser.Err.Error()}) - return - } - - for _, grp := range resultGroupUser.User { - data.User = append(data.User, user.ResultOne{ - ID: grp.ID, - GroupID: grp.GroupID, - Name: grp.Name, - NameEn: grp.NameEn, - Email: grp.Email, - Level: grp.Level, - MailVerify: grp.MailVerify, - }) - } - } else { - // User権限がLevel=2の時、又はユーザのGroupIDが0の時(グループ未登録時) - data.User = append(data.User, user.ResultOne{ - ID: authUserResult.User.ID, - GroupID: authUserResult.User.GroupID, - Name: authUserResult.User.Name, - NameEn: authUserResult.User.NameEn, - Email: authUserResult.User.Email, - Level: authUserResult.User.Level, - MailVerify: authUserResult.User.MailVerify, - }) - } - - c.JSON(http.StatusOK, data) -} diff --git a/pkg/api/store/group/connection/v0/connection.go b/pkg/api/store/group/connection/v0/connection.go index 017102fe..404b7e55 100644 --- a/pkg/api/store/group/connection/v0/connection.go +++ b/pkg/api/store/group/connection/v0/connection.go @@ -2,10 +2,10 @@ package v0 import ( "fmt" - core "github.com/homenoc/dsbd-backend/pkg/api/core" - connection "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/group/connection" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(connection *core.Connection) (*core.Connection, error) { log.Println("database connection error") return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&connection).Error return connection, err @@ -28,7 +33,12 @@ func Delete(connection *core.Connection) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(connection).Error } @@ -39,26 +49,31 @@ func Update(base int, c core.Connection) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if connection.UpdateInfo == base { - result = db.Model(&core.Connection{Model: gorm.Model{ID: c.ID}}).Update(core.Connection{ + err = db.Model(&core.Connection{Model: gorm.Model{ID: c.ID}}).Updates(core.Connection{ NTTTemplateID: c.NTTTemplateID, NOC: c.NOC, TermIP: c.TermIP, Monitor: c.Monitor, - }) + }).Error } else if connection.UpdateServiceID == base { - result = db.Model(&core.Connection{Model: gorm.Model{ID: c.ID}}).Update(core.Connection{ServiceID: c.ServiceID}) + err = db.Model(&core.Connection{Model: gorm.Model{ID: c.ID}}).Updates(core.Connection{ServiceID: c.ServiceID}).Error } else if base == connection.UpdateAll { - result = db.Model(&core.Connection{Model: gorm.Model{ID: c.ID}}).Update(c) + err = db.Model(&core.Connection{Model: gorm.Model{ID: c.ID}}).Updates(c).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.Connection) connection.ResultDatabase { @@ -67,7 +82,12 @@ func Get(base int, data *core.Connection) connection.ResultDatabase { log.Println("database connection error") return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var connectionStruct []core.Connection @@ -83,6 +103,18 @@ func Get(base int, data *core.Connection) connection.ResultDatabase { First(&connectionStruct, data.ID).Error } else if base == connection.ServiceID { err = db.Where("service_id = ?", data.ServiceID).Find(&connectionStruct).Error + } else if base == connection.NOCID { + err = db.Preload("ConnectionTemplate"). + Preload("NOC"). + Preload("BGPRouter"). + Preload("TunnelEndPointRouterIP"). + Preload("NTTTemplate"). + Preload("Service"). + Preload("Service.Group"). + Preload("Service.ServiceTemplate"). + Preload("Service.Group.User"). + Where("noc_id = ?", data.NOCID). + Find(&connectionStruct).Error } else { log.Println("base select error") return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: base select\n", time.Now())} @@ -96,7 +128,12 @@ func GetAll() connection.ResultDatabase { log.Println("database connection error") return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var connections []core.Connection err = db.Preload("ConnectionTemplate"). @@ -104,6 +141,9 @@ func GetAll() connection.ResultDatabase { Preload("NOC"). Preload("BGPRouter"). Preload("TunnelEndPointRouterIP"). + Preload("Service"). + Preload("Service.ServiceTemplate"). + Preload("Service.Group"). Find(&connections).Error return connection.ResultDatabase{Connection: connections, Err: err} diff --git a/pkg/api/store/group/memo/v0/memo.go b/pkg/api/store/group/memo/v0/memo.go new file mode 100644 index 00000000..c9833a6f --- /dev/null +++ b/pkg/api/store/group/memo/v0/memo.go @@ -0,0 +1,61 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(connection *core.Memo) (*core.Memo, error) { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Create(&connection).Error + return connection, err +} + +func Delete(connection *core.Memo) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(connection).Error +} + +func Update(memo core.Memo) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + return db.Model(&core.Memo{Model: gorm.Model{ID: memo.ID}}).Updates(memo).Error +} diff --git a/pkg/api/store/group/service/ip/plan/v0/plan.go b/pkg/api/store/group/service/ip/plan/v0/plan.go deleted file mode 100644 index 1d1c2cf5..00000000 --- a/pkg/api/store/group/service/ip/plan/v0/plan.go +++ /dev/null @@ -1,46 +0,0 @@ -package v0 - -import ( - "fmt" - "github.com/homenoc/dsbd-backend/pkg/api/core" - "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" - "log" - "time" -) - -func Create(plan *core.Plan) (*core.Plan, error) { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return plan, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - err = db.Create(&plan).Error - return plan, err -} - -func Delete(plan *core.Plan) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - return db.Delete(plan).Error -} - -func Update(u core.Plan) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - err = db.Model(&core.Plan{Model: gorm.Model{ID: u.ID}}).Update(u).Error - - return err -} diff --git a/pkg/api/store/group/service/ip/v0/ip.go b/pkg/api/store/group/service/ip/v0/ip.go index a5fae9cd..fe038210 100644 --- a/pkg/api/store/group/service/ip/v0/ip.go +++ b/pkg/api/store/group/service/ip/v0/ip.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/ip" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(network *core.IP) (*core.IP, error) { log.Println("database connection error") return network, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&network).Error return network, err @@ -28,7 +33,12 @@ func Delete(network *core.IP) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(network).Error } @@ -39,10 +49,15 @@ func Update(base int, u core.IP) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() if base == ip.UpdateAll { - err = db.Model(&core.IP{Model: gorm.Model{ID: u.ID}}).Update(u).Error + err = db.Model(&core.IP{Model: gorm.Model{ID: u.ID}}).Updates(u).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) @@ -56,7 +71,12 @@ func Get(base int, data *core.IP) ip.ResultDatabase { log.Println("database connection error") return ip.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ip.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ips []core.IP @@ -75,7 +95,12 @@ func GetAll() ip.ResultDatabase { log.Println("database connection error") return ip.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ip.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ips []core.IP err = db.Find(&ips).Error diff --git a/pkg/api/store/group/service/jpnicAdmin/v0/jpnicAdmin.go b/pkg/api/store/group/service/jpnicAdmin/v0/jpnicAdmin.go index b1fd3af2..3aa01131 100644 --- a/pkg/api/store/group/service/jpnicAdmin/v0/jpnicAdmin.go +++ b/pkg/api/store/group/service/jpnicAdmin/v0/jpnicAdmin.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicAdmin" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(network *core.JPNICAdmin) (*core.JPNICAdmin, error) { log.Println("database connection error") return network, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&network).Error return network, err @@ -28,7 +33,12 @@ func Delete(network *core.JPNICAdmin) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(network).Error } @@ -39,12 +49,17 @@ func Update(base int, u core.JPNICAdmin) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if base == jpnicAdmin.UpdateAll { - err = db.Model(&core.JPNICAdmin{Model: gorm.Model{ID: u.ID}}).Update(core.JPNICAdmin{ + err = db.Model(&core.JPNICAdmin{Model: gorm.Model{ID: u.ID}}).Updates(core.JPNICAdmin{ Org: u.Org, OrgEn: u.OrgEn, PostCode: u.PostCode, @@ -60,7 +75,7 @@ func Update(base int, u core.JPNICAdmin) error { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.JPNICAdmin) jpnicAdmin.ResultDatabase { @@ -69,7 +84,12 @@ func Get(base int, data *core.JPNICAdmin) jpnicAdmin.ResultDatabase { log.Println("database connection error") return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var jpnicAdminStruct []core.JPNICAdmin @@ -88,7 +108,12 @@ func GetAll() jpnicAdmin.ResultDatabase { log.Println("database connection error") return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var networks []core.JPNICAdmin err = db.Find(&networks).Error diff --git a/pkg/api/store/group/service/jpnicTech/v0/jpnicTech.go b/pkg/api/store/group/service/jpnicTech/v0/jpnicTech.go index f3780199..37a90ab8 100644 --- a/pkg/api/store/group/service/jpnicTech/v0/jpnicTech.go +++ b/pkg/api/store/group/service/jpnicTech/v0/jpnicTech.go @@ -5,44 +5,59 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicTech" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) -func Create(network *core.JPNICTech) (*core.JPNICTech, error) { +func Create(jpnic *core.JPNICTech) (*core.JPNICTech, error) { db, err := store.ConnectDB() if err != nil { log.Println("database connection error") - return network, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + return jpnic, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - err = db.Create(&network).Error - return network, err + err = db.Create(&jpnic).Error + return jpnic, err } -func Delete(network *core.JPNICTech) error { +func Delete(jpnic *core.JPNICTech) error { db, err := store.ConnectDB() if err != nil { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - return db.Delete(network).Error + return db.Delete(jpnic).Error } -func Update(base int, u core.JPNICTech) error { +func Update(base int, jpnic core.JPNICTech) error { db, err := store.ConnectDB() if err != nil { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() if base == jpnicTech.UpdateAll { - err = db.Model(&core.JPNICTech{Model: gorm.Model{ID: u.ID}}).Update(u).Error + err = db.Model(&core.JPNICTech{Model: gorm.Model{ID: jpnic.ID}}).Updates(jpnic).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) @@ -57,7 +72,12 @@ func Get(base int, data *core.JPNICTech) jpnicTech.ResultDatabase { log.Println("database connection error") return jpnicTech.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return jpnicTech.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var jpnicTechStruct []core.JPNICTech @@ -76,7 +96,12 @@ func GetAll() jpnicTech.ResultDatabase { log.Println("database connection error") return jpnicTech.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return jpnicTech.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var networks []core.JPNICTech err = db.Find(&networks).Error diff --git a/pkg/api/store/group/service/service_jpnicTech/v0/serviceJPNICTech.go b/pkg/api/store/group/service/service_jpnicTech/v0/serviceJPNICTech.go deleted file mode 100644 index a378f8ab..00000000 --- a/pkg/api/store/group/service/service_jpnicTech/v0/serviceJPNICTech.go +++ /dev/null @@ -1,98 +0,0 @@ -package v0 - -import ( - "fmt" - "github.com/homenoc/dsbd-backend/pkg/api/core" - "github.com/homenoc/dsbd-backend/pkg/api/core/group/service/jpnicAdmin" - "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" - "log" - "time" -) - -func Create(network *core.JPNICAdmin) (*core.JPNICAdmin, error) { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return network, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - err = db.Create(&network).Error - return network, err -} - -func Delete(network *core.JPNICAdmin) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - return db.Delete(network).Error -} - -func Update(base int, u core.JPNICAdmin) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - var result *gorm.DB - - if base == jpnicAdmin.UpdateAll { - err = db.Model(&core.JPNICAdmin{Model: gorm.Model{ID: u.ID}}).Update(core.JPNICAdmin{ - Org: u.Org, - OrgEn: u.OrgEn, - PostCode: u.PostCode, - Address: u.Address, - AddressEn: u.AddressEn, - Dept: u.Dept, - DeptEn: u.DeptEn, - Pos: u.Pos, - PosEn: u.PosEn, - Tel: u.Tel, - Fax: u.Fax, - Country: u.Country, - }).Error - } else { - log.Println("base select error") - return fmt.Errorf("(%s)error: base select\n", time.Now()) - } - return result.Error -} - -func Get(base int, data *core.JPNICAdmin) jpnicAdmin.ResultDatabase { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} - } - defer db.Close() - - var networkStruct []core.JPNICAdmin - - if base == jpnicAdmin.ID { //ID - err = db.First(&networkStruct, data.ID).Error - } else { - log.Println("base select error") - return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: base select\n", time.Now())} - } - return jpnicAdmin.ResultDatabase{Admins: networkStruct, Err: err} -} - -func GetAll() jpnicAdmin.ResultDatabase { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return jpnicAdmin.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} - } - defer db.Close() - - var networks []core.JPNICAdmin - err = db.Find(&networks).Error - return jpnicAdmin.ResultDatabase{Admins: networks, Err: err} -} diff --git a/pkg/api/store/group/service/v0/ip.go b/pkg/api/store/group/service/v0/ip.go new file mode 100644 index 00000000..d53ce41e --- /dev/null +++ b/pkg/api/store/group/service/v0/ip.go @@ -0,0 +1,58 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func JoinIP(input core.IP) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Create(&input).Error +} + +func DeleteIP(id uint) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(core.IP{Model: gorm.Model{ID: id}}).Error +} + +func UpdateIP(input core.IP) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Model(&core.IP{Model: gorm.Model{ID: input.ID}}).Updates(input).Error +} diff --git a/pkg/api/store/group/service/v0/jpnic_admin.go b/pkg/api/store/group/service/v0/jpnic_admin.go new file mode 100644 index 00000000..95803655 --- /dev/null +++ b/pkg/api/store/group/service/v0/jpnic_admin.go @@ -0,0 +1,60 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func JoinJPNICByAdmin(serviceID uint, input core.JPNICAdmin) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). + Association("JPNICAdmin"). + Append(input) +} + +func DeleteJPNICByAdmin(id uint) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(core.JPNICAdmin{Model: gorm.Model{ID: id}}).Error +} + +func UpdateJPNICByAdmin(input core.JPNICAdmin) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Model(&core.JPNICAdmin{Model: gorm.Model{ID: input.ID}}).Updates(input).Error +} diff --git a/pkg/api/store/group/service/v0/jpnic_tech.go b/pkg/api/store/group/service/v0/jpnic_tech.go new file mode 100644 index 00000000..be8f5d8e --- /dev/null +++ b/pkg/api/store/group/service/v0/jpnic_tech.go @@ -0,0 +1,58 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func JoinJPNICTech(input core.JPNICTech) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Create(&input).Error +} + +func DeleteJPNICTech(id uint) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(core.JPNICTech{Model: gorm.Model{ID: id}}).Error +} + +func UpdateJPNICTech(input core.JPNICTech) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Model(&core.JPNICTech{Model: gorm.Model{ID: input.ID}}).Updates(input).Error +} diff --git a/pkg/api/store/group/service/v0/plan.go b/pkg/api/store/group/service/v0/plan.go new file mode 100644 index 00000000..b9a7d96b --- /dev/null +++ b/pkg/api/store/group/service/v0/plan.go @@ -0,0 +1,80 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func JoinPlan(ipID uint, input core.Plan) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Model(&core.IP{Model: gorm.Model{ID: ipID}}). + Association("Plan"). + Append(&input) +} + +func DeletePlan(id uint) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(core.Plan{Model: gorm.Model{ID: id}}).Error +} + +func UpdatePlan(input core.Plan) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Model(&core.Plan{Model: gorm.Model{ID: input.ID}}).Updates(input).Error +} + +func GetPlan(data *core.Plan) (core.Plan, error) { + var plans core.Plan + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return plans, err + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return plans, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.First(&plans, data.ID).Error + + return plans, err +} diff --git a/pkg/api/store/group/service/v0/service.go b/pkg/api/store/group/service/v0/service.go index 973bdaf9..eeca2aba 100644 --- a/pkg/api/store/group/service/v0/service.go +++ b/pkg/api/store/group/service/v0/service.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/group/service" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(service *core.Service) (*core.Service, error) { log.Println("database connection error") return service, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&service).Error return service, err @@ -28,7 +33,12 @@ func Delete(service *core.Service) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(service).Error } @@ -39,183 +49,67 @@ func Update(base int, c core.Service) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result error + err = nil if service.UpdateData == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Update(core.Service{ + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Updates(core.Service{ Org: c.Org, OrgEn: c.OrgEn, PostCode: c.PostCode, Address: c.Address, AddressEn: c.AddressEn, - RouteV4: c.RouteV4, - RouteV6: c.RouteV6, ASN: c.ASN, }).Error - } else if service.UpdateRoute == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Update(core.Service{ - RouteV4: c.RouteV4, RouteV6: c.RouteV6}).Error } else if service.UpdateGID == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Update(core.Service{GroupID: c.GroupID}).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Updates(core.Service{GroupID: c.GroupID}).Error } else if service.UpdateStatus == base { } else if service.UpdateAll == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Update(c).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Updates(c).Error } else if service.ReplaceIP == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IP").Replace(c.IP[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IP").Replace(c.IP[0]) } else if service.AppendIP == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IP").Replace(c.IP[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IP").Replace(c.IP[0]) } else if service.AppendJPNICAdmin == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICAdmin").Append(c.JPNICAdmin).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICAdmin").Append(c.JPNICAdmin) } else if service.AppendJPNICTech == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICTech").Append(c.JPNICTech[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICTech").Append(c.JPNICTech[0]) } else if service.AppendConnection == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IPv4").Replace(c.Connection[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IPv4").Replace(c.Connection[0]) } else if service.DeleteIP == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IP").Replace(c.IP[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IP").Replace(c.IP[0]) } else if service.DeleteJPNICAdmin == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICAdmin").Delete(c.JPNICAdmin).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICAdmin").Delete(c.JPNICAdmin) } else if service.DeleteJPNICTech == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICTech").Delete(c.JPNICTech[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("JPNICTech").Delete(c.JPNICTech[0]) } else if service.DeleteConnection == base { - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IPv4").Delete(c.Connection[0]).Error + err = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Association("IPv4").Delete(c.Connection[0]) } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - result = db.Model(&core.Service{Model: gorm.Model{ID: c.ID}}).Update(core.Service{AddAllow: c.AddAllow}).Error - return result -} - -func JoinJPNICAdmin(serviceID uint, input core.JPNICAdmin) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("JPNICAdmin"). - Append(input) - - return nil -} - -func UpdateJPNICAdmin(serviceID uint, input core.JPNICAdmin) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("JPNICAdmin"). - Replace(&core.JPNICAdmin{Model: gorm.Model{ID: input.ID}}, &input) - - return nil + return err } -func DeleteJPNICAdmin(serviceID, jpnicAdminID uint) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("JPNICAdmin"). - Delete(&core.JPNICAdmin{Model: gorm.Model{ID: jpnicAdminID}}) - - return nil -} - -func JoinJPNICTech(serviceID uint, input core.JPNICTech) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("JPNICTech"). - Append(&input) - - return nil -} - -func UpdateJPNICTech(serviceID uint, before, after core.JPNICTech) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - after.Model = before.Model - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("JPNICTech"). - Replace(&before, &after) - - return nil -} - -func DeleteJPNICTech(serviceID, jpnicTechID uint) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("JPNICTech"). - Delete(&core.JPNICTech{Model: gorm.Model{ID: jpnicTechID}}) - - return nil -} - -func JoinIP(serviceID uint, input core.IP) error { - db, err := store.ConnectDB() - if err != nil { - log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) - } - defer db.Close() - - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("IP"). - Append(&input) - - return nil -} - -func DeleteIP(serviceID, jpnicTechID uint) error { +func Get(base int, data *core.Service) service.ResultDatabase { db, err := store.ConnectDB() if err != nil { log.Println("database connection error") - return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() - - db.Model(&core.Service{Model: gorm.Model{ID: serviceID}}). - Association("IP"). - Delete(&core.IP{Model: gorm.Model{ID: jpnicTechID}}) - - return nil -} - -func Get(base int, data *core.Service) service.ResultDatabase { - db, err := store.ConnectDB() + dbSQL, err := db.DB() if err != nil { - log.Println("database connection error") + log.Printf("database error: %v", err) return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + defer dbSQL.Close() var serviceStruct []core.Service @@ -277,7 +171,12 @@ func GetAll() service.ResultDatabase { log.Println("database connection error") return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var services []core.Service err = db.Preload("IP"). diff --git a/pkg/api/store/group/service/v0/update_test.go b/pkg/api/store/group/service/v0/update_test.go deleted file mode 100644 index 967059df..00000000 --- a/pkg/api/store/group/service/v0/update_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package v0 - -import ( - "github.com/homenoc/dsbd-backend/pkg/api/core" - "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" - "testing" -) - -func TestJoinJPNICTech(t *testing.T) { - err := config.GetConfig("/home/yonedayuto/go/src/github.com/homenoc/dsbd-backend/cmd/backend/con.json") - if err != nil { - t.Error(err) - } - - //if err = JoinJPNICTech(1, ); err != nil { - // t.Fatal(err) - //} -} - -func TestDeleteJPNICTech(t *testing.T) { - err := config.GetConfig("/home/yonedayuto/go/src/github.com/homenoc/dsbd-backend/cmd/backend/con.json") - if err != nil { - t.Error(err) - } - - if err = DeleteJPNICTech(1, 1); err != nil { - t.Fatal(err) - } -} - -func TestAddJPNICTech(t *testing.T) { - err := config.GetConfig("/home/yonedayuto/go/src/github.com/homenoc/dsbd-backend/cmd/backend/con.json") - if err != nil { - t.Error(err) - } - - data := core.Service{ - GroupID: 0, - ServiceTemplateID: nil, - ServiceTemplate: nil, - ServiceComment: "", - ServiceNumber: 0, - Org: "HomeNOC", - OrgEn: "", - PostCode: "", - Address: "", - AddressEn: "", - //ASN: 0, - RouteV4: "", - RouteV6: "", - V4Name: "", - V6Name: "", - AveUpstream: 0, - MaxUpstream: 0, - AveDownstream: 0, - MaxDownstream: 0, - MaxBandWidthAS: 0, - IP: nil, - //IPv4: nil, - JPNICAdminID: 0, - JPNICAdmin: core.JPNICAdmin{ - Org: "HomeNOC", - OrgEn: "HomeNOC", - }, - JPNICTech: []core.JPNICTech{ - { - Org: "HomeNOC", - OrgEn: "HomeNOC", - }, - }, - Open: nil, - Lock: nil, - } - - result, err := Create(&data) - if err != nil { - t.Fatal(err) - } - t.Log(result) -} diff --git a/pkg/api/store/group/v0/group.go b/pkg/api/store/group/v0/group.go index 791cbe4f..bf9de7b8 100644 --- a/pkg/api/store/group/v0/group.go +++ b/pkg/api/store/group/v0/group.go @@ -3,9 +3,9 @@ package v0 import ( "fmt" "github.com/homenoc/dsbd-backend/pkg/api/core" - group "github.com/homenoc/dsbd-backend/pkg/api/core/group" + "github.com/homenoc/dsbd-backend/pkg/api/core/group" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -25,7 +25,12 @@ func Create(g *core.Group) (*core.Group, error) { log.Println("database connection error") return g, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&g).Error return g, err @@ -37,7 +42,12 @@ func Delete(group *core.Group) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(group).Error } @@ -48,21 +58,31 @@ func Update(base int, g core.Group) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if group.UpdateOrg == base { - result = db.Model(&core.Group{Model: gorm.Model{ID: g.ID}}).Update("org", g.Org) - } else if group.UpdateStatus == base { - result = db.Model(&core.Group{Model: gorm.Model{ID: g.ID}}).Update("status", g.Status) + err = db.Model(&core.Group{Model: gorm.Model{ID: g.ID}}).Updates(core.Group{Org: g.Org}).Error + } else if group.UpdateMembership == base { + err = db.Model(&core.Group{Model: gorm.Model{ID: g.ID}}).Updates(core.Group{ + StripeCustomerID: g.StripeCustomerID, + StripeSubscriptionID: g.StripeSubscriptionID, + PaymentMembershipTemplateID: g.PaymentMembershipTemplateID, + MemberExpired: g.MemberExpired, + }).Error } else if group.UpdateAll == base { - result = db.Model(&core.Group{Model: gorm.Model{ID: g.ID}}).Update(g) + err = db.Model(&core.Group{Model: gorm.Model{ID: g.ID}}).Updates(g).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.Group) group.ResultDatabase { @@ -71,15 +91,24 @@ func Get(base int, data *core.Group) group.ResultDatabase { log.Println("database connection error") return group.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return group.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var groupStruct []core.Group if base == group.ID { //ID - err = db.Preload("Users"). + err = db.Preload("PaymentMembershipTemplate"). + Preload("Users"). Preload("Services"). Preload("Tickets"). + Preload("Memos"). + Preload("PaymentCouponTemplate"). Preload("Services.IP"). + Preload("Services.IP.Plan"). Preload("Services.Connection"). Preload("Services.Connection.ConnectionTemplate"). Preload("Services.Connection.NOC"). @@ -105,10 +134,16 @@ func GetAll() group.ResultDatabase { log.Println("database connection error") return group.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return group.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var groups []core.Group err = db.Preload("Users"). + Preload("Memos"). Find(&groups).Error return group.ResultDatabase{Group: groups, Err: err} } diff --git a/pkg/api/store/noc/bgpRouter/v0/bgpRouter.go b/pkg/api/store/noc/bgpRouter/v0/bgpRouter.go index 2c1bbf01..7d9660de 100644 --- a/pkg/api/store/noc/bgpRouter/v0/bgpRouter.go +++ b/pkg/api/store/noc/bgpRouter/v0/bgpRouter.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" router "github.com/homenoc/dsbd-backend/pkg/api/core/noc/bgpRouter" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(router *core.BGPRouter) (*core.BGPRouter, error) { log.Println("database connection error") return router, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&router).Error return router, err @@ -28,7 +33,12 @@ func Delete(router *core.BGPRouter) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(router).Error } @@ -39,21 +49,26 @@ func Update(base int, data core.BGPRouter) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if router.UpdateAll == base { - result = db.Model(&core.BGPRouter{Model: gorm.Model{ID: data.ID}}).Update(core.BGPRouter{ + err = db.Model(&core.BGPRouter{Model: gorm.Model{ID: data.ID}}).Updates(core.BGPRouter{ HostName: data.HostName, Address: data.Address, Enable: data.Enable, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.BGPRouter) router.ResultDatabase { @@ -62,7 +77,12 @@ func Get(base int, data *core.BGPRouter) router.ResultDatabase { log.Println("database connection error") return router.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return router.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var routerStruct []core.BGPRouter @@ -85,7 +105,12 @@ func GetAll() router.ResultDatabase { log.Println("database connection error") return router.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return router.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var routers []core.BGPRouter err = db.Find(&routers).Error diff --git a/pkg/api/store/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go b/pkg/api/store/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go index 90eb458c..2b143e82 100644 --- a/pkg/api/store/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go +++ b/pkg/api/store/noc/tunnelEndPointRouter/v0/tunnelEndPointRouter.go @@ -6,7 +6,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core/noc/tunnelEndPointRouter" router "github.com/homenoc/dsbd-backend/pkg/api/core/noc/tunnelEndPointRouterIP" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -17,7 +17,12 @@ func Create(router *core.TunnelEndPointRouter) (*core.TunnelEndPointRouter, erro log.Println("database connection error") return router, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&router).Error return router, err @@ -29,7 +34,12 @@ func Delete(router *core.TunnelEndPointRouter) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(router).Error } @@ -40,23 +50,28 @@ func Update(base int, data core.TunnelEndPointRouter) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if router.UpdateAll == base { - result = db.Model(&core.TunnelEndPointRouter{Model: gorm.Model{ID: data.ID}}).Update(core.TunnelEndPointRouter{ + err = db.Model(&core.TunnelEndPointRouter{Model: gorm.Model{ID: data.ID}}).Updates(core.TunnelEndPointRouter{ NOCID: data.NOCID, HostName: data.HostName, Capacity: data.Capacity, Comment: data.Comment, Enable: data.Enable, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.TunnelEndPointRouter) tunnelEndPointRouter.ResultDatabase { @@ -65,7 +80,12 @@ func Get(base int, data *core.TunnelEndPointRouter) tunnelEndPointRouter.ResultD log.Println("database connection error") return tunnelEndPointRouter.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return tunnelEndPointRouter.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var routerStruct []core.TunnelEndPointRouter @@ -86,7 +106,12 @@ func GetAll() tunnelEndPointRouter.ResultDatabase { log.Println("database connection error") return tunnelEndPointRouter.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return tunnelEndPointRouter.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var routers []core.TunnelEndPointRouter err = db.Find(&routers).Error diff --git a/pkg/api/store/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go b/pkg/api/store/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go index 401afc31..cd63b4bd 100644 --- a/pkg/api/store/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go +++ b/pkg/api/store/noc/tunnelEndPointRouterIP/v0/tunnelEndPointRouterIP.go @@ -5,7 +5,7 @@ import ( core "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/noc/tunnelEndPointRouterIP" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(router *core.TunnelEndPointRouterIP) (*core.TunnelEndPointRouterIP, log.Println("database connection error") return router, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&router).Error return router, err @@ -28,7 +33,12 @@ func Delete(router *core.TunnelEndPointRouterIP) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(router).Error } @@ -39,21 +49,26 @@ func Update(base int, data core.TunnelEndPointRouterIP) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if tunnelEndPointRouterIP.UpdateAll == base { - result = db.Model(&core.TunnelEndPointRouterIP{Model: gorm.Model{ID: data.ID}}).Update(core.TunnelEndPointRouterIP{ + err = db.Model(&core.TunnelEndPointRouterIP{Model: gorm.Model{ID: data.ID}}).Updates(core.TunnelEndPointRouterIP{ IP: data.IP, Comment: data.Comment, Enable: data.Enable, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.TunnelEndPointRouterIP) tunnelEndPointRouterIP.ResultDatabase { @@ -62,7 +77,12 @@ func Get(base int, data *core.TunnelEndPointRouterIP) tunnelEndPointRouterIP.Res log.Println("database connection error") return tunnelEndPointRouterIP.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return tunnelEndPointRouterIP.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var routerStruct []core.TunnelEndPointRouterIP @@ -84,9 +104,14 @@ func GetAll() tunnelEndPointRouterIP.ResultDatabase { log.Println("database connection error") return tunnelEndPointRouterIP.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return tunnelEndPointRouterIP.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var routers []core.TunnelEndPointRouterIP - err = db.Find(&routers).Error + err = db.Preload("TunnelEndPointRouter").Find(&routers).Error return tunnelEndPointRouterIP.ResultDatabase{TunnelEndPointRouterIP: routers, Err: err} } diff --git a/pkg/api/store/noc/v0/noc.go b/pkg/api/store/noc/v0/noc.go index 611c13a9..a56a4634 100644 --- a/pkg/api/store/noc/v0/noc.go +++ b/pkg/api/store/noc/v0/noc.go @@ -5,7 +5,7 @@ import ( core "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/noc" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(noc *core.NOC) (*core.NOC, error) { log.Println("database connection error") return noc, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&noc).Error return noc, err @@ -28,7 +33,12 @@ func Delete(noc *core.NOC) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(noc).Error } @@ -39,23 +49,28 @@ func Update(base int, data core.NOC) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if noc.UpdateAll == base { - result = db.Model(&core.NOC{Model: gorm.Model{ID: data.ID}}).Update(core.NOC{ + err = db.Model(&core.NOC{Model: gorm.Model{ID: data.ID}}).Updates(core.NOC{ Name: data.Name, Location: data.Location, Bandwidth: data.Bandwidth, Enable: data.Enable, Comment: data.Comment, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.NOC) noc.ResultDatabase { @@ -64,7 +79,12 @@ func Get(base int, data *core.NOC) noc.ResultDatabase { log.Println("database connection error") return noc.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return noc.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var nocStruct []core.NOC @@ -87,7 +107,12 @@ func GetAll() noc.ResultDatabase { log.Println("database connection error") return noc.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return noc.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var nocs []core.NOC err = db.Preload("BGPRouter"). diff --git a/pkg/api/store/noc/v0/update_test.go b/pkg/api/store/noc/v0/update_test.go index fda67a0d..61c05583 100644 --- a/pkg/api/store/noc/v0/update_test.go +++ b/pkg/api/store/noc/v0/update_test.go @@ -4,7 +4,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/noc" "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "testing" ) diff --git a/pkg/api/store/notice/v0/notice.go b/pkg/api/store/notice/v0/notice.go index 0197dba3..ab5db3b8 100644 --- a/pkg/api/store/notice/v0/notice.go +++ b/pkg/api/store/notice/v0/notice.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/notice" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -20,7 +20,12 @@ func Create(notice *core.Notice) (*core.Notice, error) { log.Println("database connection error") return notice, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(¬ice).Error return notice, err @@ -32,7 +37,12 @@ func Delete(notice *core.Notice) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(notice).Error } @@ -43,15 +53,17 @@ func Update(base int, data core.Notice) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if notice.UpdateAll == base { - result = db.Model(&core.Notice{Model: gorm.Model{ID: data.ID}}).Update(core.Notice{ - UserID: data.UserID, - GroupID: data.GroupID, - NOCID: data.NOCID, + err = db.Model(&core.Notice{Model: gorm.Model{ID: data.ID}}).Updates(core.Notice{ StartTime: data.StartTime, EndTime: data.EndTime, Important: data.Important, @@ -60,12 +72,12 @@ func Update(base int, data core.Notice) error { Info: data.Info, Title: data.Title, Data: data.Data, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.Notice) notice.ResultDatabase { @@ -74,7 +86,12 @@ func Get(base int, data *core.Notice) notice.ResultDatabase { log.Println("database connection error") return notice.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return notice.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var noticeStruct []core.Notice @@ -84,19 +101,22 @@ func Get(base int, data *core.Notice) notice.ResultDatabase { if base == notice.ID { //ID err = db.First(¬iceStruct, data.ID).Error } else if base == notice.UIDOrAll { //UserID Or All - err = db.Where("user_id = ? AND start_time < ? AND ? < end_time", data.UserID, dateTime, dateTime). + err = db.Where("start_time < ? AND ? < end_time", dateTime, dateTime). + Joins("left outer join notice_user on notices.id = notice_user.notice_id"). + Where("notice_user.user_id = ?", data.User[0].ID). Or("everyone = ? AND start_time < ? AND ? < end_time", true, dateTime, dateTime). Order("id asc").Find(¬iceStruct).Error } else if base == notice.UIDOrGIDOrAll { //UserID Or GroupID Or All - err = db.Where("user_id = ? AND start_time < ? AND ? < end_time", data.UserID, dateTime, dateTime). - Or("group_id = ? AND start_time < ? AND ? < end_time", data.GroupID, dateTime, dateTime). + err = db.Where("start_time < ? AND ? < end_time", dateTime, dateTime). + Joins("left outer join user on notice.id = notice_user.notice_id"). + Where("user_id = ?", data.User[0].Model.ID). Or("everyone = ? AND start_time < ? AND ? < end_time", true, dateTime, dateTime). Order("id asc").Find(¬iceStruct).Error } else if base == notice.UIDOrGIDOrNOCAllOrAll { //UserID Or GroupID Or NOCAll Or All - err = db.Where("user_id = ? AND start_time < ? AND ? < end_time", data.UserID, dateTime, dateTime). - Or("group_id = ? AND start_time < ? AND ? < end_time", data.GroupID, dateTime, dateTime). - Or("everyone = ? AND start_time < ? AND ? < end_time", true, dateTime, dateTime). - Or("noc_id != ? AND start_time < ? AND ? < end_time", 0, dateTime, dateTime). + err = db.Where("start_time < ? AND ? < end_time", dateTime, dateTime). + Joins("left outer join user on notice.id = notice_user.notice_id"). + Where("user_id = ?", data.User[0].Model.ID). + Or("start_time < ? AND ? < end_time AND everyone = ?", dateTime, dateTime, true). Order("id asc").Find(¬iceStruct).Error } else if base == notice.NOCAll { //UserID Or GroupID Or NOCAll Or All err = db.Where("user_id = ? AND user_id = ? AND noc_id != ? AND start_time < ? AND ? < end_time ", @@ -115,39 +135,18 @@ func Get(base int, data *core.Notice) notice.ResultDatabase { return notice.ResultDatabase{Notice: noticeStruct, Err: err} } -func GetArray(base int, data *core.Notice, array []string) notice.ResultDatabase { +func GetAll() notice.ResultDatabase { db, err := store.ConnectDB() if err != nil { log.Println("database connection error") return notice.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() - - var noticeStruct []core.Notice - - dateTime := time.Now() - - if base == notice.UIDOrGIDOrNOCAllOrAll { //UserID Or GroupID Or NOCAll Or All - err = db.Where("user_id = ? AND start_time < ? AND ? < end_time ", data.UserID, dateTime, dateTime). - Or("group_id = ? AND start_time < ? AND ? < end_time", data.GroupID, dateTime, dateTime). - Or("everyone = ? AND start_time < ? AND ? < end_time", true, dateTime, dateTime). - Or("noc_id IN (?) AND start_time < ? AND ? < end_time", array, dateTime, dateTime). - Order("id desc"). - Find(¬iceStruct).Error - } else { - log.Println("base select error") - return notice.ResultDatabase{Err: fmt.Errorf("(%s)error: base select\n", time.Now())} - } - return notice.ResultDatabase{Notice: noticeStruct, Err: err} -} - -func GetAll() notice.ResultDatabase { - db, err := store.ConnectDB() + dbSQL, err := db.DB() if err != nil { - log.Println("database connection error") + log.Printf("database error: %v", err) return notice.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + defer dbSQL.Close() var notices []core.Notice err = db.Find(¬ices).Error diff --git a/pkg/api/store/payment/v0/payment.go b/pkg/api/store/payment/v0/payment.go new file mode 100644 index 00000000..18bd5ed4 --- /dev/null +++ b/pkg/api/store/payment/v0/payment.go @@ -0,0 +1,117 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/core/payment" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(input *core.Payment) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Create(&input).Error +} + +func Delete(input *core.Payment) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(&input).Error +} + +func Update(base int, input *core.Payment) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + if payment.UpdatePaid == base { + err = db.Model(&core.Payment{PaymentIntentID: input.PaymentIntentID}).Updates(core.Payment{Paid: input.Paid}).Error + } else if payment.UpdateAll == base { + err = db.Model(&core.Payment{Model: gorm.Model{ID: input.ID}}).Updates(&input).Error + } else { + log.Println("base select error") + return fmt.Errorf("(%s)error: base select\n", time.Now()) + } + + return err +} + +func Get(base uint, input core.Payment) ([]core.Payment, error) { + var payments []core.Payment + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + if base == payment.ID { //ID + err = db.First(&payments, input.ID).Error + } else if base == payment.PaymentIntentID { //PaymentIntentID + err = db.Where("payment_intent_id = ?", input.PaymentIntentID).Find(&payments).Error + } else { + log.Println("base select error") + return payments, fmt.Errorf("(%s)error: base select\n", time.Now()) + } + + return payments, err +} + +func GetAll() ([]core.Payment, error) { + var payments []core.Payment + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return payments, err + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Preload("User").Preload("Group").Find(&payments).Error + return payments, err +} diff --git a/pkg/api/store/store.go b/pkg/api/store/store.go index ba7a9be2..d0baf15f 100644 --- a/pkg/api/store/store.go +++ b/pkg/api/store/store.go @@ -3,8 +3,8 @@ package store import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/tool/config" - "github.com/jinzhu/gorm" - _ "github.com/jinzhu/gorm/dialects/mysql" + "gorm.io/driver/mysql" + "gorm.io/gorm" "log" "strconv" ) @@ -15,7 +15,10 @@ func ConnectDB() (*gorm.DB, error) { protocol := "tcp(" + config.Conf.DB.IP + ":" + strconv.Itoa(config.Conf.DB.Port) + ")" dbName := config.Conf.DB.DBName - db, err := gorm.Open("mysql", user+":"+pass+"@"+protocol+"/"+dbName+"?parseTime=true") + dsn := user + ":" + pass + "@" + protocol + "/" + dbName + "?charset=utf8&parseTime=True&loc=Local" + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ + PrepareStmt: true, + }) if err != nil { return nil, err } @@ -27,6 +30,7 @@ func InitDB() { result := db.AutoMigrate( &core.User{}, &core.Group{}, + &core.Memo{}, &core.Service{}, &core.Connection{}, &core.NOC{}, @@ -46,6 +50,12 @@ func InitDB() { &core.Notice{}, &core.IPv4Template{}, &core.IPv6Template{}, + &core.IPv4RouteTemplate{}, + &core.IPv6RouteTemplate{}, + &core.Payment{}, + &core.PaymentCouponTemplate{}, + &core.PaymentMembershipTemplate{}, + &core.PaymentDonateTemplate{}, ) - log.Println(result.Error) + log.Println(result) } diff --git a/pkg/api/store/support/chat/v0/chat.go b/pkg/api/store/support/chat/v0/chat.go index c28296d7..f9508333 100644 --- a/pkg/api/store/support/chat/v0/chat.go +++ b/pkg/api/store/support/chat/v0/chat.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/support/chat" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(support *core.Chat) (*core.Chat, error) { log.Println("database connection error") return support, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&support).Error return support, err @@ -28,7 +33,12 @@ func Delete(support *core.Chat) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(support).Error } @@ -39,24 +49,29 @@ func Update(base int, s core.Chat) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if chat.UpdateUserID == base { - result = db.Model(&core.Chat{Model: gorm.Model{ID: s.ID}}).Update(core.Chat{UserID: s.UserID}) + err = db.Model(&core.Chat{Model: gorm.Model{ID: s.ID}}).Updates(core.Chat{UserID: s.UserID}).Error } else if chat.UpdateAll == base { - result = db.Model(&core.Chat{Model: gorm.Model{ID: s.ID}}).Update(core.Chat{ + err = db.Model(&core.Chat{Model: gorm.Model{ID: s.ID}}).Updates(core.Chat{ TicketID: s.TicketID, UserID: s.UserID, Admin: s.Admin, Data: s.Data, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.Chat) chat.ResultDatabase { @@ -65,7 +80,12 @@ func Get(base int, data *core.Chat) chat.ResultDatabase { log.Println("database connection error") return chat.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return chat.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var chatStruct []core.Chat @@ -86,7 +106,12 @@ func GetAll() chat.ResultDatabase { log.Println("database connection error") return chat.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return chat.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var chats []core.Chat err = db.Find(&chats).Error diff --git a/pkg/api/store/support/ticket/v0/ticket.go b/pkg/api/store/support/ticket/v0/ticket.go index 8034fb67..7a4c3831 100644 --- a/pkg/api/store/support/ticket/v0/ticket.go +++ b/pkg/api/store/support/ticket/v0/ticket.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/support/ticket" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(support *core.Ticket) (*core.Ticket, error) { log.Println("database connection error") return support, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&support).Error return support, err @@ -28,7 +33,12 @@ func Delete(support *core.Ticket) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(support).Error } @@ -39,22 +49,29 @@ func Update(base int, t core.Ticket) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil //#4 Issue(解決済み) if ticket.UpdateAll == base { - result = db.Model(&core.Ticket{Model: gorm.Model{ID: t.ID}}).Update(&core.Ticket{Title: t.Title, - GroupID: t.GroupID, - UserID: t.UserID, - Solved: t.Solved, - }) + err = db.Model(&core.Ticket{Model: gorm.Model{ID: t.ID}}).Updates(&core.Ticket{Title: t.Title, + GroupID: t.GroupID, + UserID: t.UserID, + Solved: t.Solved, + Request: t.Request, + RequestReject: t.RequestReject, + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.Ticket) ticket.ResultDatabase { @@ -63,7 +80,12 @@ func Get(base int, data *core.Ticket) ticket.ResultDatabase { log.Println("database connection error") return ticket.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ticket.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ticketStruct []core.Ticket @@ -95,7 +117,12 @@ func GetAll() ticket.ResultDatabase { log.Println("database connection error") return ticket.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ticket.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var tickets []core.Ticket err = db.Preload("User"). diff --git a/pkg/api/store/template/connection/v0/connection.go b/pkg/api/store/template/connection/v0/connection.go index 067cba08..5b59c29a 100644 --- a/pkg/api/store/template/connection/v0/connection.go +++ b/pkg/api/store/template/connection/v0/connection.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/template/connection" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(connection *core.ConnectionTemplate) (*core.ConnectionTemplate, erro log.Println("database connection error") return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&connection).Error return connection, err @@ -28,7 +33,12 @@ func Delete(connection *core.ConnectionTemplate) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(connection).Error } @@ -39,22 +49,27 @@ func Update(base int, c core.ConnectionTemplate) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if base == connection.UpdateAll { - result = db.Model(&core.ConnectionTemplate{Model: gorm.Model{ID: c.ID}}).Update(core.ConnectionTemplate{ + err = db.Model(&core.ConnectionTemplate{Model: gorm.Model{ID: c.ID}}).Updates(core.ConnectionTemplate{ Hidden: c.Hidden, Name: c.Name, Comment: c.Comment, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.ConnectionTemplate) connection.ResultDatabase { @@ -63,7 +78,12 @@ func Get(base int, data *core.ConnectionTemplate) connection.ResultDatabase { log.Println("database connection error") return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var connectionStruct []core.ConnectionTemplate @@ -82,7 +102,12 @@ func GetAll() connection.ResultDatabase { log.Println("database connection error") return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return connection.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var connections []core.ConnectionTemplate err = db.Find(&connections).Error diff --git a/pkg/api/store/template/ipv4/v0/ipv4.go b/pkg/api/store/template/ipv4/v0/ipv4.go index 7ef6cd90..1da41502 100644 --- a/pkg/api/store/template/ipv4/v0/ipv4.go +++ b/pkg/api/store/template/ipv4/v0/ipv4.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" ipv4 "github.com/homenoc/dsbd-backend/pkg/api/core/template/ipv4" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(ipv4 *core.IPv4Template) (*core.IPv4Template, error) { log.Println("database ipv4 error") return ipv4, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&ipv4).Error return ipv4, err @@ -28,7 +33,12 @@ func Delete(ipv4 *core.IPv4Template) error { log.Println("database ipv4 error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(ipv4).Error } @@ -39,18 +49,23 @@ func Update(base int, c core.IPv4Template) error { log.Println("database ipv4 error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if base == ipv4.UpdateAll { - result = db.Model(&core.IPv4Template{Model: gorm.Model{ID: c.ID}}).Update(c) + err = db.Model(&core.IPv4Template{Model: gorm.Model{ID: c.ID}}).Updates(c).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.IPv4Template) ipv4.ResultDatabase { @@ -59,7 +74,12 @@ func Get(base int, data *core.IPv4Template) ipv4.ResultDatabase { log.Println("database ipv4 error") return ipv4.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv4.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ipv4Struct []core.IPv4Template @@ -80,7 +100,12 @@ func GetAll() ipv4.ResultDatabase { log.Println("database ipv4 error") return ipv4.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv4.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ipv4s []core.IPv4Template err = db.Find(&ipv4s).Error diff --git a/pkg/api/store/template/ipv4_route/v0/ipv4_route.go b/pkg/api/store/template/ipv4_route/v0/ipv4_route.go new file mode 100644 index 00000000..84a7d7c6 --- /dev/null +++ b/pkg/api/store/template/ipv4_route/v0/ipv4_route.go @@ -0,0 +1,108 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + ipv4 "github.com/homenoc/dsbd-backend/pkg/api/core/template/ipv4" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(ipv4 *core.IPv4RouteTemplate) (*core.IPv4RouteTemplate, error) { + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv4 error") + return ipv4, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Create(&ipv4).Error + return ipv4, err +} + +func Delete(ipv4 *core.IPv4RouteTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv4 error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(ipv4).Error +} + +func Update(base int, c core.IPv4RouteTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv4 error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + if base == ipv4.UpdateAll { + err = db.Model(&core.IPv4RouteTemplate{Model: gorm.Model{ID: c.ID}}).Updates(c).Error + } else { + log.Println("base select error") + return fmt.Errorf("(%s)error: base select\n", time.Now()) + } + + return err +} + +func Get(id uint) ([]core.IPv4RouteTemplate, error) { + var ipv4s []core.IPv4RouteTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv4 error") + return []core.IPv4RouteTemplate{}, err + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv4s, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.First(&ipv4s, id).Error + return ipv4s, err +} + +func GetAll() ([]core.IPv4RouteTemplate, error) { + var ipv4s []core.IPv4RouteTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv4 error") + return []core.IPv4RouteTemplate{}, err + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv4s, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Find(&ipv4s).Error + return ipv4s, err + +} diff --git a/pkg/api/store/template/ipv6/v0/ipv6.go b/pkg/api/store/template/ipv6/v0/ipv6.go index 45231673..ca305c10 100644 --- a/pkg/api/store/template/ipv6/v0/ipv6.go +++ b/pkg/api/store/template/ipv6/v0/ipv6.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" ipv6 "github.com/homenoc/dsbd-backend/pkg/api/core/template/ipv6" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(ipv4 *core.IPv6Template) (*core.IPv6Template, error) { log.Println("database ipv6 error") return ipv4, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&ipv4).Error return ipv4, err @@ -28,7 +33,12 @@ func Delete(ipv4 *core.IPv6Template) error { log.Println("database ipv6 error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(ipv4).Error } @@ -39,18 +49,23 @@ func Update(base int, c core.IPv6Template) error { log.Println("database ipv6 error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if base == ipv6.UpdateAll { - result = db.Model(&core.IPv6Template{Model: gorm.Model{ID: c.ID}}).Update(c) + err = db.Model(&core.IPv6Template{Model: gorm.Model{ID: c.ID}}).Updates(c).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.IPv6Template) ipv6.ResultDatabase { @@ -59,7 +74,12 @@ func Get(base int, data *core.IPv6Template) ipv6.ResultDatabase { log.Println("database ipv6 error") return ipv6.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv6.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ipv6Struct []core.IPv6Template @@ -80,7 +100,12 @@ func GetAll() ipv6.ResultDatabase { log.Println("database ipv6 error") return ipv6.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv6.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ipv6s []core.IPv6Template err = db.Find(&ipv6s).Error diff --git a/pkg/api/store/template/ipv6_route/v0/ipv6_route.go b/pkg/api/store/template/ipv6_route/v0/ipv6_route.go new file mode 100644 index 00000000..1ac36000 --- /dev/null +++ b/pkg/api/store/template/ipv6_route/v0/ipv6_route.go @@ -0,0 +1,108 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + ipv6 "github.com/homenoc/dsbd-backend/pkg/api/core/template/ipv6" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(ipv6 *core.IPv6RouteTemplate) (*core.IPv6RouteTemplate, error) { + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv6 error") + return ipv6, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Create(&ipv6).Error + return ipv6, err +} + +func Delete(ipv4 *core.IPv6RouteTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv6 error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(ipv4).Error +} + +func Update(base int, c core.IPv6RouteTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv6 error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + if base == ipv6.UpdateAll { + err = db.Model(&core.IPv6RouteTemplate{Model: gorm.Model{ID: c.ID}}).Updates(c).Error + } else { + log.Println("base select error") + return fmt.Errorf("(%s)error: base select\n", time.Now()) + } + + return err +} + +func Get(id uint) ([]core.IPv6RouteTemplate, error) { + var ipv6s []core.IPv6RouteTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv4 error") + return []core.IPv6RouteTemplate{}, err + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv6s, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.First(&ipv6s, id).Error + return ipv6s, err +} + +func GetAll() ([]core.IPv6RouteTemplate, error) { + var ipv6s []core.IPv6RouteTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database ipv6 error") + return []core.IPv6RouteTemplate{}, err + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ipv6s, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Find(&ipv6s).Error + return ipv6s, err + +} diff --git a/pkg/api/store/template/ntt/v0/ntt.go b/pkg/api/store/template/ntt/v0/ntt.go index c6bfce10..dce8d947 100644 --- a/pkg/api/store/template/ntt/v0/ntt.go +++ b/pkg/api/store/template/ntt/v0/ntt.go @@ -5,7 +5,6 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" ntt "github.com/homenoc/dsbd-backend/pkg/api/core/template/ntt" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" "log" "time" ) @@ -16,7 +15,12 @@ func Create(ntt *core.NTTTemplate) (*core.NTTTemplate, error) { log.Println("database ntt error") return ntt, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&ntt).Error return ntt, err @@ -28,7 +32,12 @@ func Delete(ntt *core.NTTTemplate) error { log.Println("database ntt error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(ntt).Error } @@ -39,22 +48,16 @@ func Update(base int, c core.NTTTemplate) error { log.Println("database ntt error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() - - var result *gorm.DB + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - //if base == ntt.UpdateAll { - // result = db.Model(&core.NTTTemplate{Model: gorm.Model{ID: c.ID}}).Update(core.NTTTemplate{ - // Hidden: c.Hidden, - // Name: c.Name, - // Comment: c.Comment, - // }) - //} else { - // log.Println("base select error") - // return fmt.Errorf("(%s)error: base select\n", time.Now()) - //} + err = nil - return result.Error + return err } func Get(base int, data *core.NTTTemplate) ntt.ResultDatabase { @@ -63,7 +66,12 @@ func Get(base int, data *core.NTTTemplate) ntt.ResultDatabase { log.Println("database ntt error") return ntt.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ntt.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var nttStruct []core.NTTTemplate @@ -82,7 +90,12 @@ func GetAll() ntt.ResultDatabase { log.Println("database ntt error") return ntt.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return ntt.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var ntts []core.NTTTemplate err = db.Find(&ntts).Error diff --git a/pkg/api/store/template/payment_coupon/v0/payment_coupon.go b/pkg/api/store/template/payment_coupon/v0/payment_coupon.go new file mode 100644 index 00000000..86563cfb --- /dev/null +++ b/pkg/api/store/template/payment_coupon/v0/payment_coupon.go @@ -0,0 +1,107 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(coupon *core.PaymentCouponTemplate) (*core.PaymentCouponTemplate, error) { + db, err := store.ConnectDB() + if err != nil { + log.Println("database coupon error") + return coupon, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Create(&coupon).Error + return coupon, err +} + +func Delete(coupon *core.PaymentCouponTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database coupon error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(coupon).Error +} + +func Update(c core.PaymentCouponTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database coupon error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + err = db.Model(&core.PaymentCouponTemplate{Model: gorm.Model{ID: c.ID}}).Updates(core.PaymentCouponTemplate{ + Title: c.Title, + DiscountRate: c.DiscountRate, + Comment: c.Comment, + }).Error + + return err +} + +func Get(id uint) (core.PaymentCouponTemplate, error) { + var coupon core.PaymentCouponTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database coupon error") + return coupon, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return coupon, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.First(&coupon, id).Error + + return coupon, err +} + +func GetAll() ([]core.PaymentCouponTemplate, error) { + var coupons []core.PaymentCouponTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database coupon error") + return coupons, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return coupons, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Find(&coupons).Error + + return coupons, err +} diff --git a/pkg/api/store/template/payment_donate/v0/payment_donate.go b/pkg/api/store/template/payment_donate/v0/payment_donate.go new file mode 100644 index 00000000..bf57874a --- /dev/null +++ b/pkg/api/store/template/payment_donate/v0/payment_donate.go @@ -0,0 +1,107 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(connection *core.PaymentDonateTemplate) (*core.PaymentDonateTemplate, error) { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return nil, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Create(&connection).Error + return connection, err +} + +func Delete(connection *core.PaymentDonateTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(connection).Error +} + +func Update(c core.PaymentDonateTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + err = db.Model(&core.PaymentDonateTemplate{Model: gorm.Model{ID: c.ID}}).Updates(core.PaymentDonateTemplate{ + Name: c.Name, + Fee: c.Fee, + Comment: c.Comment, + }).Error + + return err +} + +func Get(id uint) (core.PaymentDonateTemplate, error) { + var payment core.PaymentDonateTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return payment, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return payment, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.First(&payment, id).Error + + return payment, err +} + +func GetAll() ([]core.PaymentDonateTemplate, error) { + var payments []core.PaymentDonateTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Find(&payments).Error + + return payments, err +} diff --git a/pkg/api/store/template/payment_membership/v0/payment_membership.go b/pkg/api/store/template/payment_membership/v0/payment_membership.go new file mode 100644 index 00000000..1f3585e2 --- /dev/null +++ b/pkg/api/store/template/payment_membership/v0/payment_membership.go @@ -0,0 +1,107 @@ +package v0 + +import ( + "fmt" + "github.com/homenoc/dsbd-backend/pkg/api/core" + "github.com/homenoc/dsbd-backend/pkg/api/store" + "gorm.io/gorm" + "log" + "time" +) + +func Create(connection *core.PaymentMembershipTemplate) (*core.PaymentMembershipTemplate, error) { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Create(&connection).Error + return connection, err +} + +func Delete(connection *core.PaymentMembershipTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + return db.Delete(connection).Error +} + +func Update(c core.PaymentMembershipTemplate) error { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = nil + + err = db.Model(&core.PaymentMembershipTemplate{Model: gorm.Model{ID: c.ID}}).Updates(core.PaymentMembershipTemplate{ + Title: c.Title, + Plan: c.Plan, + Comment: c.Comment, + }).Error + + return err +} + +func Get(id uint) (core.PaymentMembershipTemplate, error) { + var payment core.PaymentMembershipTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return payment, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return payment, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.First(&payment, id).Error + + return payment, err +} + +func GetAll() ([]core.PaymentMembershipTemplate, error) { + var payments []core.PaymentMembershipTemplate + + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return payments, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() + + err = db.Find(&payments).Error + + return payments, err +} diff --git a/pkg/api/store/template/service/v0/service.go b/pkg/api/store/template/service/v0/service.go index 0f26fd5e..dc3df7df 100644 --- a/pkg/api/store/template/service/v0/service.go +++ b/pkg/api/store/template/service/v0/service.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/template/service" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(connection *core.ServiceTemplate) (*core.ServiceTemplate, error) { log.Println("database connection error") return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return connection, fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() err = db.Create(&connection).Error return connection, err @@ -28,7 +33,12 @@ func Delete(connection *core.ServiceTemplate) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(connection).Error } @@ -39,21 +49,26 @@ func Update(base int, c core.ServiceTemplate) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if base == service.UpdateAll { - result = db.Model(&core.ServiceTemplate{Model: gorm.Model{ID: c.ID}}).Update(core.ServiceTemplate{ + err = db.Model(&core.ServiceTemplate{Model: gorm.Model{ID: c.ID}}).Updates(core.ServiceTemplate{ Hidden: c.Hidden, Name: c.Name, Comment: c.Comment, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } func Get(base int, data *core.ServiceTemplate) service.ResultDatabase { @@ -62,7 +77,12 @@ func Get(base int, data *core.ServiceTemplate) service.ResultDatabase { log.Println("database connection error") return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var connectionStruct []core.ServiceTemplate @@ -82,7 +102,12 @@ func GetAll() service.ResultDatabase { log.Println("database connection error") return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return service.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var connections []core.ServiceTemplate err = db.Find(&connections).Error diff --git a/pkg/api/store/token/v0/token.go b/pkg/api/store/token/v0/token.go index 6afca326..1678b90c 100644 --- a/pkg/api/store/token/v0/token.go +++ b/pkg/api/store/token/v0/token.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/token" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -16,7 +16,12 @@ func Create(t *core.Token) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Create(t).Error } @@ -27,7 +32,12 @@ func Delete(t *core.Token) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(t).Error } @@ -38,7 +48,12 @@ func DeleteAll() error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Exec("DELETE FROM tokens").Error } @@ -49,15 +64,20 @@ func Update(base int, t *core.Token) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() if token.AddToken == base { - err = db.Model(&core.Token{Model: gorm.Model{ID: t.ID}}).Update(core.Token{Model: gorm.Model{}, + err = db.Model(&core.Token{Model: gorm.Model{ID: t.ID}}).Updates(core.Token{ ExpiredAt: t.ExpiredAt, UserID: t.UserID, Status: t.Status, AccessToken: t.AccessToken}).Error } else if token.UpdateToken == base { - err = db.Model(&core.Token{Model: gorm.Model{ID: t.ID}}).Update("expired_at", t.ExpiredAt).Error + err = db.Model(&core.Token{Model: gorm.Model{ID: t.ID}}).Updates(core.Token{ExpiredAt: t.ExpiredAt}).Error } else if token.UpdateAll == base { - err = db.Model(&core.Token{Model: gorm.Model{ID: t.ID}}).Update(core.Token{ + err = db.Model(&core.Token{Model: gorm.Model{ID: t.ID}}).Updates(core.Token{ ExpiredAt: t.ExpiredAt, UserID: t.UserID, Status: t.Status, @@ -80,7 +100,12 @@ func Get(base int, input *core.Token) token.ResultDatabase { log.Println("database connection error") return token.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return token.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var tokenStruct []core.Token @@ -93,6 +118,9 @@ func Get(base int, input *core.Token) token.ResultDatabase { Preload("User"). Preload("User.Group"). Find(&tokenStruct).Error + } else if base == token.AccessToken { + err = db.Where("access_token = ? AND admin = ?", input.AccessToken, true). + Find(&tokenStruct).Error } else if base == token.AdminToken { err = db.Where("access_token = ? AND admin = ? AND expired_at > ?", input.AccessToken, true, time.Now()).Find(&tokenStruct).Error @@ -111,7 +139,12 @@ func GetAll() token.ResultDatabase { log.Println("database connection error") return token.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return token.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var tokens []core.Token err = db.Find(&tokens).Error diff --git a/pkg/api/store/user/v0/user.go b/pkg/api/store/user/v0/user.go index 15679753..533bac68 100644 --- a/pkg/api/store/user/v0/user.go +++ b/pkg/api/store/user/v0/user.go @@ -5,7 +5,7 @@ import ( "github.com/homenoc/dsbd-backend/pkg/api/core" "github.com/homenoc/dsbd-backend/pkg/api/core/user" "github.com/homenoc/dsbd-backend/pkg/api/store" - "github.com/jinzhu/gorm" + "gorm.io/gorm" "log" "time" ) @@ -17,7 +17,12 @@ func Create(u *core.User) error { return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Create(&u).Error } @@ -28,7 +33,12 @@ func Delete(u *core.User) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() return db.Delete(u).Error } @@ -39,14 +49,19 @@ func Update(base int, u *core.User) error { log.Println("database connection error") return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error()) + } + defer dbSQL.Close() - var result *gorm.DB + err = nil if user.UpdateVerifyMail == base { - result = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Update(core.User{MailVerify: u.MailVerify}) + err = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Updates(core.User{MailVerify: u.MailVerify}).Error } else if user.UpdateInfo == base { - result = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Update(core.User{ + err = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Updates(core.User{ Name: u.Name, NameEn: u.NameEn, Email: u.Email, @@ -54,13 +69,13 @@ func Update(base int, u *core.User) error { Level: u.Level, MailVerify: u.MailVerify, MailToken: u.MailToken, - }) + }).Error } else if user.UpdateGID == base { - result = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Update(core.User{GroupID: u.GroupID}) + err = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Updates(core.User{GroupID: u.GroupID}).Error } else if user.UpdateLevel == base { - result = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Update("level", u.Level) + err = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Updates(core.User{Level: u.Level}).Error } else if user.UpdateAll == base { - result = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Update(core.User{ + err = db.Model(&core.User{Model: gorm.Model{ID: u.ID}}).Updates(core.User{ GroupID: u.GroupID, Name: u.Name, NameEn: u.NameEn, @@ -70,13 +85,13 @@ func Update(base int, u *core.User) error { MailVerify: u.MailVerify, MailToken: u.MailToken, ExpiredStatus: u.ExpiredStatus, - }) + }).Error } else { log.Println("base select error") return fmt.Errorf("(%s)error: base select\n", time.Now()) } - return result.Error + return err } // value of base can reference from api/core/user/interface.go @@ -86,16 +101,43 @@ func Get(base int, u *core.User) user.ResultDatabase { log.Println("database connection error") return user.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return user.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var userStruct []core.User if base == user.ID { //ID err = db.First(&userStruct, u.ID).Error + } else if base == user.IDDetail { + err = db.Where("id = ?", u.ID). + Preload("Ticket"). + Preload("Ticket.Chat"). + Preload("Group"). + Preload("Group.PaymentMembershipTemplate"). + Preload("Group.PaymentCouponTemplate"). + Preload("Group.Users"). + Preload("Group.Services"). + Preload("Group.Tickets"). + Preload("Group.Tickets.Chat"). + Preload("Group.Services.IP"). + Preload("Group.Services.IP.Plan"). + Preload("Group.Services.Connection"). + Preload("Group.Services.Connection.ConnectionTemplate"). + Preload("Group.Services.Connection.NOC"). + Preload("Group.Services.Connection.BGPRouter"). + Preload("Group.Services.Connection.BGPRouter.NOC"). + Preload("Group.Services.Connection.TunnelEndPointRouterIP"). + Preload("Group.Services.ServiceTemplate"). + Preload("Group.Services.JPNICAdmin"). + Preload("Group.Services.JPNICTech").Find(&userStruct).Error } else if base == user.GID { //GroupID err = db.Where("group_id = ?", u.GroupID).Find(&userStruct).Error } else if base == user.Email { //Mail - err = db.Where("email = ?", u.Email).First(&userStruct).Error + err = db.Where("email = ?", u.Email).Find(&userStruct).Error } else if base == user.MailToken { //Token err = db.Where("mail_token = ?", u.MailToken).Find(&userStruct).Error } else if base == user.GIDAndLevel { //GroupID and Level @@ -113,13 +155,40 @@ func Get(base int, u *core.User) user.ResultDatabase { return user.ResultDatabase{User: userStruct, Err: err} } +// value of base can reference from api/core/user/interface.go +func GetArray(u []uint) user.ResultDatabase { + db, err := store.ConnectDB() + if err != nil { + log.Println("database connection error") + return user.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return user.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() + + var userStruct []core.User + + err = db.Where(u).Find(&userStruct).Error + + return user.ResultDatabase{User: userStruct, Err: err} +} + func GetAll() user.ResultDatabase { db, err := store.ConnectDB() if err != nil { log.Println("database connection error") return user.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} } - defer db.Close() + + dbSQL, err := db.DB() + if err != nil { + log.Printf("database error: %v", err) + return user.ResultDatabase{Err: fmt.Errorf("(%s)error: %s\n", time.Now(), err.Error())} + } + defer dbSQL.Close() var users []core.User err = db.Find(&users).Error