lepisi-pengumuman/assets/js/models/post.js

112 lines
3.4 KiB
JavaScript

let m = require('mithril')
let fecha = require('fecha')
let user = require('./user')
let cookie = require('../others/cookie')
var post = {
loading: false,
list: [],
current: {},
curStatus: 3,
loadList: function() {
post.loading = true
return m.request({
method: 'GET',
url: '/api/pengumuman/?status=' + post.curStatus,
withCredentials: true
})
.then(function(result) {
post.list = result.data
post.list.map(function(p) {
post.validateStatus(p.id)
})
post.loading = false
})
},
loadCurrent: function(id) {
post.loading = true
return m.request({
method: 'GET',
url: '/api/pengumuman/' + id,
withCredentials: true
})
.then(function(result) {
post.current = result.data
post.loading = false
})
},
upload: function() {
post.loading = true
return m.request({
method: 'POST',
url: '/posts/post/' + window.location.search,
data: post.current,
withCredentials: true,
headers: {client: 'api', 'x-query': window.location.search}
})
.then(function(response) {
if (response.status) {
m.route.set(response.route_to)
}
post.current = {}
post.loading = false
window.message = response.message
})
},
save: function() {
post.loading = true
return m.request({
method: 'POST',
url: '/posts/put/' + window.location.search,
data: post.current,
withCredentials: true,
headers: {client: 'api', 'x-query': window.location.search}
})
.then(function(response) {
post.current = {}
if (response.status) {
m.route.set(response.route_to)
}
post.loading = false;
window.message = response.message
})
},
toggleStatus: function(id) {
post.current = _.find(post.list, function(o) { return o.id == id })
if (post.current.status == 2) {
post.current.status = 1
var d = new Date();
post.current.valid_at = fecha.format(new Date(), 'YYYY-MM-DD H:mm:s')
} else if (post.current.status == 1) {
post.current.status = 0
}
post.save()
},
validateStatus: function(id) {
post.current = _.find(post.list, function(o) { return o.id == id })
// console.log(new Date(post.current.valid_at) > new Date());
if (post.current.status != 0) {
if (new Date(post.current.valid_at) > new Date()) {
status = 2
// console.log(post.current.id, 'soon');
} else if (new Date(post.current.valid_at) <= new Date()) {
if (new Date(post.current.expired_at) < new Date()) {
status = 0
// console.log(post.current.id, 'expired');
} else {
status = 1
// console.log(post.current.id, 'active');
}
}
if (post.current.status != status) {
post.current.status = status
post.save()
}
}
// console.log(post.current);
}
}
module.exports = post