Implemented list, add, update, delete publisher
the build failed Details

This commit is contained in:
konrad 2017-11-21 12:09:45 +01:00 committed by kolaente
parent fb6354ce2c
commit 1d2dfa487c
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
11 changed files with 411 additions and 119 deletions

View File

@ -0,0 +1,232 @@
<template>
<div v-if="user.authenticated">
<h1>Publishers overview</h1>
<div class="ui info message" v-if="loading">
<icon name="refresh" spin></icon>&nbsp;&nbsp;
Loading...
</div>
<div class="ui negative message" v-if="error">
<div class="header">
An error occured.
</div>
{{ error.message }}
<p v-if="error.response.data">
{{ error.response.data.Message }}
</p>
</div>
<div class="ui positive message" v-if="success">
<div class="header">
Success
</div>
{{ success }}
</div>
<div v-if="!loading && !error">
<router-link to="/publishers/add" class="ui green labeled icon button" style="float: right;">
<i class="plus icon"></i>
Add a new publisher
</router-link>
<button @click="loadPublishers()" class="ui teal labeled icon button" style="float: right;">
<i class="refresh icon"></i>
Refresh
</button>
<form id="search">
<div class="ui icon input">
<input placeholder="Search for anything..." type="text" v-model="searchQuery">
<i class="search icon"></i>
</div>
</form>
<paginate
name="publishers"
:list="filteredData"
:per="35"
tag="div"
>
<grid
:data="paginated('publishers')"
:columns="gridColumns"
:buttons="gridButtons"
:btnclick="gridBtnClicked"
>
</grid>
</paginate>
<div class="pagination-container">
<paginate-links
tag="div"
for="publishers"
:hide-single-page="true"
:classes="{
'ul': ['ui', 'pagination', 'menu'],
'li': 'item',
'li a': 'pagination-link'
}"
>
</paginate-links>
<div v-if="$refs.paginator">
Viewing {{$refs.paginator.pageItemsCount}} results
</div>
</div>
</div>
<modal
v-if="showModal"
@close="showModal = false"
v-on:submit="deleteBtnSuccess()">
<span slot="header">Delete this publisher</span>
<p slot="text">Are you sure you want to delete this publisher? This cannot be undone!</p>
</modal>
</div>
</template>
<script>
import auth from '../auth'
import {HTTP} from '../http-common'
import router from '../router'
export default {
name: 'Publishers',
data () {
return {
user: auth.user,
publishers: [],
searchQuery: '',
gridColumns: ['Name'],
gridButtons: [
{
text: 'Delete',
icon: 'trash',
action: this.DeletePublisher,
css: 'ui red icon button'
},
{
text: '',
icon: 'edit',
action: this.editPublisher,
css: 'ui blue icon button'
}
],
loading: false,
paginate: ['publishers'],
error: '',
success: '',
allStatus: [],
showModal: false
}
},
created () {
this.loadPublishers()
},
watch: {
// call again the method if the route changes
'$route': 'loadPublishers'
},
computed: {
filteredData: function () {
var filterKey = this.searchQuery && this.searchQuery.toLowerCase()
var data = this.publishers
if (filterKey) {
data = data.filter(function (row) {
return Object.keys(row).some(function (key) {
if (row[key].content) {
return String(row[key].content).toLowerCase().indexOf(filterKey) > -1
} else {
return String(row[key]).toLowerCase().indexOf(filterKey) > -1
}
})
})
}
return data
}
},
methods: {
loadPublishers () {
this.loading = true
this.publishers = []
HTTP.get(`publishers`)
.then(response => {
let bs = response.data
let i = 0
// Loop throught the data we got from our API and prepare an array to display all authors
for (const b in bs) {
this.publishers[i] = {
ID: {content: bs[b].ID, hide: true}, // Don't show the ID
Name: {content: bs[b].Name, link: '/publisher/' + bs[b].ID} // Add a link to the element
}
// increment dat shit
i++
}
this.loading = false
})
.catch(e => {
this.loading = false
this.error = e
})
},
gridBtnClicked (opt, gridObject) {
opt.action(gridObject)
},
deleteBtnSuccess () { // Event helper function
this.$emit('delete-submit')
},
DeletePublisher (obj) {
this.showModal = true
this.$on('delete-submit', function () {
console.log(obj)
HTTP.delete('publishers/' + obj.ID.content)
.then(response => {
console.log(response)
if (response.status === 200 && response.data.Message === 'success') {
this.success = 'The publisher was deleted successfully.'
this.loadPublishers()
}
})
.catch(e => {
this.error = e
})
this.showModal = false
})
},
editPublisher (publisher) {
router.push({ name: 'publisher-edit', params: { id: publisher.ID.content } })
}
}
}
</script>
<style>
a.pagination-link{
margin: -5px -1.14286em -18px;
display: block;
position: absolute;
cursor: pointer;
padding: 0.928571em 1.14286em;
color: rgba(0,0,0,.87);
-webkit-transition: background-color 200ms; /* Safari */
transition: background-color 200ms;
}
a.pagination-link:hover{
background: rgba(0,0,0,.02);
}
.pagination{
padding: 0;
}
.pagination-container{
margin-top: 1rem;
text-align: center;
}
#search{
margin-bottom: 1rem;
}
</style>

View File

@ -0,0 +1,99 @@
<template>
<div>
<div class="ui negative message" v-if="error">
<div class="header">
An error occured.
</div>
{{ error.message }}
<template v-if="error.response">
<br/>{{ error.response.data.Message }}
</template>
</div>
<div class="ui positive message" v-if="success">
<div class="header">
Success
</div>
{{ success }}
</div>
<form class="ui form" v-bind:class="{ loading: loading }" v-if="!success" @submit.prevent="insertOrUpdatePublisher">
<div class="field">
<label>Name</label>
<input name="Name" placeholder="Name" type="text" v-model="publisher.Name" required>
</div>
<button class="ui blue button" type="submit">Submit</button>
</form>
</div>
</template>
<script>
import {HTTP} from '../http-common'
export default {
name: 'PublishersAddEdit',
data () {
return {
error: '',
success: '',
loading: false,
publisherID: this.$route.params.id,
edit: false,
publisher: {
Name: ''
}
}
},
created () {
this.loading = true
// Look if we're in edit mode and get the publisher infos if nessesary
if (this.publisherID) {
HTTP.get('publishers/' + this.publisherID)
.then(response => {
this.publisher = response.data
this.edit = true
})
.catch(e => {
this.error = e
})
}
this.loading = false
},
methods: {
insertOrUpdatePublisher: function () {
if (this.publisher.Lastname === '') {
this.error = {message: 'Please provide name.'}
} else {
this.loading = true
// Finally Send it
// If we want to newly insert it, make a different request
if (this.edit) {
HTTP.post('publishers/' + this.publisher.ID, {publisher: this.publisher})
.then(response => {
this.loading = false
this.success = 'The publisher was successfully updated!'
this.error = ''
})
.catch(e => {
this.loading = false
this.error = e
})
} else { // insert a new publisher
HTTP.put('publishers', {publisher: this.publisher})
.then(response => {
this.loading = false
this.success = 'The publisher was successfully inserted!'
this.error = ''
})
.catch(e => {
this.loading = false
this.error = e
})
}
}
}
}
}
</script>

View File

@ -6,6 +6,8 @@ import Books from '@/components/Books'
import BooksAddEdit from '@/components/BooksAddEdit'
import Authors from '@/components/Authors'
import AuthorsAddEdit from '@/components/AuthorsAddEdit'
import Publishers from '@/components/Publishers'
import PublishersAddEdit from '@/components/PublishersAddEdit'
Vue.use(Router)
@ -50,6 +52,21 @@ export default new Router({
path: '/authors/:id/edit',
name: 'author-edit',
component: AuthorsAddEdit
},
{
path: '/publishers',
name: 'publishers',
component: Publishers
},
{
path: '/publishers/add',
name: 'publishers-add',
component: PublishersAddEdit
},
{
path: '/publishers/:id/edit',
name: 'publisher-edit',
component: PublishersAddEdit
}
],
linkActiveClass: 'active'

View File

@ -36,7 +36,7 @@ func AddOrUpdateBook(book Book) (newBook Book, err error) {
}
if !exists {
newPublisher, err := AddPublisher(Publisher{Name: book.PublisherFull.Name})
newPublisher, err := AddOrUpdatePublisher(Publisher{Name: book.PublisherFull.Name})
if err != nil {
return Book{}, err
}

View File

@ -1,11 +1,19 @@
package models
// AddPublisher adds a publisher from a publisher struct
func AddPublisher(publisher Publisher) (newPublisher Publisher, err error) {
_, err = x.Insert(&publisher)
// AddOrUpdatePublisher adds or updates a publisher from a publisher struct
func AddOrUpdatePublisher(publisher Publisher) (newPublisher Publisher, err error) {
if publisher.ID == 0 {
_, err = x.Insert(&publisher)
if err != nil {
return Publisher{}, err
if err != nil {
return Publisher{}, err
}
} else {
_, err = x.Where("id = ?", publisher.ID).Update(&publisher)
if err != nil {
return Publisher{}, err
}
}
newPublisher, _, err = GetPublisherByID(publisher.ID)

View File

@ -10,9 +10,6 @@ func DeletePublisherByID(id int64) error {
}
// Set all publisher to 0 on all book with this publisher
//book := Book{Publisher:0}
//book.Publisher = 0
//_, err = x.Where("publisher = ?", id).Update(book)
_, err = x.Table("books").Where("publisher = ?", id).Update(map[string]interface{}{"publisher": 0})
return err

View File

@ -1,15 +0,0 @@
package models
// UpdatePublisher updates a publisher, takes an ID and a publisher struct with the new publisher infos
func UpdatePublisher(publisher Publisher, id int64) (newPublisher Publisher, err error) {
_, err = x.Where("id = ?", id).Update(&publisher)
if err != nil {
return Publisher{}, err
}
// Get the newly updated publisher
newPublisher, _, err = GetPublisherByID(id)
return newPublisher, err
}

View File

@ -1,36 +0,0 @@
package v1
import (
"encoding/json"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strings"
)
// PublisherAdd is the handler to add a publisher
func PublisherAdd(c echo.Context) error {
// Check for Request Content
publisher := c.FormValue("publisher")
if publisher == "" {
return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
}
// Decode the JSON
var publisherstruct models.Publisher
dec := json.NewDecoder(strings.NewReader(publisher))
err := dec.Decode(&publisherstruct)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding publisher: " + err.Error()})
}
// Insert the publisher
newPublisher, err := models.AddPublisher(publisherstruct)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
return c.JSON(http.StatusOK, newPublisher)
}

View File

@ -0,0 +1,47 @@
package v1
import (
"encoding/json"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strings"
"fmt"
)
type publisherPayload struct {
Publisher models.Publisher `json:"publisher" form:"publisher"`
}
// PublisherAddOrUpdate is the handler to add a publisher
func PublisherAddOrUpdate(c echo.Context) error {
// Check for Request Content
publisherFromString := c.FormValue("publisher")
var publisherToInsert models.Publisher
if publisherFromString == "" {
b := new(publisherPayload)
if err := c.Bind(b); err != nil {
fmt.Println(err)
return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
}
publisherToInsert = b.Publisher
} else {
// Decode the JSON
dec := json.NewDecoder(strings.NewReader(publisherFromString))
err := dec.Decode(&publisherToInsert)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding publisher: " + err.Error()})
}
}
// Insert the publisher
newPublisher, err := models.AddOrUpdatePublisher(publisherToInsert)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
return c.JSON(http.StatusOK, newPublisher)
}

View File

@ -1,57 +0,0 @@
package v1
import (
"encoding/json"
"git.mowie.cc/konrad/Library/models"
"github.com/labstack/echo"
"net/http"
"strconv"
"strings"
)
// PublisherUpdate is the handler to update a publishers information
func PublisherUpdate(c echo.Context) error {
// Check for Request Content
publisher := c.FormValue("publisher")
if publisher == "" {
return c.JSON(http.StatusBadRequest, models.Message{"No publisher model provided"})
}
// Look for the publishers id
id := c.Param("id")
// Make int
publisherID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Could not get publisher infos"})
}
// Check if the publisher exists
_, exists, err := models.GetPublisherByID(publisherID)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Could not get publisher infos"})
}
if !exists {
return c.JSON(http.StatusBadRequest, models.Message{"The publisher does not exist."})
}
// Decode the JSON
var publisherstruct models.Publisher
dec := json.NewDecoder(strings.NewReader(publisher))
err = dec.Decode(&publisherstruct)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error decoding publisher: " + err.Error()})
}
// Insert the publisher
newPublisher, err := models.UpdatePublisher(publisherstruct, publisherID)
if err != nil {
return c.JSON(http.StatusInternalServerError, models.Message{"Error"})
}
return c.JSON(http.StatusOK, newPublisher)
}

View File

@ -94,9 +94,9 @@ func RegisterRoutes(e *echo.Echo) {
a.POST("/authors/:id", apiv1.AuthorAddOrUpdate)
// Manage Publishers
a.PUT("/publishers", apiv1.PublisherAdd)
a.PUT("/publishers", apiv1.PublisherAddOrUpdate)
a.DELETE("/publishers/:id", apiv1.PublisherDelete)
a.POST("/publishers/:id", apiv1.PublisherUpdate)
a.POST("/publishers/:id", apiv1.PublisherAddOrUpdate)
// Manage Users